ITeye博客

commons-email笔记

weishuwei · 2007-06-29 17:24 · 问题拾遗 · Markdown

java 代码

 

  1. package example;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.mail.internet.AddressException;
  6. import javax.mail.internet.InternetAddress;
  7. import javax.mail.internet.MimeUtility;
  8. import org.apache.commons.mail.Email;
  9. import org.apache.commons.mail.EmailAttachment;
  10. import org.apache.commons.mail.EmailException;
  11. import org.apache.commons.mail.HtmlEmail;
  12. import org.apache.commons.mail.MultiPartEmail;
  13. public class SendMail3 {
  14. public void sendMail() throws AddressException,EmailException {
  15. try {
  16. Email htmlEmail = new HtmlEmail();
  17. // STMP服务器
  18. htmlEmail.setHostName("smtp.sina.com.cn");
  19. htmlEmail
  20. .setAuthentication("weishuwei112@sina.com", "wswlyn841013");
  21. htmlEmail.addTo("weishuwei112@sina.com");
  22. List list = new ArrayList();
  23. // throw AddressException
  24. list.add(new InternetAddress("jonekolly@126.com"));
  25. list.add(new InternetAddress("weishuwei112@sina.com"));
  26. htmlEmail.setTo(list);
  27. // addTo(String email),就是向一个List添加email,
  28. // setTo(list)是批量添加email
  29. htmlEmail.setFrom("weishuwei112@sina.com");
  30. htmlEmail.setCharset("GBK");
  31. htmlEmail.setSubject("email 测试");
  32. htmlEmail.setMsg("email 测试");
  33. htmlEmail.send();
  34. System.out.println("end");
  35. } catch (EmailException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. public void sendEmailAttachment() throws UnsupportedEncodingException {
  40. EmailAttachment attachment = new EmailAttachment();
  41. attachment.setPath("D:\\eBook\\CSS.chm");
  42. attachment.setDisposition(EmailAttachment.ATTACHMENT);
  43. attachment.setDescription("Picture of John");//附件描述
  44. attachment.setName("CSS.chm");// 名字必须带文件扩展名
  45. attachment.setName(MimeUtility.encodeText("需传送的附件.txt"));
  46. //      HtmlEmail hemail=new HtmlEmail();为MultiPartEmail子类
  47. //      hemail.attach(attachment);
  48. MultiPartEmail email = new MultiPartEmail();
  49. email.setCharset("GBK");
  50. email.setHostName("smtp.sina.com.cn");
  51. email.setAuthentication("weishuwei112@sina.com", "wswlyn841013");
  52. try {
  53. email.addTo("weishuwei112@sina.com", "martin");
  54. email.setFrom("weishuwei112@sina.com", "martin");
  55. email.setSubject("邮件主题");
  56. email.setMsg("邮件内容");
  57. //中文:将setMsg替换为setContent()
  58. email.setContent("This is a simple test of commons-email", "text/plain;charset=GBK");
  59. // add attachment
  60. email.attach(attachment);
  61. email.send();
  62. System.out.println("end");
  63. } catch (EmailException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。