Java实现邮件发送
在日常工作中,通过邮件或短信做报警或者信息推送的场景还是挺多的,而java中,常用的就是JavaMail来做这个事情了,到网上搜索了一把,发现apache有个commons email 的开源包,现在借助它来尝鲜一把
简单使用
添加pom依赖:
1 2 3 4 5 6
| <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dependency>
|
查看使用帮助: http://commons.apache.org/proper/commons-email/userguide.html
1. 简单使用case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Test public void testEmailSend() { try { Email email = new SimpleEmail(); email.setHostName("smtp.163.com"); email.setSmtpPort(25); email.setAuthenticator(new DefaultAuthenticator("userName", "accessToken")); email.setSSLOnConnect(true); email.setFrom("xhhuiblog@163.com"); email.setCharset("utf-8"); email.addTo("bangzewu@126.com"); email.setSubject("邮件标题"); email.setMsg("邮件内容"); String ans = email.send(); System.out.println(ans); } catch (Exception e) { e.printStackTrace(); } }
|
从实际的使用来看,还是比较简单的,设置一些必要的参数(host,端口,认证信息,fromEmail, toEmail, title, content)
额外需要注意的一点是,为了中文正常显示,请指定charset
2. html使用姿势
更加常见的邮件发送是带有格式的,且有可能有附件,所以我们通常用的更多的是下面的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| private String template = "<html><meta charset=utf-8>\n" + "\n" + "<style>\n" + "div.card {\n" + " background-color:white; \n" + " box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);\n" + " text-align: center;\n" + "}\n" + "\n" + "div.header {\n" + " background-color: #4CAF50;\n" + " box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);\n" + " color: white;\n" + " padding: 10px;\n" + " font-size: 40px;\n" + "}\n" + "\n" + "div.container {\n" + " padding: 10px;\n" + "}\n" + "</style>\n" + "\n" + "<div class=\"card\">\n" + " <div class=\"header\">\n" + " <h1>星期一</h1>\n" + " </div>\n" + "\n" + " <div class=\"container\">\n" + " <p>2016.04.10</p>\n" + " </div>\n" + "</div>\n" + "</html>";
@Test public void testHtmlEmailSend() { try { EmailAttachment attachment = new EmailAttachment(); attachment.setURL(new URL("http://s11.mogucdn.com/mlcdn/c45406/180410_256l2egkgj3lfdkjkbf41b1i09l3f_1280x1280.jpg")); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("公众号"); attachment.setName("logo.jpg");
HtmlEmail email = new HtmlEmail(); email.setCharset("UTF-8"); email.setHostName("smtp.163.com"); email.setSmtpPort(25); email.setAuthenticator(new DefaultAuthenticator("username", "token")); email.setSSLOnConnect(true); email.setFrom("xhhuiblog@163.com"); email.setSubject("TestMail");
email.attach(attachment);
email.setHtmlMsg(template);
email.setTextMsg("Your email client does not support HTML messages");
email.addTo("bangzewu@126.com"); String ans = email.send(); System.out.println(ans); } catch (Exception e) { e.printStackTrace(); } }
|
邮件结果如下:
II. 其他
基于hexo + github pages搭建的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
声明
尽信书则不如,已上内容,纯属一家之言,因本人能力一般,见识有限,如发现bug或者有更好的建议,随时欢迎批评指正
扫描关注