java 代码
- package example;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.mail.internet.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeUtility;
- import org.apache.commons.mail.Email;
- import org.apache.commons.mail.EmailAttachment;
- import org.apache.commons.mail.EmailException;
- import org.apache.commons.mail.HtmlEmail;
- import org.apache.commons.mail.MultiPartEmail;
- public class SendMail3 {
- public void sendMail() throws AddressException,EmailException {
- try {
- Email htmlEmail = new HtmlEmail();
- // STMP服务器
- htmlEmail.setHostName("smtp.sina.com.cn");
- htmlEmail
- .setAuthentication("weishuwei112@sina.com", "wswlyn841013");
- htmlEmail.addTo("weishuwei112@sina.com");
- List list = new ArrayList();
- // throw AddressException
- list.add(new InternetAddress("jonekolly@126.com"));
- list.add(new InternetAddress("weishuwei112@sina.com"));
- htmlEmail.setTo(list);
- // addTo(String email),就是向一个List添加email,
- // setTo(list)是批量添加email
- htmlEmail.setFrom("weishuwei112@sina.com");
- htmlEmail.setCharset("GBK");
- htmlEmail.setSubject("email 测试");
- htmlEmail.setMsg("email 测试");
- htmlEmail.send();
- System.out.println("end");
- } catch (EmailException e) {
- e.printStackTrace();
- }
- }
- public void sendEmailAttachment() throws UnsupportedEncodingException {
- EmailAttachment attachment = new EmailAttachment();
- attachment.setPath("D:\\eBook\\CSS.chm");
- attachment.setDisposition(EmailAttachment.ATTACHMENT);
- attachment.setDescription("Picture of John");//附件描述
- attachment.setName("CSS.chm");// 名字必须带文件扩展名
- attachment.setName(MimeUtility.encodeText("需传送的附件.txt"));
- // HtmlEmail hemail=new HtmlEmail();为MultiPartEmail子类
- // hemail.attach(attachment);
- MultiPartEmail email = new MultiPartEmail();
- email.setCharset("GBK");
- email.setHostName("smtp.sina.com.cn");
- email.setAuthentication("weishuwei112@sina.com", "wswlyn841013");
- try {
- email.addTo("weishuwei112@sina.com", "martin");
- email.setFrom("weishuwei112@sina.com", "martin");
- email.setSubject("邮件主题");
- email.setMsg("邮件内容");
- //中文:将setMsg替换为setContent()
- email.setContent("This is a simple test of commons-email", "text/plain;charset=GBK");
- // add attachment
- email.attach(attachment);
- email.send();
- System.out.println("end");
- } catch (EmailException e) {
- e.printStackTrace();
- }
- }
- }