服务器之家

服务器之家 > 正文

Java封装好的mail包发送电子邮件的类

时间:2020-03-21 13:48     来源/作者:hebedich

下面代码是利用Java mail包封装了一个发送邮件的类

?
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
 
public class SendMail {
  private static final String MAIL_ADDRESS_REGEX = "^[\\w\\.=-]+@[\\w\\.-]+\\.[\\w]{2,3}$";
 
  private String mailServer;
  private String sender;
  private String[] receiver;
 
  public SendMail(){
 
  }
 
  public void setMailBasicInfo(String mailServer,String sender,String receiver){
    this.mailServer = mailServer;
    this.sender = sender;
    this.receiver =receiver.split(",");
  }
 
  public void setMailBasicInfo(String mailServer,String sender,String[] users){
    this.mailServer = mailServer;
    this.sender = sender;
    this.receiver = users;
  }
 
  public void setMailBasicInfo(String mailServer,String sender,List<String> users){
    this.mailServer = mailServer;
    this.sender = sender;
    this.receiver = new String[users.size()];
    users.toArray(this.receiver);
  }
 
  public boolean send(String subject, String content, List<String> fileNames)
  {
    subject = subject==null?"":subject;
    content = content==null?"":content;
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServer);
    Session session = Session.getInstance(props, null);
    try
    {
      InternetAddress[] receiver = getReceiverList();
      if (receiver.length == 0)
      {
        System.out.println("receiver is null");
        return false;
      }
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(sender));
      msg.setRecipients(Message.RecipientType.TO, receiver);
      msg.setSubject(subject);
      msg.setSentDate(new Date());
 
      Multipart container = new MimeMultipart();
      MimeBodyPart textBodyPart = new MimeBodyPart();
      textBodyPart.setContent(content.toString(), "text/html;charset=gbk");
      container.addBodyPart(textBodyPart);
 
      doAttachFile(container,fileNames);
      msg.setContent(container);
      System.out.println("begin send mail");
      Transport.send(msg);
      System.out.println("send mail success");
    }
    catch (MessagingException e)
    {
      System.out.println("send mail fail");
      System.out.println(e);
      return false;
    }
    catch(Exception e){
      return false;
    }
    return true;
  }
 
  public boolean send(String subject, String content){
    return send(subject,content,null);
  }
 
  public boolean send(String subject){
    return send(subject,null);
  }
 
  private void doAttachFile(Multipart container, List<String> fileNames) throws MessagingException{
    if(fileNames==null || fileNames.size()==0)
      return;
    for(String filename:fileNames){
      File f = new File(filename);
      if(!f.isFile())
        continue;
      System.out.println("the attach file is:"+filename);
      MimeBodyPart fileBodyPart = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(f);// 要发送的附件地址
      fileBodyPart.setDataHandler(new DataHandler(fds));
      fileBodyPart.setFileName(fds.getName());// 设置附件的名称
      container.addBodyPart(fileBodyPart);
    }
  }
 
  private InternetAddress[] getReceiverList() throws AddressException
  {
    ArrayList<InternetAddress> toList = new ArrayList<InternetAddress>();
    for (int i = 0; i < receiver.length; ++i)
    {
      if (receiver[i].matches(MAIL_ADDRESS_REGEX))
      {
        toList.add(new InternetAddress(receiver[i]));
      }
    }
 
    return (InternetAddress[]) toList.toArray(new InternetAddress[toList.size()]);
  }
}

使用举例

?
1
2
3
4
5
6
7
8
9
10
String host = "168.xx.xx.xx"; //邮件服务器的地址
String subject = "发送邮件的主题";
String sender = "test@gmail.com";
List<String> receivers = new ArrayList<String>();
receivers.add("user1@263.com");
receivers.add("user2@263.com");
String content = "邮件主题";
SendMail sendMail = new SendMail();
sendMail.setMailBasicInfo(host, sender, receivers);
sendMail.send(subject, content, null); //没有附件

正文也可以是html内容,如

?
1
String content = "<html>详细信息:<a href='xxxx'>请点击查看!</a></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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package com.message.base.email;
 
import com.message.base.spring.ApplicationHelper;
import com.message.base.utils.StringUtils;
import com.message.base.utils.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
 
/**
 * 发送邮件服务器.
 *
 * @author sunhao(sunhao.java@gmail.com)
 * @version V1.0, 13-3-25 上午6:19
 */
public class EmailServer {
  private static final Logger logger = LoggerFactory.getLogger(EmailServer.class);
  //spring中配置
  /**邮箱服务器配置**/
  private List<EmailConfig> config;
  /**是否开启debug调试模式**/
  private boolean isDebug = false;
  /**是否启用身份验证**/
  private boolean isAuth = true;
  /**验证类型**/
  private String authType = "auth";
 
  /**
   * 私有化默认构造器,使外部不可实例化
   */
  private EmailServer(){}
 
  /**
   * 单例,保证上下文中只有一个EmailServer
   *
   * @return EmailServer
   */
  public static EmailServer getInstance(){
    return ApplicationHelper.getInstance().getBean(EmailServer.class);
  }
 
  /**
   * 发送普通邮件(单个接收人)
   *
   * @param username   发件人用户名
   * @param password   发件人密码
   * @param title     邮件标题
   * @param content    邮件正文
   * @param receiver   单个接收人
   * @return
   */
  public boolean sendTextMail(String username, String password, String title, String content, String receiver){
    return this.sendTextMail(username, password, title, content, Collections.singletonList(receiver));
  }
 
  /**
   * 发送普通邮件(多个接收人)
   *
   * @param username   发件人用户名
   * @param password   发件人密码
   * @param title     邮件标题
   * @param content    邮件正文
   * @param receivers   多个接收人
   * @return
   */
  public boolean sendTextMail(String username, String password, String title, String content, List<String> receivers){
    Authentication auth = null;
    if(this.isAuth()){
      //如果需要身份认证,则创建一个密码验证器
      auth = new Authentication(username, password);
    }
 
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", this.isAuth() ? "true" : "false");
    props.setProperty("mail.transport.protocol", "auth");
    EmailConfig config = this.getEmailConfig(username);
    props.setProperty("mail.smtp.host", config.getSmtp());
    props.setProperty("mail.smtp.port", config.getPort() + "");
 
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(this.isDebug);
 
    Message message = this.makeTextMail(session, title, content, username, receivers, false);
    try {
      Transport.send(message);
 
      return true;
    } catch (MessagingException e) {
      logger.error(e.getMessage(), e);
      return false;
    }
  }
 
  /**
   * 发送HTML邮件(单个接收人)
   *
   * @param username   发件人用户名
   * @param password   发件人密码
   * @param title     邮件标题
   * @param content    邮件正文
   * @param receiver   单个接收人
   * @return
   */
  public boolean sendHtmlMail(String username, String password, String title, String content, String receiver){
    return this.sendHtmlMail(username, password, title, content, Collections.singletonList(receiver));
  }
 
  /**
   * 发送HTML邮件(多个接收人)
   *
   * @param username   发件人用户名
   * @param password   发件人密码
   * @param title     邮件标题
   * @param content    邮件正文
   * @param receivers   多个接收人
   * @return
   */
  public boolean sendHtmlMail(String username, String password, String title, String content, List<String> receivers){
    Authentication auth = null;
    if(this.isAuth()){
      //如果需要身份认证,则创建一个密码验证器
      auth = new Authentication(username, password);
    }
 
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", this.isAuth() ? "true" : "false");
    props.setProperty("mail.transport.protocol", "auth");
    EmailConfig config = this.getEmailConfig(username);
    props.setProperty("mail.smtp.host", config.getSmtp());
    props.setProperty("mail.smtp.port", config.getPort() + "");
 
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(this.isDebug);
 
    Message message = this.makeTextMail(session, title, content, username, receivers, true);
    try {
      Transport.send(message);
 
      return true;
    } catch (MessagingException e) {
      logger.error(e.getMessage(), e);
      return false;
    }
  }
 
  /**
   * 获取邮件服务器配置
   *
   * @param email     邮箱地址
   * @return
   */
  private EmailConfig getEmailConfig(String email){
    String mailServiceDomainName = this.getMailServiceDomainName(email);
    for(EmailConfig config : this.config) {
      if(config.getName().equals(mailServiceDomainName)){
        return config;
      }
    }
    return null;
  }
 
  /**
   * 创建邮件message
   *
   * @param session    根据配置获得的session
   * @param title     邮件主题
   * @param content    邮件的内容
   * @param from     发件者
   * @param receivers   收件者
   * @param isHtmlMail  是否是html邮件
   */
  private Message makeTextMail(Session session, String title, String content, String from, List<String> receivers, boolean isHtmlMail){
    Message message = new MimeMessage(session);
    try {
      /**标题**/
      logger.info("this mail's title is {}", title);
      message.setSubject(title);
      /**内容**/
      logger.info("this mail's content is {}", content);
      if(isHtmlMail){
        //是html邮件
        message.setContent(content, "text/html;charset=utf-8");
      } else {
        //普通邮件
        message.setText(content);
      }
      /**发件者地址**/
      logger.info("this mail's sender is {}", from);
      Address fromAddress = new InternetAddress(from);
      message.setFrom(fromAddress);
      /**接收者地址**/
      Address[] tos = new InternetAddress[receivers.size()];
      for(int i = 0; i < receivers.size(); i++){
        String receiver = receivers.get(i);
        if(ValidateUtils.isEmail(receiver)){
          tos[i] = new InternetAddress(receiver);
        }
      }
      /**发件时间**/
      message.setSentDate(new Date());
 
      message.setRecipients(Message.RecipientType.TO, tos);
    } catch (MessagingException e) {
      logger.error(e.getMessage(), e);
      e.printStackTrace();
    }
 
    return message;
  }
 
  /**
   * 获取邮箱域名
   *
   * @param email   邮箱
   * @return
   */
  private String getMailServiceDomainName(String email){
    if(StringUtils.isEmpty(email)){
      return "";
    } else {
      int firstIndex = StringUtils.indexOf(email, "@");
      int secondIndex = StringUtils.lastIndexOf(email, ".");
 
      return StringUtils.substring(email, firstIndex + 1, secondIndex);
    }
  }
 
  public List<EmailConfig> getConfig() {
    return config;
  }
 
  public void setConfig(List<EmailConfig> config) {
    this.config = config;
  }
 
  public boolean isDebug() {
    return isDebug;
  }
 
  public void setDebug(boolean debug) {
    isDebug = debug;
  }
 
  public boolean isAuth() {
    return isAuth;
  }
 
  public void setAuth(boolean auth) {
    isAuth = auth;
  }
 
  public String getAuthType() {
    return authType;
  }
 
  public void setAuthType(String authType) {
    this.authType = authType;
  }
}

调用方式如下

?
1
2
3
4
5
6
7
8
9
public boolean sendMail() throws Exception {
  List<String> receivers = new ArrayList<String>();
  receivers.add("sunhao0550@163.com");
  receivers.add("sunhao0550@sina.cn");
  EmailServer.getInstance().sendHtmlMail("message_admin@163.com", "这里是密码", "测试发送HTML邮件",
      "<span style='color: red;font-size: 20pt'>测试发送HTML邮件</span><a href='http://www.baidu.com' target='_blank'>链接到百度</a>", receivers);
  return EmailServer.getInstance().sendTextMail("message_admin@163.com", "这里是密码", "测试发送文本邮件",
      "测试发送文本邮件测试发送文本邮件测试发送文本邮件", receivers);
}

PS:正在考虑扩展,如果把这几个类封在jar包中,如何进行邮件服务器配置的扩展.

如有不好之处,欢迎拍砖.

标签:

相关文章

热门资讯

玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情 2019-06-22
返回顶部