一、简介
Commons Email封装了javamail,使用非常简单。
功能:简单文本邮件、带附件的邮件、HTML格式的邮件
官方首页:http://commons.apache.org/email/,目前最新版本是1.1
官方示例:http://commons.apache.org/email/userguide.html
使用前需引入3个jar文件:commons-email-1.1.jar、javamail.jar、activation.jar
二、简单文本邮件
SimpleEmail email = new SimpleEmail();
email.setHostName("mail.fastunit.com");
email.setAuthentication("[email protected]", "***");//邮件服务器验证:用户名/密码
email.setCharset("UTF-8");// 必须放在前面,否则乱码
email.addTo("[email protected]");
email.setFrom("[email protected]", "support");
email.setSubject("subject中文");
email.setMsg("msg中文");
email.send();
三、带附件的邮件
MultiPartEmail email = new MultiPartEmail();
email.setHostName("mail.fastunit.com");
email.setAuthentication("[email protected]", "***");
email.setCharset("UTF-8");
email.addTo("[email protected]");
email.setFrom("[email protected]", "support");
email.setSubject("subject中文");
email.setMsg("msg中文");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("d:/a.gif");// 本地文件
// attachment.setURL(new URL("http://xxx/a.gif"));//远程文件
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("a");
attachment.setName("a");
email.attach(attachment);
email.send();
四、HTML格式邮件
HtmlEmail email = new HtmlEmail();
email.setHostName("mail.fastunit.com");
email.setAuthentication("[email protected]", "***");
email.setCharset("UTF-8");
email.addTo("[email protected]");
email.setFrom("[email protected]", "support");
email.setSubject("subject中文");
email.setHtmlMsg("<b>msg中文</b>");
email.send();
五、其他
使用免费邮箱来测试时,有些免费邮箱不提供此服务,无法通过邮件服务器验证。