使用commons mail时需要的jar包:
1,commons-email-1.1.jar
2,mail.jar
3,activation.jar
(在web应用里只需要commons-email包)
发送简单的文字邮件:
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.sina.com");
email.setAuthentication("username", "password");//在邮件服务商处注册的用户名和密码
email.addTo("mailTo@163.com");
email.setFrom("username@sina.com", "alias");
email.setCharset("UTF-8");//gbk或gb2312,只要支持中文就行
email.setSubject("title");
email.setMsg("content");
email.send();
发送带附件的邮件:
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("mypictures/john.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
attachment.setName("John");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("mail.myserver.com");
email.setAuthentication("username", "password");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setCharset("UTF-8");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// add the attachment
email.attach(attachment);
// send the email
email.send();
创建多个EmailAttachment对象,并调用MultiPartEmail.attach();就可以发送多个附件.
发送HTML格式的邮件:
发送html格式的邮件和简单邮件的区别就在创建HtmlEmail对象
并用email.setHtmlMsg(String)或email.setMsg(String)把含有html标签的字符串赋给email对象.
HtmlEmail对象还有一个setTextMsg(String)方法,这个方法参数里的html标签会被当做普通字符处理,不会被解析成html元素.
更详细内容可以看apache commons-email的用户指南.