---
title: "commons-email笔记"
author: "weishuwei"
date: "2007-06-29T17:24:21Z"
tags: ["Apache", "CSS"]
slug: "commons-email"
draft: false
lastmod: "2007-06-29T17:24:21Z"
id: 95582
url: "https://weishuwei.iteye.com/blog/95582"
---

java 代码

 

01. package example;
02. import java.io.UnsupportedEncodingException;
03. import java.util.ArrayList;
04. import java.util.List;
05. import javax.mail.internet.AddressException;
06. import javax.mail.internet.InternetAddress;
07. import javax.mail.internet.MimeUtility;
08. import org.apache.commons.mail.Email;
09. 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. }