本文將介紹多種使用Java發(fā)送Email的應(yīng)用實(shí)踐。
前提摘要:在學(xué)習(xí)Java Web的構(gòu)建中,無論是觸發(fā)型的郵件-注冊,重置密碼郵件,還是批量式的營銷廣告,訂閱郵件,郵件發(fā)送是系統(tǒng)離不開的應(yīng)用場景。本文需要你知道
Maven的基本使用。
一、實(shí)用Java Mail發(fā)送郵件
引入maven依賴
<!-- mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.codemonkey.simplejavamail</groupId>
<artifactId>simple-java-mail</artifactId>
<version>2.1</version>
</dependency>
Demo Code
package cn.daimaniu.blog.mail;
import org.codemonkey.simplejavamail.Email;
import org.codemonkey.simplejavamail.Mailer;
import org.codemonkey.simplejavamail.TransportStrategy;
import javax.mail.Message;
/**
* Author :keepcleargas
* Date :2016-09-04 13:52.
* <p>
* 通過Java Mail 發(fā)送郵件,@see{ org.codemonkey.simplejavamail 簡單化的Mail發(fā)送}
*/
public class JavaMailSender implements IMailSender {
private final String host = "smtp.126.com"; // smtp host
private final int port = 465; //smtp 端口
private final String user = "<請?zhí)顚懩愕膆ost相對應(yīng)的郵件地址>"; //發(fā)送者郵件地址
private final String password = "<郵件密碼>"; //郵件密碼
private final String sender = "<發(fā)件人名稱>"; //發(fā)送人名稱
public boolean send(String to, String toName, String body) {
Email email = new Email();
email.setFromAddress(sender, user);
email.setReplyToAddress(sender, user);
email.addRecipient(toName, to, Message.RecipientType.TO);
email.setTextHTML(body);
email.setSubject("你好" + toName + ",我是一封來自菜鳥筆記的郵件!!!");
new Mailer(host, port, user, password, TransportStrategy.SMTP_SSL).sendMail(email);
return true;
}
}
Notice: 記得將代碼里的<>的內(nèi)容替換掉, 如<請?zhí)顚懩愕膆ost相對應(yīng)的郵件地址> 為
xxxx@126.com.
打開終端,執(zhí)行Test
mvn test -Dtest=MailTest#TestJavaMailSender.
即可發(fā)送郵件了。
效果如下

二、使用第三方郵件服務(wù)
Aliyun郵件服務(wù)示例
引入maven依賴
<!--aliyun mail-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dm</artifactId>
<version>3.0.0-rc1</version>
</dependency>
Demo Code
package cn.daimaniu.blog.mail;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
* Author :keepcleargas
* Date :2016-09-04 13:55.
* <p>
* 通過Aliyun Java SDK 發(fā)送郵件
*/
public class AliyunMailSender implements IMailSender {
public boolean send(String to, String toName, String body) {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<your accessKey>", "<your accessSecret>");
IAcsClient client = new DefaultAcsClient(profile);
SingleSendMailRequest request = new SingleSendMailRequest();
try {
request.setAccountName("<控制臺(tái)創(chuàng)建的發(fā)信地址>");
request.setFromAlias("菜鳥筆記"); //發(fā)送人的昵稱
request.setAddressType(1);
request.setTagName("<控制臺(tái)創(chuàng)建的標(biāo)簽>");
request.setReplyToAddress(true);
request.setToAddress(to);
request.setSubject("你好" + toName + ",我是一封來自菜鳥筆記的郵件!!!");
request.setHtmlBody(body);
SingleSendMailResponse httpResponse = client.getAcsResponse(request);
System.out.println("res:" + httpResponse.toString());
return true;
} catch (ServerException e) {
e.printStackTrace();
return false;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}
Notice: Aliyun 郵件服務(wù)需要在阿里云控制臺(tái)申請開通,并設(shè)置自己的域名相關(guān)的 發(fā)件人如 vip@daimaniu.cn,將驗(yàn)證成功的發(fā)件人,accessId和SecretKey替換<>。
打開終端,執(zhí)行Test
mvn test -Dtest=MailTest#TestAliyunMailSender
效果如下

三、構(gòu)建你的發(fā)送Html內(nèi)容
使用模板語言,構(gòu)建Html.
Velocity[^1]初識
Velocity 是一個(gè)基于Java 的模板引擎,它允許任何人僅僅簡單的使用模板語言來引用由Java 代碼定義的對象,從而實(shí)現(xiàn)界面和Java 代碼的分離,使得界面設(shè)計(jì)人員可以和Java 程序開發(fā)人員同步開發(fā)一個(gè)遵循MVC 架構(gòu)的web 站點(diǎn)。
推薦閱讀 [^2]使用 Velocity 模板引擎快速生成代碼
構(gòu)建郵件正文
引入maven依賴
<!--template-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
在/src/main/resources/下新建文件夾template,添加reg.vm模板(發(fā)送注冊驗(yàn)證郵件模板).
reg.vm 標(biāo)準(zhǔn)的html格式
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf8">
</head>
<body>
<p>${toName},你好</p>
<p>歡迎來到菜鳥筆記,您的登錄帳號是:${to}</p>
<a >請點(diǎn)此完成郵箱驗(yàn)證</a>
<p>(如果以上鏈接無法點(diǎn)擊,請將地址手工復(fù)制到瀏覽器地址欄中訪問)
<a >http://blog.daimaniu.cn/confirm?code=${code}</a>
</p>
<p>----------------------------------------------</p>
<p>此信是由菜鳥筆記發(fā)出,請勿直接回復(fù)。</p>
</body>
</html>
VelocityUtil.java
public class VelocityUtil {
/**
* 生成 注冊郵件
*
* @param to 接收人的郵件地址
* @param toName 接收人的昵稱
* @param code 郵件驗(yàn)證碼
* @return
*/
public static String genRegMail(String to, String toName, String code) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
Template t = ve.getTemplate("template/reg.vm", "utf-8");
VelocityContext ctx = new VelocityContext();
ctx.put("to", to);
ctx.put("toName", toName);
//code random
ctx.put("code", code);
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
return sw.toString();
}
}
Notice: ctx map里 填寫的字段 都是reg.vm 里 ${}對應(yīng)的數(shù)據(jù)字段。
打開終端,執(zhí)行Test
mvn test -Dtest=MailTest#VelocityHtmlTest

四、場景案例分析
Trigger Sample:
- Teambition的協(xié)作邀請.
- 知乎的注冊郵箱驗(yàn)證
- 阿里云的服務(wù)器操作郵件
- Google/Outlook的異地登錄安全提醒
- .......
Subscribe Sample:
1.daocloud的每周精選
2.垃圾郵件---[手動(dòng)滑稽]
參考列表
- 菜鳥筆記源碼
- Aliyun Mail服務(wù)
- Sendcloud Mail服務(wù)
- Mailgun Mail服務(wù)
- [^1]Velocity
- [^2]使用 Velocity 模板引擎快速生成代碼
本文源代碼地址:https://github.com/daimaniu/cainiaobiji ,歡迎star 和 fork。
原文地址:http://blog.daimaniu.cn/cai-niao-bi-ji-er-javayou-jian-fa-song-shi-jian/
下期預(yù)告
下期預(yù)告(9月8號):Java Excel報(bào)表導(dǎo)入導(dǎo)出 - 企業(yè)管理后臺(tái)必備技能。
歡迎大家關(guān)注我的微博,或者在 Follow 我。菜鳥筆記 周四不見不散