欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java邮件发送工具

程序员文章站 2023-09-09 18:28:18
最近在web项目中,客户端注册时需要通过邮箱验证,服务器就需要向客户端发送邮件,我把发送邮件的细节进行了简易的封装: 最近在web项目中,客户端注册时需要通过邮箱验证,服务器就需要向客户端发送邮件,我把发送邮件的细节进行了简易的封装: 在maven中需要导入: 1 2

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

在maven中需要导入:

 1 <!--email-->
 2 <dependency>
 3    <groupid>javax.mail</groupid>
 4    <artifactid>mail</artifactid>
 5    <version>1.4.7</version>
 6 </dependency>
 7 <dependency>
 8    <groupid>javax.activation</groupid>
 9    <artifactid>activation</artifactid>
10    <version>1.1.1</version>
11 </dependency>

 

发送方的封装:

 1 import javax.mail.authenticator;
 2 import javax.mail.passwordauthentication;
 3 import javax.mail.session;
 4 import java.util.properties;
 5 
 6 public abstract class mailsession implements emailconstant {
 7     // mail的session对象
 8     protected session session;
 9     // 发送方邮箱
10     protected string srcemail;
11     // 发送方的授权码(不是邮箱登陆密码,如何获取请百度)
12     protected string authcode;
13 
14     protected mailsession(string srcemail, string authcode) {
15         this.srcemail = srcemail;
16         this.authcode = authcode;
17 
18         createsession();
19     }
20 
21     protected abstract void docreatesession(properties properties);
22 
23     private void createsession() {
24         // 获取系统属性,并设置
25         properties properties = system.getproperties();
26         // 由于不同的邮箱在初始化session时有不同的操作,需要由子类实现
27         docreatesession(properties);
28         properties.setproperty(mail_auth, "true");
29         
30         // 生成session对象
31         session = session.getdefaultinstance(properties, new authenticator() {
32             @override
33             public passwordauthentication getpasswordauthentication() {
34                 return new passwordauthentication(srcemail, authcode);
35             }
36         });
37     }
38 
39     public session getsession() {
40         return session;
41     }
42 
43     public string getsrcemail() {
44         return srcemail;
45     }
46 
47     @override
48     public string tostring() {
49         return "mailsession{" +
50                 "session=" + session +
51                 ", srcemail='" + srcemail + '\'' +
52                 ", authcode='" + authcode + '\'' +
53                 '}';
54     }
55 
56 }

emailconstant :

 1 /**
 2 *  需要的系统属性
 3 **/
 4 public interface emailconstant {
 5     string host_qq = "smtp.qq.com";
 6     string host_163 = "smtp.163.com";
 7     string mail_host = "mail.smtp.host";
 8     string mail_auth = "mail.smtp.auth";
 9     string mail_ssl_enable = "mail.smtp.ssl.enable";
10     string mail_ssl_socket_factory = "mail.smtp.ssl.socketfactory";
11 }

163邮箱的系统设置:

 1 public class wymailsession extends mailsession {
 2 
 3     public wymailsession(string srcemail, string authcode) {
 4         super(srcemail, authcode);
 5     }
 6 
 7     @override
 8     protected void docreatesession(properties properties) {
 9         properties.setproperty(mail_host, emailconstant.host_163);
10     }
11 
12 }

qq邮箱的系统设置:

 1 public class qqmailsession extends mailsession {
 2 
 3     public qqmailsession(string srcemail, string authcode) {
 4         super(srcemail, authcode);
 5     }
 6 
 7     @override
 8     protected void docreatesession(properties properties) {
 9         properties.setproperty(mail_host, emailconstant.host_qq);
10 
11         try {
12             mailsslsocketfactory mailsslsocketfactory = new mailsslsocketfactory();
13             mailsslsocketfactory.settrustallhosts(true);
14             properties.put(mail_ssl_enable, "true");
15             properties.put(mail_ssl_socket_factory, mailsslsocketfactory);
16         } catch (generalsecurityexception e) {
17             e.printstacktrace();
18         }
19     }
20 
21 }

发送的邮件封装:

 1 public class mailmessage {
 2     // 接收方邮箱
 3     private string tagemail;
 4     // 主题
 5     private string subject;
 6     // 内容
 7     private string content;
 8 
 9     public mailmessage(string tagemail, string subject, string content) {
10         this.tagemail = tagemail;
11         this.subject = subject;
12         this.content = content;
13     }
14 
15     public string gettagemail() {
16         return tagemail;
17     }
18 
19     public string getsubject() {
20         return subject;
21     }
22 
23     public string getcontent() {
24         return content;
25     }
26 
27     @override
28     public string tostring() {
29         return "mailmessage{" +
30                 "tagemail='" + tagemail + '\'' +
31                 ", subject='" + subject + '\'' +
32                 ", content='" + content + '\'' +
33                 '}';
34     }
35 
36 }

发送部分:

  1 import com.zc.util.logger.logger;
  2 import com.zc.util.logger.loggerfactory;
  3 
  4 import javax.mail.message;
  5 import javax.mail.messagingexception;
  6 import javax.mail.transport;
  7 import javax.mail.internet.internetaddress;
  8 import javax.mail.internet.mimemessage;
  9 import java.util.queue;
 10 import java.util.concurrent.concurrentlinkedqueue;
 11 import java.util.concurrent.executor;
 12 
 13 public class mailsender {
 14 
 15     private static final logger logger = loggerfactory.getlogger(mailsender.class);
 16   // 这个队列是有在多个发送方的情况下,可以轮流发送
 17     private final queue<mailsession> queue = new concurrentlinkedqueue<>();
 18   // 使用线程池,让线程去完成发送
 19     private final executor executor;
 20 
 21     public mailsender(executor executor) {
 22         this.executor = executor;
 23     }
 24   // 指定发送方,发送邮件
 25     public void sendto(mailsession mailsession, mailmessage mailmessage) {
 26         if (mailsession == null) {
 27             string msg = "mailsender sendto(), mailsession can not null!";
 28             if (logger.iserrorenabled()) {
 29                 logger.error(msg);
 30             }
 31             throw new nullpointerexception(msg);
 32         }
 33 
 34         if (!queue.contains(mailsession)) {
 35             addsender(mailsession);
 36         }
 37 
 38         executor.execute(new runnable() {
 39             @override
 40             public void run() {
 41                 message message = new mimemessage(mailsession.getsession());
 42                 try {
 43                     message.setfrom(new internetaddress(mailsession.getsrcemail()));
 44                     // 设置接收人
 45                     message.addrecipient(message.recipienttype.to,
 46                             new internetaddress(mailmessage.gettagemail()));
 47                     // 设置邮件主题
 48                     message.setsubject(mailmessage.getsubject());
 49                     // 设置邮件内容
 50                     message.setcontent(mailmessage.getcontent(), "text/html;charset=utf-8");
 51                     // 发送邮件
 52                     transport.send(message);
 53 
 54                     if (logger.isinfoenabled()) {
 55                         logger.info("mailsender [thread:" + thread.currentthread().getname()
 56                                 + "] send email["
 57                                 + "from: " + mailsession.getsrcemail()
 58                                 + ", to: " + mailmessage.gettagemail()
 59                                 + ", subject: " + mailmessage.getsubject()
 60                                 + ", content: " + mailmessage.getcontent()
 61                                 + "]");
 62                     }
 63                 } catch (messagingexception e) {
 64                     e.printstacktrace();
 65                 }
 66 
 67             }
 68         });
 69     }
 70   // 未指定发送方,由队列轮流发送
 71     public void sendto(mailmessage mailmessage) {
 72         if (mailmessage == null) {
 73             string msg = "mailsender sendto(), mailmessage not defined!";
 74             if (logger.iserrorenabled()) {
 75                 logger.error(msg);
 76             }
 77             throw new nullpointerexception(msg);
 78         }
 79 
 80         mailsession mailsession = queue.poll();
 81         queue.add(mailsession);
 82 
 83         sendto(mailsession, mailmessage);
 84     }
 85 
 86     public void addsender(mailsession mailsession) {
 87         if (mailsession == null) {
 88             string msg = "mailsender addsender(), sender not defined!";
 89             if (logger.iserrorenabled()) {
 90                 logger.error(msg);
 91             }
 92             throw new nullpointerexception(msg);
 93         }
 94 
 95         queue.add(mailsession);
 96 
 97         if (logger.isinfoenabled()) {
 98             logger.info("mailsender add sender:[" + mailsession + "]");
 99         }
100     }
101 
102     public mailsession removesender(mailsession mailsession) {
103         if (queue.remove(mailsession)) {
104             if (logger.isinfoenabled()) {
105                 logger.info("mailsender remove sender:[" + mailsession + "]");
106             }
107         }
108 
109         return mailsession;
110     }
111 
112 }

 

测试:

 1 public class demo {
 2 
 3     public static void main(string[] args) {
 4         executor executor = executors.newcachedthreadpool(new namedthreadfactory("zc_email"));
 5         mailsender sender = new mailsender(executor);
 6         sender.sendto(new qqmailsession("xxxxx@qq.com", "xxxxx"),
 7                 new mailmessage("xxxx@163.com", "java邮件!", "这是使用java发送的邮件!请查收"));
 8         
 9         // todo 记得线程池的关闭
10     }
11 
12 }

日志输出:

1 18:24:02.871 [main] info com.zc.util.logger.loggerfactory - using logger: com.zc.util.logger.slf4j.slf4jloggeradapter
2 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
3 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邮件发送工具