java实现后台自动发邮件功能spring利用javamail,quartz定时发送邮件

ko22223 贡献于2012-01-12

作者 宝宝工作室  创建于2011-04-09 03:23:00   修改者宝宝工作室  修改于2011-04-09 03:42:00字数58497

文档摘要:java实现后台自动发邮件功能spring利用javamail,quartz定时发送邮件
关键词:

 spring和quartz进行定时邮件发送 收集 文章分类:Java编程 关于Spring的邮件发送的功能演示: 参见:      http://java123.blog.51cto.com/397472/81237     http://wmswu.javaeye.com/blog/200412     http://blog.sina.com.cn/s/blog_612205540100ehlh.html (我把程序中一些敏感的地方替换成了其他的文字,直接调试肯定不行,只是给大家一个参考)   需要用到的jar包是   spring-context.jar   mail.jar   spring-core.jar   activation.jar   commons-logging.jar    quartz-all-1.6.0.jar (定时器所需要的包)  这些是程序必须要用到的包。 1:简单邮件 简单邮件中是可以实现邮件群发的功能的,区别是收件人可以是一个数组。 Java代码   1. package com;         2. import org.springframework.mail.SimpleMailMessage;         3. import org.springframework.mail.javamail.JavaMailSenderImpl;         4. /**     5.  * 本类测试简单邮件     6.  *      7.  * @author sunny     8.  *      9.  */         10. public class SingleMailSend {         11.     public static void main(String args[]){         12.         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();         13. //      设定mail server       14.         senderImpl.setHost("192.168.1.1");         15.         senderImpl.setUsername("username");         16.         senderImpl.setPassword("password");         17.       18.       19. //      建立邮件消息       20.         SimpleMailMessage mailMessage = new SimpleMailMessage();         21. //      设置收件人,寄件人       22.         // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"};       23. //      mailMessage.setTo(array);       24.         mailMessage.setTo("sun111@163.com");         25.         mailMessage.setFrom("webadmin@163.com");         26.         mailMessage.setSubject("测试邮件群发!");         27.         mailMessage.setText("测试我的简单邮件发送机制!!");         28.       29. //      发送邮件       30.         senderImpl.send(mailMessage);         31.       32.         System.out.println("邮件发送成功.....");         33.     }         34. }      package com; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; /** * 本类测试简单邮件 * * @author sunny * */ public class SingleMailSend { public static void main(String args[]){ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 设定mail server senderImpl.setHost("192.168.1.1"); senderImpl.setUsername("username"); senderImpl.setPassword("password"); // 建立邮件消息 SimpleMailMessage mailMessage = new SimpleMailMessage(); // 设置收件人,寄件人 // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"}; // mailMessage.setTo(array); mailMessage.setTo("sun111@163.com"); mailMessage.setFrom("webadmin@163.com"); mailMessage.setSubject("测试邮件群发!"); mailMessage.setText("测试我的简单邮件发送机制!!"); // 发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } } 、 2:HTML邮件的发送 Java代码   1. package com;       2.       3. import javax.mail.internet.MimeMessage;       4. import org.springframework.mail.javamail.JavaMailSenderImpl;       5. import org.springframework.mail.javamail.MimeMessageHelper;       6.       7. /**      8.  * 本类测试html邮件      9.  * @author sunny      10.  *      11.  */      12. public class HTMLMailDemo {       13.     /**      14.      * @param args      15.      */      16.     public static void main(String[] args) throws Exception {       17.         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();       18.       19.         //设定mail server         20.         senderImpl.setHost("192.168.1.1");       21.         senderImpl.setUsername("username");       22.         senderImpl.setPassword("password");       23.       24.         //建立邮件消息,发送简单邮件和html邮件的区别         25.         MimeMessage mailMessage = senderImpl.createMimeMessage();       26.         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);       27.       28.         //设置收件人,寄件人         29.         messageHelper.setTo("sun111@163.com");       30.         messageHelper.setFrom("webadmin@163.com");       31.         messageHelper.setSubject("测试HTML邮件!");       32.         //true 表示启动HTML格式的邮件         33.         messageHelper       34.                 .setText(       35.                         "

hello!!zhangjian

",       36.                         true);       37.       38.         //发送邮件         39.         senderImpl.send(mailMessage);       40.       41.         System.out.println("邮件发送成功.....");       42.     }       43. }      44.  3:本类测试邮件中嵌套图片    45. package com;       46.       47. import java.io.File;       48. import javax.mail.internet.MimeMessage;       49. import org.springframework.core.io.FileSystemResource;       50. import org.springframework.mail.javamail.JavaMailSenderImpl;       51. import org.springframework.mail.javamail.MimeMessageHelper;       52.       53. /**      54.  * 本类测试邮件中嵌套图片      55.  * @author sunny      56.  *      57.  */      58. public class AttachedImageMail {       59.     public static void main(String[] args) throws Exception{         60.    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();         61.             62.    //设定mail server         63.    senderImpl.setHost("192.168.1.2");         64.    senderImpl.setUsername("username");         65.    senderImpl.setPassword("pssword");         66.    //建立邮件消息,发送简单邮件和html邮件的区别         67.    MimeMessage mailMessage = senderImpl.createMimeMessage();         68.    //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,            69.  multipart模式         70.    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);         71.             72.    //设置收件人,寄件人         73.    messageHelper.setTo("sun111@163.com");         74.    messageHelper.setFrom("webadmin@163.com");         75.    messageHelper.setSubject("测试邮件中嵌套图片!!");         76.    //true 表示启动HTML格式的邮件         77.    messageHelper.setText("

hello!!zhangjian

" +         78.      "",true);         79.               80.    FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg"));         81.             82.    messageHelper.addInline("aaa",img);         83.             84.    //发送邮件         85.    senderImpl.send(mailMessage);         86.             87.    System.out.println("邮件发送成功.....");         88.   }       89. }      90.    91.
   92.
   package com; import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 本类测试html邮件 * @author sunny * */ public class HTMLMailDemo { /** * @param args */ public static void main(String[] args) throws Exception { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); //设定mail server senderImpl.setHost("192.168.1.1"); senderImpl.setUsername("username"); senderImpl.setPassword("password"); //建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); //设置收件人,寄件人 messageHelper.setTo("sun111@163.com"); messageHelper.setFrom("webadmin@163.com"); messageHelper.setSubject("测试HTML邮件!"); //true 表示启动HTML格式的邮件 messageHelper .setText( "

hello!!zhangjian

", true); //发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } } 3:本类测试邮件中嵌套图片 Java代码   1. package com;       2.       3. import java.io.File;       4. import javax.mail.internet.MimeMessage;       5. import org.springframework.core.io.FileSystemResource;       6. import org.springframework.mail.javamail.JavaMailSenderImpl;       7. import org.springframework.mail.javamail.MimeMessageHelper;       8.       9. /**      10.  * 本类测试邮件中嵌套图片      11.  * @author sunny      12.  *      13.  */      14. public class AttachedImageMail {       15.     public static void main(String[] args) throws Exception{         16.    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();         17.             18.    //设定mail server         19.    senderImpl.setHost("192.168.1.2");         20.    senderImpl.setUsername("username");         21.    senderImpl.setPassword("pssword");         22.    //建立邮件消息,发送简单邮件和html邮件的区别         23.    MimeMessage mailMessage = senderImpl.createMimeMessage();         24.    //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,            25.  multipart模式         26.    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);         27.             28.    //设置收件人,寄件人         29.    messageHelper.setTo("sun111@163.com");         30.    messageHelper.setFrom("webadmin@163.com");         31.    messageHelper.setSubject("测试邮件中嵌套图片!!");         32.    //true 表示启动HTML格式的邮件         33.    messageHelper.setText("

hello!!zhangjian

" +         34.      "",true);         35.               36.    FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg"));         37.             38.    messageHelper.addInline("aaa",img);         39.             40.    //发送邮件         41.    senderImpl.send(mailMessage);         42.             43.    System.out.println("邮件发送成功.....");         44.   }       45. }     package com; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 本类测试邮件中嵌套图片 * @author sunny * */ public class AttachedImageMail { public static void main(String[] args) throws Exception{ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); //设定mail server senderImpl.setHost("192.168.1.2"); senderImpl.setUsername("username"); senderImpl.setPassword("pssword"); //建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用, multipart模式 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); //设置收件人,寄件人 messageHelper.setTo("sun111@163.com"); messageHelper.setFrom("webadmin@163.com"); messageHelper.setSubject("测试邮件中嵌套图片!!"); //true 表示启动HTML格式的邮件 messageHelper.setText("

hello!!zhangjian

" + "",true); FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg")); messageHelper.addInline("aaa",img); //发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } } 4:  测试邮件中包含附件 Java代码   1. package com;       2.       3. import java.io.File;       4. import javax.mail.internet.MimeMessage;       5. import org.springframework.core.io.FileSystemResource;       6. import org.springframework.mail.javamail.JavaMailSenderImpl;       7. import org.springframework.mail.javamail.MimeMessageHelper;       8.       9. public class AttachedFileMail {       10.     /**     11.      * 本类测试的是关于邮件中带有附件的例子     12.      *      13.      * @param args     14.      */      15.     public static void main(String[] args) throws Exception{         16.         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();         17.       18.         // 设定mail server       19.         senderImpl.setHost("192.168.1.2");         20.         senderImpl.setUsername("username");         21.         senderImpl.setPassword("password");         22.         // 建立邮件消息,发送简单邮件和html邮件的区别       23.         MimeMessage mailMessage = senderImpl.createMimeMessage();         24.         // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,       25.         ultipart模式         26.         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);         27.       28.         // 设置收件人,寄件人       29.         messageHelper.setTo("sun111@163.com");         30.         messageHelper.setFrom("webadmin@163.com");         31.         messageHelper.setSubject("测试邮件中上传附件!!");         32.         // true 表示启动HTML格式的邮件       33.         messageHelper.setText("

你好:附件中有关于CSS的学习资料!

",true);         34.       35.         FileSystemResource file = new FileSystemResource(new File("d:/CSS110.rar"));         36.         // 这里的方法调用和插入图片是不同的。       37.         messageHelper.addAttachment("CSS110.rar",file);         38.       39.         // 发送邮件       40.         senderImpl.send(mailMessage);         41.       42.         System.out.println("邮件发送成功.....");         43.     }       44. }     package com; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class AttachedFileMail { /** * 本类测试的是关于邮件中带有附件的例子 * * @param args */ public static void main(String[] args) throws Exception{ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 设定mail server senderImpl.setHost("192.168.1.2"); senderImpl.setUsername("username"); senderImpl.setPassword("password"); // 建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用, ultipart模式 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); // 设置收件人,寄件人 messageHelper.setTo("sun111@163.com"); messageHelper.setFrom("webadmin@163.com"); messageHelper.setSubject("测试邮件中上传附件!!"); // true 表示启动HTML格式的邮件 messageHelper.setText("

你好:附件中有关于CSS的学习资料!

",true); FileSystemResource file = new FileSystemResource(new File("d:/CSS110.rar")); // 这里的方法调用和插入图片是不同的。 messageHelper.addAttachment("CSS110.rar",file); // 发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } } 5.spring和quartz进行定时邮件发送 一  发送邮件的基类: Java代码   1.    web服务器启动后,程序会按时间定时执行。 详见:http://happymen001.javaeye.com/admin/blogs/580099 下面附定时器的时间配置例子: 0 27 14 * * ?      一些例子 "0 0 12 * * ?" 每天中午12点触发 "0 15 10 ? * *" 每天上午10:15触发 "0 15 10 * * ?" 每天上午10:15触发 "0 15 10 * * ? *" 每天上午10:15触发 "0 15 10 * * ? 2005" 2005年的每天上午10:15触发 "0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发 "0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发 "0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发 "0 15 10 15 * ?" 每月15日上午10:15触发 "0 15 10 L * ?" 每月最后一日的上午10:15触发 "0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 "0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发 "0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发 如果缺少  quartz-all-1.6.0.jar  包可能就会报 ERROR] main 2010-01-26 10:43:15,034 org.springframework.web.context.ContextLoader     - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodInvokingJobDetail' defined in ServletContext resource [/WEB-INF/classes/config/spring/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org.quartz.JobExecutionException Caused by: java.lang.NoClassDefFoundError: org.quartz.JobExecutionException at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean.class$(MethodInvokingJobDetailFactoryBean.java:83) at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean.(MethodInvokingJobDetailFactoryBean.java:82) spring利用javamail,quartz定时发送邮件 spring提供的定时发送邮件功能一直深受广大web开发者的喜爱,最近忙里偷闲,自己写了个简单的例子以供大家参考, 首先从spring配置文件开始吧:                                                                                                    sendTimeSheetAlert                                                                                                                          0 0 0 ? * 5                                                                                                                                                         Java代码: 你讲在下面的代码中找到上面红色标注的那个方法 package com.mdcl.timecard.mail.impl; /** * Title: mail * * @Company: company * @author: myjavaword * @version: 1.0 * @time: 2008.4.22 * @Copyright: Copyright (c) 2008,dmcl. All Rights Reserved. */ import java.util.ArrayList; import java.util.List; import javax.mail.MessagingException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.mdcl.timecard.action.BaseAction; import com.mdcl.timecard.mail.IMailManager; import com.mdcl.timecard.po.Resource; import com.mdcl.timecard.service.IResourceService; import com.mdcl.timecard.util.StringUtil; import com.mdcl.timecard.util.SystemManager; public class MailManager  implements IMailManager {     SimpleHtmlMailSender messageSender;     private static final Logger logger = Logger.getLogger(MailManager.class);          public void sendMail() {        } /** * 发送填写timesheet通知邮件 */     public void sendTimeSheetAlert() {   //获取资源列表   List list = new ArrayList();   //从配置文件获取发件人   String emailfrom = SystemManager.getInstance().getPropValue("emailfrom");   //从配置文件获取连接地址   String wabappurl = SystemManager.getInstance().getPropValue("wabappurl");   String text = "please add timesheet!";   // 取出所有资源做循环   Resource resource = new Resource();   resource.setEmail("verygoodverypowerful@gmail.com");   list.add(resource);   int i = 0;   for (Resource listElement : list) {       if(StringUtils.isNotBlank(listElement.getEmail())){     messageSender.sendMessage(listElement.getEmail(), emailfrom, "please Add timesheet", text);     logger.info("系统已经通知用户:"+listElement.getName()+"填写本周timesheet 。email:"+listElement.getEmail()+"已经发送成功。");       }     }     }      public SimpleHtmlMailSender getMessageSender() {              return messageSender;     }     public void setMessageSender(SimpleHtmlMailSender   messageSender) {              this.messageSender = messageSender;     } } IMailManager.java: package com.mdcl.timecard.mail; /** * Title: mail * * @Company: company * @author:myjavaword * @version: 1.0 * @time: 2008.4.22 * @Copyright: Copyright (c) 2008,dmcl. All Rights Reserved. */ public interface IMailManager { /** * 发送email */ void sendMail(); /** * 发送填写TimeSheet通知emial * @param mailMessage */ void sendTimeSheetAlert(); } BaseMailSender.java package com.mdcl.timecard.mail.impl; /** * Title: mail * * @Company: company * @author: myjavaword * @version: 1.0 * @time: 2008.4.22 * @Copyright: Copyright (c) 2008,dmcl. All Right s Reserved. */ import org.springframework.mail.javamail.JavaMailSender; public abstract class BaseMailSender { protected String to; protected String from; protected String subject; protected JavaMailSender sender;//当发送MIMI消息时用到的类 public void setTo(String to) {   this.to = to; } public void setFrom(String from) {   this.from = from; } public void setSubject(String subject) {   this.subject = subject; } public void setJavaMailSender(JavaMailSender sender) {   this.sender = sender; } } 配置文件 mail.properties mail.host=xxxx mail.username=xxxx mail.password=xxxx conf.properties emailfrom=Emali地址 emailto=Email地址 wabappurl = 填写链接ui 关于Spring的邮件发送的功能演示: (我把程序中一些敏感的地方替换成了其他的文字,直接调试肯定不行,只是给大家一个参考)   需要用到的jar包是   spring-context.jar   mail.jar   spring-core.jar   activation.jar   commons-logging.jar   这些是程序必须要用到的包。   1:简单邮件  简单邮件中是可以实现邮件群发的功能的,区别是收件人可以是一个数组。 Java代码   1. package com;      2. import org.springframework.mail.SimpleMailMessage;      3. import org.springframework.mail.javamail.JavaMailSenderImpl;      4. /**   5.  * 本类测试简单邮件   6.  *    7.  * @author sunny   8.  *    9.  */      10. public class SingleMailSend {      11.     public static void main(String args[]){      12.         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();      13. //      设定mail server    14.         senderImpl.setHost("192.168.1.1");      15.         senderImpl.setUsername("username");      16.         senderImpl.setPassword("password");      17.    18.    19. //      建立邮件消息    20.         SimpleMailMessage mailMessage = new SimpleMailMessage();      21. //      设置收件人,寄件人    22.         // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"};    23. //      mailMessage.setTo(array);    24.         mailMessage.setTo("sun111@163.com");      25.         mailMessage.setFrom("webadmin@163.com");      26.         mailMessage.setSubject("测试邮件群发!");      27.         mailMessage.setText("测试我的简单邮件发送机制!!");      28.    29. //      发送邮件    30.         senderImpl.send(mailMessage);      31.    32.         System.out.println("邮件发送成功.....");      33.     }      34. }    package com; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; /** * 本类测试简单邮件 * * @author sunny * */ public class SingleMailSend { public static void main(String args[]){ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 设定mail server senderImpl.setHost("192.168.1.1"); senderImpl.setUsername("username"); senderImpl.setPassword("password"); // 建立邮件消息 SimpleMailMessage mailMessage = new SimpleMailMessage(); // 设置收件人,寄件人 // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"}; // mailMessage.setTo(array); mailMessage.setTo("sun111@163.com"); mailMessage.setFrom("webadmin@163.com"); mailMessage.setSubject("测试邮件群发!"); mailMessage.setText("测试我的简单邮件发送机制!!"); // 发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } }  2:HTML邮件的发送 Java代码   1. package com;    2.    3. import javax.mail.internet.MimeMessage;    4. import org.springframework.mail.javamail.JavaMailSenderImpl;    5. import org.springframework.mail.javamail.MimeMessageHelper;    6.    7. /**    8.  * 本类测试html邮件    9.  * @author sunny    10.  *    11.  */   12. public class HTMLMailDemo {    13.     /**    14.      * @param args    15.      */   16.     public static void main(String[] args) throws Exception {    17.         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();    18.    19.         //设定mail server      20.         senderImpl.setHost("192.168.1.1");    21.         senderImpl.setUsername("username");    22.         senderImpl.setPassword("password");    23.    24.         //建立邮件消息,发送简单邮件和html邮件的区别      25.         MimeMessage mailMessage = senderImpl.createMimeMessage();    26.         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);    27.    28.         //设置收件人,寄件人      29.         messageHelper.setTo("sun111@163.com");    30.         messageHelper.setFrom("webadmin@163.com");    31.         messageHelper.setSubject("测试HTML邮件!");    32.         //true 表示启动HTML格式的邮件      33.         messageHelper    34.                 .setText(    35.                         "

hello!!zhangjian

",    36.                         true);    37.    38.         //发送邮件      39.         senderImpl.send(mailMessage);    40.    41.         System.out.println("邮件发送成功.....");    42.     }    43. }   package com; import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 本类测试html邮件 * @author sunny * */ public class HTMLMailDemo { /** * @param args */ public static void main(String[] args) throws Exception { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); //设定mail server senderImpl.setHost("192.168.1.1"); senderImpl.setUsername("username"); senderImpl.setPassword("password"); //建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); //设置收件人,寄件人 messageHelper.setTo("sun111@163.com"); messageHelper.setFrom("webadmin@163.com"); messageHelper.setSubject("测试HTML邮件!"); //true 表示启动HTML格式的邮件 messageHelper .setText( "

hello!!zhangjian

", true); //发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } }  3:本类测试邮件中嵌套图片 Java代码   1. package com;    2.    3. import java.io.File;    4. import javax.mail.internet.MimeMessage;    5. import org.springframework.core.io.FileSystemResource;    6. import org.springframework.mail.javamail.JavaMailSenderImpl;    7. import org.springframework.mail.javamail.MimeMessageHelper;    8.    9. /**    10.  * 本类测试邮件中嵌套图片    11.  * @author sunny    12.  *    13.  */   14. public class AttachedImageMail {    15.     public static void main(String[] args) throws Exception{      16.    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();      17.          18.    //设定mail server      19.    senderImpl.setHost("192.168.1.2");      20.    senderImpl.setUsername("username");      21.    senderImpl.setPassword("pssword");      22.    //建立邮件消息,发送简单邮件和html邮件的区别      23.    MimeMessage mailMessage = senderImpl.createMimeMessage();      24.    //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,         25.  multipart模式      26.    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);      27.          28.    //设置收件人,寄件人      29.    messageHelper.setTo("sun111@163.com");      30.    messageHelper.setFrom("webadmin@163.com");      31.    messageHelper.setSubject("测试邮件中嵌套图片!!");      32.    //true 表示启动HTML格式的邮件      33.    messageHelper.setText("

hello!!zhangjian

" +      34.      "",true);      35.            36.    FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg"));      37.          38.    messageHelper.addInline("aaa",img);      39.          40.    //发送邮件      41.    senderImpl.send(mailMessage);      42.          43.    System.out.println("邮件发送成功.....");      44.   }    45. }   package com; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 本类测试邮件中嵌套图片 * @author sunny * */ public class AttachedImageMail { public static void main(String[] args) throws Exception{ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); //设定mail server senderImpl.setHost("192.168.1.2"); senderImpl.setUsername("username"); senderImpl.setPassword("pssword"); //建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用, multipart模式 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); //设置收件人,寄件人 messageHelper.setTo("sun111@163.com"); messageHelper.setFrom("webadmin@163.com"); messageHelper.setSubject("测试邮件中嵌套图片!!"); //true 表示启动HTML格式的邮件 messageHelper.setText("

hello!!zhangjian

" + "",true); FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg")); messageHelper.addInline("aaa",img); //发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } }  4:  测试邮件中包含附件 Java代码   1. package com;    2.    3. import java.io.File;    4. import javax.mail.internet.MimeMessage;    5. import org.springframework.core.io.FileSystemResource;    6. import org.springframework.mail.javamail.JavaMailSenderImpl;    7. import org.springframework.mail.javamail.MimeMessageHelper;    8.    9. public class AttachedFileMail {    10.     /**   11.      * 本类测试的是关于邮件中带有附件的例子   12.      *    13.      * @param args   14.      */   15.     public static void main(String[] args) throws Exception{      16.         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();      17.    18.         // 设定mail server    19.         senderImpl.setHost("192.168.1.2");      20.         senderImpl.setUsername("username");      21.         senderImpl.setPassword("password");      22.         // 建立邮件消息,发送简单邮件和html邮件的区别    23.         MimeMessage mailMessage = senderImpl.createMimeMessage();      24.         // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,    25.         ultipart模式      26.         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);      27.    28.         // 设置收件人,寄件人    29.         messageHelper.setTo("sun111@163.com");      30.         messageHelper.setFrom("webadmin@163.com");      31.         messageHelper.setSubject("测试邮件中上传附件!!");      32.         // true 表示启动HTML格式的邮件    33.         messageHelper.setText("

你好:附件中有关于CSS的学习资料!

",true);      34.    35.         FileSystemResource file = new FileSystemResource(new File("d:/CSS110.rar"));      36.         // 这里的方法调用和插入图片是不同的。    37.         messageHelper.addAttachment("CSS110.rar",file);      38.    39.         // 发送邮件    40.         senderImpl.send(mailMessage);      41.    42.         System.out.println("邮件发送成功.....");      43.     }    44. }   package com; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class AttachedFileMail { /** * 本类测试的是关于邮件中带有附件的例子 * * @param args */ public static void main(String[] args) throws Exception{ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 设定mail server senderImpl.setHost("192.168.1.2"); senderImpl.setUsername("username"); senderImpl.setPassword("password"); // 建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用, ultipart模式 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); // 设置收件人,寄件人 messageHelper.setTo("sun111@163.com"); messageHelper.setFrom("webadmin@163.com"); messageHelper.setSubject("测试邮件中上传附件!!"); // true 表示启动HTML格式的邮件 messageHelper.setText("

你好:附件中有关于CSS的学习资料!

",true); FileSystemResource file = new FileSystemResource(new File("d:/CSS110.rar")); // 这里的方法调用和插入图片是不同的。 messageHelper.addAttachment("CSS110.rar",file); // 发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功....."); } } 5.spring和quartz进行定时邮件发送 一  发送邮件的基类: Java代码   1. package com.spring.mail;    2.    3. import org.springframework.mail.MailSender;    4.    5. //import org.springframework.mail.javamail.JavaMailSender;       6.    7. public abstract class BaseMailSender {    8.     protected String to;    9.    10.     protected String from;    11.    12.     protected String subject;    13.    14.     protected MailSender sender;    15.    16.     //当发送的邮件为简单邮件时用MailSender即可;      17.    18.     //protected JavaMailSender sender;      19.     //当发送的邮件为MIMI时用JavaMailSender      20.     public void setTo(String to) {    21.         this.to = to;    22.     }    23.    24.     public void setFrom(String from) {    25.         this.from = from;    26.     }    27.    28.     public void setSubject(String subject) {    29.         this.subject = subject;    30.     }    31.    32.     public void setJavaMailSender(MailSender sender) {//(JavaMailSender sender) {      33.         this.sender = sender;    34.     }    35. }   package com.spring.mail; import org.springframework.mail.MailSender; //import org.springframework.mail.javamail.JavaMailSender; public abstract class BaseMailSender { protected String to; protected String from; protected String subject; protected MailSender sender; //当发送的邮件为简单邮件时用MailSender即可; //protected JavaMailSender sender; //当发送的邮件为MIMI时用JavaMailSender public void setTo(String to) { this.to = to; } public void setFrom(String from) { this.from = from; } public void setSubject(String subject) { this.subject = subject; } public void setJavaMailSender(MailSender sender) {//(JavaMailSender sender) { this.sender = sender; } }  发送邮件调用的类 Java代码   1. package com.spring.mail;    2.    3. import javax.mail.MessagingException;    4.    5. import org.springframework.context.support.ClassPathXmlApplicationContext;    6. import org.springframework.mail.SimpleMailMessage;    7.    8. public class SimpleHtmlMailSender extends BaseMailSender {    9.    10.     public void sendMessage() throws MessagingException {    11.         String textStr = "Helo!!!!!!!!!!!";//发送邮件的消息主体        12.         SimpleMailMessage msg = new SimpleMailMessage();    13.         msg.setTo(to);    14.         msg.setFrom(from);    15.         msg.setSubject(subject);    16.         msg.setText(textStr);    17.         sender.send(msg);    18.     }    19.    20.     public void doIt() throws Exception {    21.    22.         ClassPathXmlApplicationContext ctx1 = new ClassPathXmlApplicationContext(    23.                 new String[] { "ApplicationContext.xml" });    24.         SimpleHtmlMailSender sender = (SimpleHtmlMailSender) ctx1    25.                 .getBean("messageSender");    26.    27.         sender.sendMessage();    28.         System.out.println("发送成功");    29.     }    30. }   package com.spring.mail; import javax.mail.MessagingException; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mail.SimpleMailMessage; public class SimpleHtmlMailSender extends BaseMailSender { public void sendMessage() throws MessagingException { String textStr = "Helo!!!!!!!!!!!";//发送邮件的消息主体 SimpleMailMessage msg = new SimpleMailMessage(); msg.setTo(to); msg.setFrom(from); msg.setSubject(subject); msg.setText(textStr); sender.send(msg); } public void doIt() throws Exception { ClassPathXmlApplicationContext ctx1 = new ClassPathXmlApplicationContext( new String[] { "ApplicationContext.xml" }); SimpleHtmlMailSender sender = (SimpleHtmlMailSender) ctx1 .getBean("messageSender"); sender.sendMessage(); System.out.println("发送成功"); } }  配置文件ApplicationContext: Xml代码   1.        2.       3.       4.       5.        6.         7.    smtp.163.com      8.         9.          10.     tomcat0506      11.         12.         13.    wes      14.         15.                16.           17.      true      18.           19.                20.   
      21.         22.         23.          24.           25.           26.    wes830506@126.com      27.           28.           29.     tomcat0506@163.com      30.           31.         32.    test      33.           34.          35.       36.       37.               38.         39.         40.          43.       44.                 45.   doIt       46.       47.         48.       49.        50.         51.         52.          53.    3000      54.         55.         56.          57.    6000      58.         59.         60.       61.       62.        63.          64.    0 0 6,12,20 * * ?          65.         66.       67.         68.         69.           70.           71.           72.            73.        74.    smtp.163.com tomcat0506 wes true wes830506@126.com tomcat0506@163.com test doIt 3000 6000 0 0 6,12,20 * * ?  二  mimi邮件发送   在编写发送邮件程序时需要用到的类有一下几个:  org.springframework.mail.javamail.JavaMailSender;  //此类继承了spring里面的  //MailSender接口--定义了两个简单的sender方法,用于发送简单的邮件信息,参数类型为:SimpleMailMessage([])  //JavaMailSender类继承了上面方法后支持MIMI邮件,可以发MIMI消息  org.springframework.context.support.ClassPathXmlApplicationContext;  //spring里面读取配置文件时需要用到的类  org.springframework.mail.javamail.MimeMessageHelper;  //在发送MIMI消息时需要用到的辅助类    javax.mail.MessagingException;    javax.mail.internet.MimeMessage;  //J2EE里面支持发送MIMe信息需要的类 例子: 发送邮件的基类 BaseMailSender  .java:   Java代码   1. import org.springframework.mail.javamail.JavaMailSender;    2.    3. public abstract class BaseMailSender {    4.     protected String to;    5.     protected String from;    6.     protected String subject;    7.     protected JavaMailSender sender;//当发送MIMI消息时用到的类      8.    9.     public void setTo(String to) {    10.         this.to = to;    11.     }    12.    13.     public void setFrom(String from) {    14.         this.from = from;    15.     }    16.    17.     public void setSubject(String subject) {    18.         this.subject = subject;    19.     }    20.    21.     public void setJavaMailSender(JavaMailSender sender) {    22.         this.sender = sender;    23.     }    24. }   import org.springframework.mail.javamail.JavaMailSender; public abstract class BaseMailSender { protected String to; protected String from; protected String subject; protected JavaMailSender sender;//当发送MIMI消息时用到的类 public void setTo(String to) { this.to = to; } public void setFrom(String from) { this.from = from; } public void setSubject(String subject) { this.subject = subject; } public void setJavaMailSender(JavaMailSender sender) { this.sender = sender; } }  发送邮件的类: Java代码   1. package com.spring.mail;    2.    3. import javax.mail.MessagingException;    4. import javax.mail.internet.MimeMessage;    5.    6. import org.springframework.context.support.ClassPathXmlApplicationContext;    7. import org.springframework.mail.SimpleMailMessage;    8. import org.springframework.mail.javamail.MimeMessageHelper;    9.    10. public class SimpleHtmlMailSender extends BaseMailSender {    11.    12.     public void sendMessage() throws MessagingException {    13.    14.         //String htmlHead = "";      15.         //String htmlBody = "";      16.         //String htmlEnd = "";      17.         // StringBuffer mailMessage = new StringBuffer();      18.         //mailMessage.append(htmlHead);      19.         //mailMessage.append(htmlBody);      20.         //mailMessage.append(htmlEnd);      21.    22.         //当发送的邮件为简单邮件时注销此句        23.         String textStr = "

^_^!

";    24.    25.         //String textStr = "Helo could you see this email?";//发送邮件的消息主体      26.    27.         //SimpleMailMessage msg = new SimpleMailMessage();      28.    29.         //当发送邮件为简单邮件时把此句注销即可      30.    31.         MimeMessage msg = sender.createMimeMessage();    32.         MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GB2312");    33.    34.         helper.setTo(to);    35.         helper.setFrom(from);    36.         helper.setSubject(subject);    37.         helper.setText(textStr, true);    38.         /*    39.         msg.setTo(to);    40.         msg.setFrom(from);    41.         msg.setSubject(subject);    42.         msg.setText(textStr);    43.          */   44.         sender.send(msg);    45.     }    46.    47.     public void doIt() throws Exception {//static void main(String[] args) throws Exception {//      48.         //ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "springexample-creditaccount.xml" });      49.    50.         ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(    51.                 new String[] { "ApplicationContext.xml" });    52.    53.         SimpleHtmlMailSender sender = (SimpleHtmlMailSender) ctx    54.                 .getBean("messageSender");    55.         sender.sendMessage();    56.         System.out.println("发送成功");    57.     }    58. }   package com.spring.mail; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.MimeMessageHelper; public class SimpleHtmlMailSender extends BaseMailSender { public void sendMessage() throws MessagingException { //String htmlHead = ""; //String htmlBody = ""; //String htmlEnd = ""; // StringBuffer mailMessage = new StringBuffer(); //mailMessage.append(htmlHead); //mailMessage.append(htmlBody); //mailMessage.append(htmlEnd); //当发送的邮件为简单邮件时注销此句 String textStr = "

^_^!

"; //String textStr = "Helo could you see this email?";//发送邮件的消息主体 //SimpleMailMessage msg = new SimpleMailMessage(); //当发送邮件为简单邮件时把此句注销即可 MimeMessage msg = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GB2312"); helper.setTo(to); helper.setFrom(from); helper.setSubject(subject); helper.setText(textStr, true); /* msg.setTo(to); msg.setFrom(from); msg.setSubject(subject); msg.setText(textStr); */ sender.send(msg); } public void doIt() throws Exception {//static void main(String[] args) throws Exception {// //ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "springexample-creditaccount.xml" }); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] { "ApplicationContext.xml" }); SimpleHtmlMailSender sender = (SimpleHtmlMailSender) ctx .getBean("messageSender"); sender.sendMessage(); System.out.println("发送成功"); } }  配置文件同上! 关于Spring的邮件发送的功能演示: (下面是我自己写的一个可以发送简单邮件和附件的邮件功能,可以改换邮箱后直接使用)   需要用到的jar包是   spring-context.jar   mail-1.4.jar   spring-core.jar   activation.jar   commons-logging.jar   这些是程序必须要用到的包。 1.BaseMailSender.java package com.trisun.T82A.java.mail; import org.springframework.mail.javamail.JavaMailSender; public abstract class BaseMailSender {  protected String to;  protected String from;  protected String subject;  protected JavaMailSender sender;//当发送MIMI消息时用到的类  public void setTo(String to) {   this.to = to;  }  public void setFrom(String from) {   this.from = from;  }  public void setSubject(String subject) {   this.subject = subject;  }  public void setJavaMailSender(JavaMailSender sender) {   this.sender = sender;  } } 2.SimpleHtmlMailSender.java package com.trisun.T82A.java.mail; import java.io.File; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.MimeMessageHelper; public class SimpleHtmlMailSender extends BaseMailSender{  public  void sendMessage() throws MessagingException {           //当发送的邮件为简单邮件时注销此句    String textStr = "

^_^!

";   //String textStr = "Helo could you see this email?";//发送邮件的消息主体     //SimpleMailMessage msg = new SimpleMailMessage();     //当发送邮件为简单邮件时把此句注销即可     MimeMessage msg = sender.createMimeMessage();   MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");     helper.setTo(to);   helper.setFrom(from);   helper.setSubject(subject);  // helper.addAttachment("a.doc", new ClassPathResource("/a.doc"));   FileSystemResource file = new FileSystemResource(new File("d:/mail/b.rar"));     // 这里的方法调用和插入图片是不同的。     helper.addAttachment("b.rar",file);   helper.setText(textStr, true);   sender.send(msg);  }  } 3.SpringSendMail.java package com.trisun.T82A.java.mail; import java.util.TimerTask; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mail.javamail.JavaMailSenderImpl;  public class SpringSendMail{      public SimpleHtmlMailSender messageSender;  public SimpleHtmlMailSender getMessageSender() {   return messageSender;  }  public void setMessageSender(SimpleHtmlMailSender messageSender) {   this.messageSender = messageSender;  }  public SpringSendMail() {}        private JavaMailSenderImpl mailSender;   public JavaMailSenderImpl getMailSender() {      return mailSender;   }   public void setMailSender(JavaMailSenderImpl mailSender) {      this.mailSender = mailSender;   }   public void execute() {          try{         messageSender.sendMessage();      System.out.println("发送成功");           }catch(Exception e){       e.printStackTrace();      }   }  } 4.applicationContext-mail.xml         smtp服务器地址          user          pwd               true                            64256975@qq.com          t8log@jhsys.cn          test      5.applicationContext-quartz.xml                                                                             关于定时规则: 名称 是否必须 允许值 特殊字符 秒 是 0-59 , - * / 分 是 0-59 , - * / 时 是 0-23 , - * / 日 是 1-31 , - * ? / L W C 月 是 1-12 或 JAN-DEC , - * / 周 是 1-7 或 SUN-SAT , - * ? / L C # 年 否 空 或 1970-2099 , - * / java实现后台自动发邮件功能 web.xml文件 mailsenderservlet com.email.MailSenderServlet server smtp.163.com port 25 address username@163.com username username password ****** validate true time 5 1 servlet: package com.email; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MailSenderServlet extends HttpServlet { private MailSender sender; private Thread t; public void init() throws ServletException { sender = new MailSender(); sender.setRoot(root); String server = getInitParameter("server"); String port = getInitParameter("port"); String address = getInitParameter("address"); String username = getInitParameter("username"); String password = getInitParameter("password"); if (server == null || port == null || address == null || username == null || password == null) { System.out.println("系统文件web.xml错误:邮件发送程序初始化失败!"); return; } sender.setServer(server); sender.setPort(port); sender.setAddress(address); sender.setUsername(username); sender.setPassword(password); String time = getInitParameter("time"); if (time != null) { sender.setTime(Integer.parseInt(time)); } String validate = getInitParameter("validate"); if (validate != null) { sender.setValidate(Boolean.valueOf(validate).booleanValue()); } t = new Thread(sender); t.start(); //启动邮件发送线程 } public void destroy() { sender.stop(); //停止邮件发送线程 try { t.join(1000); if (t.isAlive()) { System.out.println("邮件发送线程未停止。"); } } catch (Exception e) {} } } 邮件发送程序 package com.email; import java.io.*; import java.sql.*; import java.util.*; import java.util.Date; import javax.activation.*; import javax.mail.*; import javax.mail.Message.*; import javax.mail.internet.*; /** *

Copyright: Copyright (c) 2004

* @author flyxxxxx@163.com * @version 1.0 */ public class MailSender implements Runnable { private int time = 5 * 60 * 1000; //扫描数据库时间间隔 private boolean flag = true; //停止线程标记 private String server = "127.0.0.1"; //SMTP服务器地址 private String port = "25"; //SMTP服务器端口 private String address; //用于发送EMAIL的发送者地址 private String username; //发送者的用户名 private String password; //发送者的密码 private boolean validate = true; //邮件服务器是否要求验证 private File root = null; //WEB根目录 MailConfigManager manager = MailConfigManager.getInstance(); public MailSender() { } public void setAddress(String address) { this.address = address; } public void setPassword(String password) { this.password = password; } public void setPort(String port) { if (port != null && port.length() > 0) { this.port = port; } } public void setServer(String server) { this.server = server; } public void setUsername(String username) { this.username = username; } public void setValidate(boolean validate) { this.validate = validate; } public void setTime(int minute) { this.time = minute * 60 * 1000; } public void run() { long lastTime = new Date().getTime(); //保存前一次发送邮件的时间 while (flag) { //服务器停止时退出线程 long k = new Date().getTime() - lastTime; if (k < -1000) { //防止系统修改时间 lastTime = new Date().getTime(); continue; } if (k > time) { //超过设定时间间隔开始发送邮件 sendData(); lastTime = new Date().getTime(); } try { Thread.sleep(100); } catch (Exception e) {} } } public void stop() { flag = false; } /** * 检索数据库,并发送邮件 */ private void sendData() { ResultSet rs=null;//读取数据库数据 try { Session session = Session.getInstance(getProperties(), new Authentic()); while(flag) {//服务器停止时退出线程 String toAddress = null;//发送地址(从rs中得到) String subject = null;//邮件主题 String content = null ;//邮件内容 String file[] = null;//所有附件(绝对路径) sendMail(session, toAddress, subject, content, file);//发送邮件 } } catch (Exception e) { e.printStackTrace(); } finally { if(rs!=null){ try{ rs.close(); } catch(SQLException e){} } } } /** * 发送邮件 * @param session 会话 * @param toAddress 目的地址 * @param subject 邮件主题 * @param content 邮件内容(HTML) * @param files 邮件附件 * @return 是否发送成功 */ private boolean sendMail(Session session, String toAddress, String subject, String content, String[] files) { toAddress = "lijin@regaltec.com.cn"; try { Message rs = new MimeMessage(session); Address from = new InternetAddress(address); rs.setFrom(from); //发送地址 rs.setRecipient(RecipientType.TO, new InternetAddress(toAddress)); //接收地址 rs.setSubject(subject); //邮件主题 Multipart mp = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(content, "text/html; charset=GBK"); //邮件HTML内容 mp.addBodyPart(html); if (files != null && files.length > 0) { //邮件附件 for (int i = 0; i < files.length; i++) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(files[i]); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeWord(files[i]), "GBK", null)); mp.addBodyPart(mbp); } } rs.setContent(mp); //邮件全部内容 rs.setSentDate(new Date()); //发送时间 Transport.send(rs); //发送 return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 邮件会话属性 * @return 会话属性 */ private Properties getProperties() { Properties rs = new Properties(); rs.put("mail.smtp.host", server); rs.put("mail.smtp.port", port); rs.put("mail.smtp.auth", validate ? "true" : "false"); return rs; } public void setRoot(File root) { this.root = root; } class Authentic extends Authenticator { //验证密码 public Authentic() { } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } } 用Java写的一个发邮件的东东(群发+多附件) 没什么好玩的了,最近看到好多地方有发邮件的东东,正好在看Java,就用Java写了,需要下载mail.jar和activation.jar,此外,用到我前次写的操作XML文件的一个类(上篇文章),好了,不多说了,代码贴贴,怎么用就看自己了: //JavaMail中一些我们需要的类 //1.Properties // //JavaMail需要Properties来创建一个session对象,其属性值就是发送邮件的主机,如: // //Properties props = new Properties (); //props.put("mail.smtp.host", "smtp.xxxx.com");//可以换上你的smtp主机名,就像你在OutLook中设置smtp主机名一样。 //props.put("mail.smtp.auth", "true"); //通过验证 // //2.Session // //所有的基于JavaMail的程序都至少需要一个或全部的对话目标。 // //Session session = Session.getInstance(props, null); // //3.MimeMessage // //信息对象将把你所发送的邮件真实的反映出来。 // //MimeMessage msg = new MimeMessage(session); // //4.Transport // //邮件的发送是由Transport来完成的: // //Transport.send(msg); import java.awt.List; import java.net.MalformedURLException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.dom4j.DocumentException; /* * Created on 2005-4-14 21:27:16 * */ /** * @author zxub * */ public class MailSender { String host; String userName; String password; String from; String to; String subject; String body; String fileName; // 用于保存发送附件的文件名列表 List arrFileName = new List(); public MailSender(String to, String subject, String body) throws MalformedURLException, DocumentException { //初始化发件人、收件人、主题等 OperaXML OX = new OperaXML(); this.from = OX.getNodeValue("config.xml", "config/Host1/From"); this.host = OX.getNodeValue("config.xml", "config/Host1/SmtpHost"); this.userName = OX.getNodeValue("config.xml", "config/Host1/UserName"); this.password = OX.getNodeValue("config.xml", "config/Host1/Password"); this.to = to; this.subject =subject; this.body = body; } // 用于收集附件名 public void attachFile(String fileName) { this.arrFileName.add(fileName); } // 开始发送 public boolean startSend() { //创建Properties对象 Properties props = System.getProperties(); //创建信件服务器 props.put("mail.smtp.host", this.host); props.put("mail.smtp.auth", "true"); //通过验证 //得到默认的对话对象 Session session = Session.getDefaultInstance(props, null); try { //创建一个消息,并初始化该消息的各项元素 MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(this.from)); if (this.to.trim().length() > 0) { String[] arr = this.to.split(","); //int ReceiverCount=1; int receiverCount = arr.length; if (receiverCount > 0) { InternetAddress[] address = new InternetAddress[receiverCount]; for (int i = 0; i < receiverCount; i++) { address[i] = new InternetAddress(arr[i]); } msg.addRecipients(Message.RecipientType.TO, address); } else { System.out .println("None receiver! The program will be exit!"); System.exit(0); } } else { System.out.println("None receiver! The program will be exit!"); System.exit(0); } msg.setSubject(subject); //后面的BodyPart将加入到此处创建的Multipart中 Multipart mp = new MimeMultipart(); //获取附件 int FileCount = this.arrFileName.getItemCount(); if (FileCount > 0) { for (int i = 0; i < FileCount; i++) { MimeBodyPart mbp = new MimeBodyPart(); //选择出附件名 fileName = arrFileName.getItem(i).toString(); //得到数据源 FileDataSource fds = new FileDataSource(fileName); //得到附件本身并至入BodyPart mbp.setDataHandler(new DataHandler(fds)); //得到文件名同样至入BodyPart mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(this.body); mp.addBodyPart(mbp); //移走集合中的所有元素 arrFileName.removeAll(); //Multipart加入到信件 msg.setContent(mp); } else { //设置邮件正文 msg.setText(this.body); } //设置信件头的发送日期 msg.setSentDate(new Date()); msg.saveChanges(); //发送信件 Transport transport = session.getTransport("smtp"); transport.connect(this.host, this.userName, this.password); transport.sendMessage(msg, msg .getRecipients(Message.RecipientType.TO)); transport.close(); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } return false; } return true; } public static void main(String[] args) { try { MailSender sendmail = new MailSender("邮箱地址1,邮箱地址2", "邮件主题", "邮件内容"); sendmail.attachFile("E:\\eclipse\\workspace\\MailSender\\MailSender.rar");//附件地址 //sendmail.attachFile("附件2地址");.................... sendmail.startSend(); System.out.println("OK"); } catch (Exception e) { e.printStackTrace(); } } } 发表于 @ 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zxub/archive/2005/04/17/351675.aspx javaMail实现发送E_mail添加附件 package com.king.mail; import java.util.Date; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class SendMailUtil { private String to; private String from; private String username; private String password; private String smtpServer; private String filename; private String subject; private String content; Vector file = new Vector(); public SendMailUtil() { } public SendMailUtil(String to, String from, String smtpServer, String username, String password, String subject, String content) {// 构造器 this.to = to; this.from = from; this.smtpServer = smtpServer; this.username = username; this.password = password; this.subject = subject; this.content = content; } public String transferChinese(String strText) {// 内容格式转码 try { strText = MimeUtility.encodeText(new String(strText.getBytes(), "gb2312"), "gb2312", "B"); } catch (Exception err) { err.printStackTrace(); } return strText; } public void attachfile(String fname) { file.addElement(fname); } public boolean send() { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password);// 用户登录stmp服务器时候验证用户名和密码。 } }); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); subject = transferChinese(subject); msg.setSubject(subject); Multipart mp = new MimeMultipart(); MimeBodyPart mbpContent = new MimeBodyPart(); mbpContent.setText(content); mp.addBodyPart(mbpContent); Enumeration efile = file.elements(); while (efile.hasMoreElements()) { MimeBodyPart mbpFile = new MimeBodyPart(); filename = efile.nextElement().toString(); FileDataSource fds = new FileDataSource(filename); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); mp.addBodyPart(mbpFile); } file.removeAllElements(); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); } catch (Exception err) { err.printStackTrace(); return false; } return true; } public static void main(String[] args) { try { SendMailUtil sm = new SendMailUtil(); sm.setSmtpServer("smtp.sina.com"); // 邮件协议 sm.setUsername("kingsever@sina.com");// 发件人 sm.setPassword("6557043");// 发件人密码 sm.setTo("kingsever@sina.com");// 收件人地址 sm.setFrom("kingsever@sina.com");// 发件人地址 sm.setSubject("测试附件能不能上传");// 邮件主题 sm.setContent("http://localhost:8080/sms/datasyn.sms?sign=go"); // sm.attachfile(""); 发送附件 sm.send(); // 发送 System.out.println("send success..."); } catch (Exception err) { err.printStackTrace(); } } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Vector getFile() { return file; } public void setFile(Vector file) { this.file = file; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSmtpServer() { return smtpServer; } public void setSmtpServer(String smtpServer) { this.smtpServer = smtpServer; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } JavaMail 发送邮件源代码 package mail.com.qdrk.www; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.util.ByteArrayDataSource; import sun.misc.BASE64Encoder; /** * * @author CARRIER * 设置好 * to 收件人 * subject 主题 * content 正文 */ public class JavaMail { private static String SMTPHOST="mail.yuancheng.com.cn"; private static String USERNAME="yanfangli@yuancheng.com.cn"; private static String PASSWORD="carrier"; private static String FROM="yanfangli@yuancheng.com.cn"; private static String FROMNAME="奋斗平台"; private final String MAIL_SMTP_HOST="mail.smtp.host"; private final String MAIL_SMTP_AUTH="mail.smtp.auth"; private String to; private String subject; private String content; public JavaMail() { // TODO Auto-generated constructor stub } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public void sendMail() { Properties props=new Properties(); props.put("mail.smtp.host", SMTPHOST); props.put("mail.smtp.auth", "true"); //建立会话 Session session=null; try{ Authenticator auth=new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USERNAME,PASSWORD); } }; session=Session.getInstance(props, auth); //设置调试 //session.setDebug(true); System.out.println("与"+SMTPHOST+"成功建立会话"); //建立消息 MimeMessage message=new MimeMessage(session); message.setFrom(new InternetAddress(FROM,FROMNAME)); message.setSentDate(new Date()); //加载收件人地址 InternetAddress toAddress=new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); //加载主题 BASE64Encoder enc=new BASE64Encoder(); message.setSubject("=?GBK?B?" +enc.encode(subject.getBytes())+"?="); //加载正文内容(带HTML标签) message.setDataHandler(new DataHandler( new ByteArrayDataSource(content, "text/html"))); //建立发送 Transport transport=session.getTransport("smtp"); transport.connect(SMTPHOST, USERNAME, PASSWORD); transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO)); //关闭发送 transport.close(); } catch(Exception e) { e.getStackTrace(); } System.out.println("给"+to+"的邮件,发送成功"); } public static void main(String[] args){ //String to="miderph@163.com"; //String to="yanfangli@yuancheng.com.cn"; //String to="miderph@live.cn"; String to="miderph001@sina.com"; //String to="miderph@126.com"; //String to="miderph@hotmail.com"; String subject="记账公司注册信息"; String content="用户名:admin
密码:123
激活链接 "; JavaMail mail=new JavaMail(); mail.setTo(to); mail.setSubject(subject); mail.setContent(content); mail.sendMail(); } } 发邮件的JAVA程序 以下是一个邮件发HTML的例子,供大家写发邮件参考. 功能是发送UL地址的HTML到邮件.其中的图片会随同邮件一同发给和户. package com.fswan.memo; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.activation.DataHandler; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * @author swan Fong(方志文) * */ public class TestMail { public static final String ul = "http://www.qxzw.com/htmpage/0/14/123.htm" ; public static void main(String[] args) { try { URL url = new URL(ul); // InputStream ins = url.openStream(); sendMail(url,"newsbot@yeah.net","smtp.yeah.net"); } catch (MalformedURLException e) { e.printStackTrace(); } } public static void sendMail(URL url,String mail,String smtpServer) { System.out.println("send"); MimeMultipart mp = new MimeMultipart(); String idStr = new SimpleDateFormat("hhmmsss").format(new Date()); System.out.println(idStr); try { InputStream ins = url.openStream(); StringBuffer sb = new StringBuffer(); byte[] conts = new byte[10240]; int len = ins.read(conts); while (len > 0) { sb.append(new String(conts,0,len)); // System.out.println(new String(conts)); // conts = new byte[10240]; len = ins.read(conts); } String con = sb.toString(); String con2 = sb.toString(); sb = new StringBuffer(); String regex = "]*)\"?.*/?\\s*>"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(con); ArrayList _mailAttachment = new ArrayList(); int lastPos = 0; while (m.find()) { sb.append(con.substring(lastPos, m.start())); sb.append(m.group().replaceAll(m.group(1), "cid:" + idStr + _mailAttachment.size())); _mailAttachment.add(new URL(url, m.group(1))); lastPos = m.end(); } sb.append(con.substring(lastPos, con.length())); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(sb.toString(),"text/html; charset=GB2312"); mp.addBodyPart(mbp2); for (int i = 0; i < _mailAttachment.size(); i++) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler((URL)_mailAttachment.get(i))); mbp.setHeader("Content-ID",idStr+i); mp.addBodyPart(mbp); } Properties prop = new Properties(); prop.put("mail.smtp.host", smtpServer); prop.put("mail.smtp.auth", "true"); Session s = Session.getInstance(prop, new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("newsbot@yeah.net", "fswan123"); } }); MimeMessage message = new MimeMessage(s); message.setSubject("mail"); message.setFrom(new InternetAddress(mail)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail)); message.setContent(mp); Transport.send(message); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } System.out.println("Finished"); } } 发送邮件 例子 package zyp; import java.util.Date; import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SimpleMailSender { public static void main(String[] arge) throws Exception { String from = "zyp1221@126.com"; String to = "zhang-yanpeng@dept01.stos.com"; String subject = "Test mail"; //String body = "Zyp JAVA MAIL TEST!"; String body = "呵呵...小坏一下~ 十次循环哦............"; Properties props = System.getProperties(); // 设置SMTP邮件服务器: props.put("mail.smtp.host", "172.25.72.7"); // SMTP服务器需要验证: props.put("mail.smtp.auth", "true"); // 传入用户名和口令: Session session = Session.getDefaultInstance(props, new PasswordAuthenticator("zhang-yanpeng", "dept01.stos.com")); // 创建新邮件: Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject); msg.setText(body); msg.setSentDate(new Date()); // 发送: for(int i=0;i<=9;i++){ System.out.println("#################"); Transport.send(msg); } } } class PasswordAuthenticator extends Authenticator { private String username; private String password; public PasswordAuthenticator(String username, String password) { this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zyp1221/archive/2008/11/04/3212155.aspx 用javamail发送邮件 aistill(原作) 关键字 javamail,smtp,附件,HTML邮件,smtp认证 /* 在java版经常看到有人问如何用javamail发送邮件?如何接收邮件?如何访问多个文件夹等。问题零散,而历史的回复早已经淹没在问题的海洋之中。 本人之前所做过一个java项目,其中包含有WebMail功能,当初为用java实现而对javamail摸索了一段时间,总算有点收获。看到论坛中的经常有此方面的问题,因此把我的一些经验帖出来,希望对大家有些帮助。 此篇仅介绍用javamail实现发送邮件功能,其中涉及smtp认证,邮件附件发送,及HTML内容邮件等。 其它有关多邮箱的实现,接收POP3邮件及IMAP等内容,将在后续文章中介绍。 如下程序需要:javamail,JAF包,j2ee.jar包含了上述两个包,建议大家安装J2SDKEE或直接拷贝j2ee.jar,将其添加到jbuilder的library中,或系统ClassPath中 */ package com.me.util.mail; /** * @author Zhangkun aistill@msn.com * @version 1.0 */ import java.util.*; import javax.mail.*; import javax.mail.internet.*; import java.util.Date; import javax.activation.*; import java.io.*; import com.me.util.*; public class sendMail { private MimeMessage mimeMsg; //MIME邮件对象 private Session session; //邮件会话对象 private Properties props; //系统属性 private boolean needAuth = false; //smtp是否需要认证 private String username = ""; //smtp认证用户名和密码 private String password = ""; private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 /** * */ public sendMail() { setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取 createMimeMessage(); } public sendMail(String smtp){ setSmtpHost(smtp); createMimeMessage(); } /** * @param hostName String */ public void setSmtpHost(String hostName) { System.out.println("设置系统属性:mail.smtp.host = "+hostName); if(props == null)props = System.getProperties(); //获得系统属性对象 props.put("mail.smtp.host",hostName); //设置SMTP主机 } /** * @return boolean */ public boolean createMimeMessage() { try{ System.out.println("准备获取邮件会话对象!"; session = Session.getDefaultInstance(props,null); //获得邮件会话对象 } catch(Exception e){ System.err.println("获取邮件会话对象时发生错误!"+e); return false; } System.out.println("准备创建MIME邮件对象!"; try{ mimeMsg = new MimeMessage(session); //创建MIME邮件对象 mp = new MimeMultipart(); return true; } catch(Exception e){ System.err.println("创建MIME邮件对象失败!"+e); return false; } } /** * @param need boolean */ public void setNeedAuth(boolean need) { System.out.println("设置smtp身份认证:mail.smtp.auth = "+need); if(props == null)props = System.getProperties(); if(need){ props.put("mail.smtp.auth","true"; }else{ props.put("mail.smtp.auth","false"; } } /** * @param name String * @param pass String */ public void setNamePass(String name,String pass) { username = name; password = pass; } /** * @param mailSubject String * @return boolean */ public boolean setSubject(String mailSubject) { System.out.println("设置邮件主题!"; try{ mimeMsg.setSubject(mailSubject); return true; } catch(Exception e) { System.err.println("设置邮件主题发生错误!"; return false; } } /** * @param mailBody String */ public boolean setBody(String mailBody) { try{ BodyPart bp = new MimeBodyPart(); bp.setContent(";"+mailBody,"text/html;charset=GB2312"; mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println("设置邮件正文时发生错误!"+e); return false; } } /** * @param name String * @param pass String */ public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:"+filename); try{ BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println("增加邮件附件:"+filename+"发生错误!"+e); return false; } } /** * @param name String * @param pass String */ public boolean setFrom(String from) { System.out.println("设置发信人!"; try{ mimeMsg.setFrom(new InternetAddress(from)); //设置发信人 return true; } catch(Exception e) { return false; } } /** * @param name String * @param pass String */ public boolean setTo(String to){ if(to == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to)); return true; } catch(Exception e) { return false; } } /** * @param name String * @param pass String */ public boolean setCopyTo(String copyto) { if(copyto == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); return true; } catch(Exception e) { return false; } } /** * @param name String * @param pass String */ public boolean sendout() { try{ mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println("正在发送邮件...."; Session mailSession = Session.getInstance(props,null); Transport transport = mailSession.getTransport("smtp"; transport.connect((String)props.get("mail.smtp.host"),username,password); transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO)); //transport.send(mimeMsg); System.out.println("发送邮件成功!"); transport.close(); return true; } catch(Exception e) { System.err.println("邮件发送失败!"+e); return false; } } /** * Just do it as this */ public static void main(String[] args) { String mailbody = ";"+ ";"; sendMail themail = new sendMail("smtp.msn.com"); themail.setNeedAuth(true); if(themail.setSubject("标题") == false) return; if(themail.setBody(mailbody) == false) return; if(themail.setTo("gates@msn.com") == false) return; if(themail.setFrom("bill@msn.com") == false) return; if(themail.addFileAffix("c:\\boot.ini") == false) return; themail.setNamePass("user","password"); if(themail.sendout() == false) return; } } 给你一个email地址,java程序,如何实现发送邮件呢!邮件中加入附件,为指定的文件?? import java.util.*; import javax.mail.*; import javax.mail.internet.*; import java.util.Date; import javax.activation.*; import java.io.*; //import com.me.util.*; public class testmail { private MimeMessage mimeMsg; //MIME邮件对象 private Session session; //邮件会话对象 private Properties props; //系统属性 private boolean needAuth = false; //smtp是否需要认证 private String username = " "; //smtp认证用户名和密码 private String password = " "; private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 /** * */ public testmail() { // setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取 createMimeMessage(); } public testmail(String smtp){ setSmtpHost(smtp); createMimeMessage(); } /** * @param hostName String */ public void setSmtpHost(String hostName) { System.out.println( "设置系统属性:mail.smtp.host = "+hostName); if(props == null)props = System.getProperties(); //获得系统属性对象 props.put( "mail.smtp.host ",hostName); //设置SMTP主机 } /** * @return boolean */ public boolean createMimeMessage() { try{ System.out.println( "准备获取邮件会话对象! "); session = Session.getDefaultInstance(props,null); //获得邮件会话对象 } catch(Exception e){ System.err.println( "获取邮件会话对象时发生错误! "+e); return false; } System.out.println( "准备创建MIME邮件对象! "); try{ mimeMsg = new MimeMessage(session); //创建MIME邮件对象 mp = new MimeMultipart(); return true; } catch(Exception e){ System.err.println( "创建MIME邮件对象失败! "+e); return false; } } /** * @param need boolean */ public void setNeedAuth(boolean need) { System.out.println( "设置smtp身份认证:mail.smtp.auth = "+need); if(props == null)props = System.getProperties(); if(need){ props.put( "mail.smtp.auth ", "true "); }else{ props.put( "mail.smtp.auth ", "false "); } } /** * @param name String * @param pass String */ public void setNamePass(String name,String pass) { username = name; password = pass; } /** * @param mailSubject String * @return boolean */ public boolean setSubject(String mailSubject) { System.out.println( "设置邮件主题! "); try{ mimeMsg.setSubject(mailSubject); return true; } catch(Exception e) { System.err.println( "设置邮件主题发生错误! "); return false; } } /** * @param mailBody String */ public boolean setBody(String mailBody) { try{ BodyPart bp = new MimeBodyPart(); bp.setContent( " "+mailBody, "text/html;charset=gb2312 "); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println( "设置邮件正文时发生错误! "+e); return false; } } /** * @param name String * @param pass String */ public boolean addFileAffix(String filename) { System.out.println( "增加邮件附件: "+filename); try{ BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch(Exception e){ System.err.println( "增加邮件附件: "+filename+ "发生错误! "+e); return false; } } /** * @param name String * @param pass String */ public boolean setFrom(String from) { System.out.println( "设置发信人! "); try{ mimeMsg.setFrom(new InternetAddress(from)); //设置发信人 return true; } catch(Exception e) { return false; } } /** * @param name String * @param pass String */ public boolean setTo(String to){ if(to == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to)); return true; } catch(Exception e) { return false; } } /** * @param name String * @param pass String */ public boolean setCopyTo(String copyto) { if(copyto == null)return false; try{ mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); return true; } catch(Exception e) { return false; } } /** * @param name String * @param pass String */ public boolean sendout() { try{ mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println( "正在发送邮件.... "); Session mailSession = Session.getInstance(props,null); Transport transport = mailSession.getTransport( "smtp "); transport.connect((String)props.get( "mail.smtp.host "),username,password); transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO)); //transport.send(mimeMsg); System.out.println( "发送邮件成功! "); transport.close(); return true; } catch(Exception e) { System.err.println( "邮件发送失败! "+e); return false; } } /** * Just do it as this */ public static void main(String[] args) { String mailbody = " "+ " "; testmail themail = new testmail( "192.168.10.251 "); themail.setNeedAuth(true); if(themail.setSubject( "标题 ") == false) return; if(themail.setBody(mailbody) == false) return; if(themail.setTo( "leqi@ipanel.cn ") == false) return; if(themail.setFrom( "leqi@ipanel.cn ") == false) return; if(themail.addFileAffix( "mail/LAYMAN.txt ") == false) return; themail.setNamePass( "leqi ", "111 "); if(themail.sendout() == false) return; } } 已经可以发邮件了,但是要去掉if(themail.setBody(mailbody) == false) return; 报错,说格式不对,!: 邮件发送失败!javax.mail.MessagingException: IOException while sending message; nested exception is: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type text/html;charset=gb2312 怎么改呀 定时发邮件的问题已经解决了!现在就是邮件中写东西有问题! javax.mail.MessagingException: IOException while sending message; nested exception is: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type text/html;charset=gb2312 如果不要if(themail.setBody(mailbody) == false) return;就没问题,但那样,我的邮件就没有正文了,只有标题和附件了!急呀! 把bp.setContent( " "+mailBody, "text/html;charset=gb2312 "); 改为 bp.setText( " "+mailBody , "text/html;charset=gb2312 ");

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 10 金币 [ 分享文档获得金币 ] 6 人已下载

下载文档