apache的commons项目下有个email子项目,它对JavaMail API进行了封装,用起来特变方便。下面就简单介绍。
1. 首先配置需要的jar包
需要将mail.jar和commons-email.jar添加到我们的CLASSPATH中即可,如下图:
如果您的项目是gradle项目,那么配置commons-email可以更简洁了:
compile('org.apache.commons:commons-email:1.4')
2. 发送普通邮件
- /**
- * 用org.apache.commons.mail发送普通邮件
- *
- * @author wangzhipeng
- *
- */
- public class TestCommon {
- public TestCommon() {
- }
- public static void main(String[] args) {
- SimpleEmail email = new SimpleEmail();
- email.setHostName("smtp.qq.com");// 设置使用发电子邮件的邮件服务器,这里以qq邮箱为例(其它例如:【smtp.163.com】,【smtp.sohu.com】)
- try {
- // 收件人邮箱
- email.addTo("1115366817@qq.com");
- // 邮箱服务器身份验证
- email.setAuthentication("你的邮箱地址", "你的邮箱授权码");
- // 发件人邮箱
- email.setFrom("你的邮箱地址");
- // 邮件主题
- email.setSubject("zhipeng-JavaMail");
- // 邮件内容
- email.setMsg("Kobe Bryante Never Stop Trying");
- // 发送邮件
- email.send();
- } catch (EmailException ex) {
- ex.printStackTrace();
- }
- }
- }
3. 发送HTML类型邮件
- /**
- * 用org.apache.commons.mail发送HTML邮件
- *
- * @author wangzhipeng
- *
- */
- public class TestCommonHTML {
- public TestCommonHTML() {
- }
- public static void main(String[] args) {
- // 不要使用SimpleEmail,会出现乱码问题
- HtmlEmail email = new HtmlEmail();
- // SimpleEmail email = new SimpleEmail();
- try {
- // 这里是SMTP发送服务器的名字:qq的如下:
- email.setHostName("smtp.qq.com");
- // 字符编码集的设置
- email.setCharset("gbk");
- // 收件人的邮箱
- email.addTo("你的邮箱地址");
- // 发送人的邮箱
- email.setFrom("379275614@qq.com", "wangzhipeng");
- // 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
- email.setAuthentication("你的邮箱地址", "你的邮箱授权码");
- email.setSubject("下午3:00会议室讨论,请准时参加");
- // 要发送的信息,由于使用了HtmlEmail,可以在邮件内容中使用HTML标签
- email.setMsg("<h1 style='color:red'>下午3:00会议室讨论</h1>" + " 请准时参加!");
- // 发送
- email.send();
- System.out.println("邮件发送成功!");
- } catch (EmailException e) {
- e.printStackTrace();
- System.out.println("邮件发送失败!");
- }
- }
- }
结果如下:
4、发送带图片的HTML格式邮件
// load your HTML email template
String htmlEmailTemplate = ....
// define you base URL to resolve relative resource locations
URL url = new URL("http://www.apache.org");
// create the email message
HtmlEmail email = new ImageHtmlEmail();
email.setDataSourceResolver(new DataSourceResolverImpl(url));
email.setHostName("mail.myserver.com");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setSubject("Test email with inline image");
// set the html message
email.setHtmlMsg(htmlEmailTemplate);
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();
参考http://blog.youkuaiyun.com/wang379275614/article/details/46624889
http://www.open-open.com/lib/view/open1410621206648.html