最近在web项目中,客户端注册时需要通过邮箱验证,服务器就需要向客户端发送邮件,我把发送邮件的细节进行了简易的封装:

在maven中需要导入:

 <!--Email-->
<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>

发送方的封装:

 import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties; public abstract class MailSession implements EmailConstant {
// Mail的Session对象
protected Session session;
// 发送方邮箱
protected String srcEmail;
// 发送方的授权码(不是邮箱登陆密码,如何获取请百度)
protected String authCode; protected MailSession(String srcEmail, String authCode) {
this.srcEmail = srcEmail;
this.authCode = authCode; createSession();
} protected abstract void doCreateSession(Properties properties); private void createSession() {
// 获取系统属性,并设置
Properties properties = System.getProperties();
// 由于不同的邮箱在初始化Session时有不同的操作,需要由子类实现
doCreateSession(properties);
properties.setProperty(MAIL_AUTH, "true"); // 生成Session对象
session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(srcEmail, authCode);
}
});
} public Session getSession() {
return session;
} public String getSrcEmail() {
return srcEmail;
} @Override
public String toString() {
return "MailSession{" +
"session=" + session +
", srcEmail='" + srcEmail + '\'' +
", authCode='" + authCode + '\'' +
'}';
} }

EmailConstant :

 /**
* 需要的系统属性
**/
public interface EmailConstant {
String HOST_QQ = "smtp.qq.com";
String HOST_163 = "smtp.163.com";
String MAIL_HOST = "mail.smtp.host";
String MAIL_AUTH = "mail.smtp.auth";
String MAIL_SSL_ENABLE = "mail.smtp.ssl.enable";
String MAIL_SSL_SOCKET_FACTORY = "mail.smtp.ssl.socketFactory";
}

163邮箱的系统设置:

 public class WYMailSession extends MailSession {

     public WYMailSession(String srcEmail, String authCode) {
super(srcEmail, authCode);
} @Override
protected void doCreateSession(Properties properties) {
properties.setProperty(MAIL_HOST, EmailConstant.HOST_163);
} }

QQ邮箱的系统设置:

 public class QQMailSession extends MailSession {

     public QQMailSession(String srcEmail, String authCode) {
super(srcEmail, authCode);
} @Override
protected void doCreateSession(Properties properties) {
properties.setProperty(MAIL_HOST, EmailConstant.HOST_QQ); try {
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put(MAIL_SSL_ENABLE, "true");
properties.put(MAIL_SSL_SOCKET_FACTORY, mailSSLSocketFactory);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
} }

发送的邮件封装:

 public class MailMessage {
// 接收方邮箱
private String tagEmail;
// 主题
private String subJect;
// 内容
private String content; public MailMessage(String tagEmail, String subJect, String content) {
this.tagEmail = tagEmail;
this.subJect = subJect;
this.content = content;
} public String getTagEmail() {
return tagEmail;
} public String getSubJect() {
return subJect;
} public String getContent() {
return content;
} @Override
public String toString() {
return "MailMessage{" +
"tagEmail='" + tagEmail + '\'' +
", subJect='" + subJect + '\'' +
", content='" + content + '\'' +
'}';
} }

发送部分:

 import com.zc.util.logger.Logger;
import com.zc.util.logger.LoggerFactory; import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor; public class MailSender { private static final Logger LOGGER = LoggerFactory.getLogger(MailSender.class);
  // 这个队列是有在多个发送方的情况下,可以轮流发送
private final Queue<MailSession> queue = new ConcurrentLinkedQueue<>();
  // 使用线程池,让线程去完成发送
private final Executor executor; public MailSender(Executor executor) {
this.executor = executor;
}
  // 指定发送方,发送邮件
public void sendTo(MailSession mailSession, MailMessage mailMessage) {
if (mailSession == null) {
String msg = "MailSender sendTo(), mailSession can not null!";
if (LOGGER.isErrorEnabled()) {
LOGGER.error(msg);
}
throw new NullPointerException(msg);
} if (!queue.contains(mailSession)) {
addSender(mailSession);
} executor.execute(new Runnable() {
@Override
public void run() {
Message message = new MimeMessage(mailSession.getSession());
try {
message.setFrom(new InternetAddress(mailSession.getSrcEmail()));
// 设置接收人
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(mailMessage.getTagEmail()));
// 设置邮件主题
message.setSubject(mailMessage.getSubJect());
// 设置邮件内容
message.setContent(mailMessage.getContent(), "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message); if (LOGGER.isInfoEnabled()) {
LOGGER.info("MailSender [thread:" + Thread.currentThread().getName()
+ "] send email["
+ "from: " + mailSession.getSrcEmail()
+ ", to: " + mailMessage.getTagEmail()
+ ", subject: " + mailMessage.getSubJect()
+ ", content: " + mailMessage.getContent()
+ "]");
}
} catch (MessagingException e) {
e.printStackTrace();
} }
});
}
  // 未指定发送方,由队列轮流发送
public void sendTo(MailMessage mailMessage) {
if (mailMessage == null) {
String msg = "MailSender sendTo(), mailMessage not defined!";
if (LOGGER.isErrorEnabled()) {
LOGGER.error(msg);
}
throw new NullPointerException(msg);
} MailSession mailSession = queue.poll();
queue.add(mailSession); sendTo(mailSession, mailMessage);
} public void addSender(MailSession mailSession) {
if (mailSession == null) {
String msg = "MailSender addSender(), sender not defined!";
if (LOGGER.isErrorEnabled()) {
LOGGER.error(msg);
}
throw new NullPointerException(msg);
} queue.add(mailSession); if (LOGGER.isInfoEnabled()) {
LOGGER.info("MailSender add sender:[" + mailSession + "]");
}
} public MailSession removeSender(MailSession mailSession) {
if (queue.remove(mailSession)) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("MailSender remove sender:[" + mailSession + "]");
}
} return mailSession;
} }

测试:

 public class Demo {

     public static void main(String[] args) {
Executor executor = Executors.newCachedThreadPool(new NamedThreadFactory("ZC_Email"));
MailSender sender = new MailSender(executor);
sender.sendTo(new QQMailSession("xxxxx@qq.com", "xxxxx"),
new MailMessage("xxxx@163.com", "java邮件!", "这是使用java发送的邮件!请查收")); // TODO 记得线程池的关闭
} }

日志输出:

 18:24:02.871 [main] INFO com.zc.util.logger.LoggerFactory - using logger: com.zc.util.logger.slf4j.Slf4jLoggerAdapter
18:24:04.243 [main] INFO com.zc.util.mail.MailSender - [ZC-LOGGER] MailSender add sender:[MailSession{session=javax.mail.Session@1134affc, srcEmail='xxxxxx@qq.com', authCode='ijsuavtbasohbgbb'}], current host: 172.19.126.174
18:24:05.990 [ZC_Email-thread-1] INFO com.zc.util.mail.MailSender - [ZC-LOGGER] MailUtils [thread:ZC_Email-thread-1] send email[from: xxxxx@qq.com, to: xxxxxx@163.com, subject: java邮件!, content: 这是使用java发送的邮件!请查收], current host: 172.19.126.174

邮件截图:

java邮件发送工具的更多相关文章

  1. java 邮件发送工具类

    首先需要下载mail.jar文件,我个人通常是使用maven中心库的那个: <dependency> <groupId>javax.mail</groupId> & ...

  2. java 邮件发送工具类【来源网络自己已经实际应用】

    最近在做一个Java发送邮件的工具类,现在分享一下完整的代码 首先需要java邮件的包javax.mail-1.5.4.jar 之前因为链接给错了,很不好意思,现在重新发一次. 包在这里可以下载htt ...

  3. Java邮件发送工具类

    个人博客 地址:https://www.wenhaofan.com/article/20190507104851 引入Pom依赖 依赖于apchae email包,maven项目可直接加入以下依赖,普 ...

  4. Java 基于mail.jar 和 activation.jar 封装的邮件发送工具类

    准备工作 发送邮件需要获得协议和支持! 开启服务 POP3/SMTP 服务 如何开启 POP3/SMTP 服务:https://www.cnblogs.com/pojo/p/14276637.html ...

  5. 邮件发送工具类 SendMail.java

    package com.util; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.Simp ...

  6. JAVA邮件发送的简单实现

    JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件.这一机制被广泛的用在注 ...

  7. QT开发之旅四邮件发送工具

    终于有了一个晚上安静的写写程序,最近一直忙着公司商务上的事情,一直想用QT实现一个调用最底层socket通信来实现的邮件发送程序,以前用C#写过,微软都封装好的,不知道底层是如何实现的,只知道调用方法 ...

  8. java-基于JavaMail的Java邮件发送

    1.基于JavaMail的Java邮件发送:简单邮件发送 2.基于JavaMail的Java邮件发送:复杂邮件发送

  9. 基于JavaMail的Java邮件发送:复杂邮件发送

    参考:http://blog.csdn.net/xietansheng/article/details/51722660package com.bfd.ftp.utils;import java.ut ...

随机推荐

  1. [bzoj2982]combination_卢卡斯

    Combination bzoj-2982 题目大意:求$C_n^m/%10007$. 注释:$1\le n,m\le 2\cdot 10^9$. 想法:裸卢卡斯定理. 先处理出$mod$数之内的阶乘 ...

  2. codevs——2750 心系南方灾区

    2750 心系南方灾区  时间限制: 1 s  空间限制: 2000 KB  题目等级 : 青铜 Bronze 题解  查看运行结果     题目描述 Description 现在我国南方正在承受百年 ...

  3. mysql-performance-schema

    http://www.fromdual.com/mysql-performance-schema-hints http://www.cnblogs.com/cchust/

  4. Java发送邮件示例

    利用Java发送邮件示例: 1.发送QQ邮件 import java.util.Properties; import javax.mail.Message; import javax.mail.Mes ...

  5. 我的arcgis培训照片7

    来自:http://www.cioiot.com/successview-553-1.html

  6. 命令行man的帮助手册

    http://blog.csdn.net/gatieme/article/details/51656707 指定使用那种语音的手册,可以使用命令选项-M man -M /usr/share/man/z ...

  7. POJ 3342 Party at Hali-Bula (树形dp 树的最大独立集 判多解 好题)

    Party at Hali-Bula Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 5660   Accepted: 202 ...

  8. SDUST 2844-Mineral Water(数学)

    Mineral Water nid=24#time" title="C.C++.go.haskell.lua.pascal Time Limit1000ms Memory Limi ...

  9. [Python]基于权重的随机数2种实现方式

    问题: 比如我们要选从不同省份选取一个号码.每一个省份的权重不一样,直接选随机数肯定是不行的了,就须要一个模型来解决问题. 简化成以下的问题: 字典的key代表是省份,value代表的是权重,我们如今 ...

  10. Android基础新手教程——4.1.1 Activity初学乍练

    Android基础新手教程--4.1.1 Activity初学乍练 标签(空格分隔): Android基础新手教程 本节引言: 本节開始解说Android的四大组件之中的一个的Activity(活动) ...