加入javax.mail包依赖:
<pre name="code" class="java"><dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${mail.version}</version>
</dependency>
</pre><pre code_snippet_id="1589522" snippet_file_name="blog_20160226_4_2264635" name="code" class="java">package me.text.sender.mail;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 邮件发送类
*
* @author wdmyong
*
*/
public class MailSender {
private static final Logger LOGGER = LoggerFactory.getLogger(MailSender.class);
private static final String MAIL_HOST = "mail.smtp.host";
private static final String MAIL_AUTH = "mail.smtp.auth";
private static final String MAIL_PROTOCOL = "mail.transport.protocol";
private static final String MAIL_SENDER_USERNAME = "mail.sender.username";
private static final String MAIL_SENDER_PASSWD = "mail.sender.password";
private static final String MAIL_RECEIVES = "mail.receiver.hosts";
private String host = "smtp.126.com";
private String protocol = "smtp";
private String auth = "true";
private String userName = ""; //用来发送邮件的邮箱
private String passWord = ""; //邮箱密码,126好像开通smtp之后有一个密码,不用邮箱的密码
private List<String> receivers = new ArrayList<String>();
private Session session;
private MimeMessage message;
private Transport transport;
public MailSender() {
initConf();
}
/**
* 发送邮件
*
* @param subject 邮件主题
* @param mailContent 邮件内容
* @return
*/
public String mailSend(String subject, String mailContent) {
return mailSend(subject, mailContent, null, null);
}
/**
* 发送邮件
*
* @param subject 邮件主题
* @param mailContent 邮件内容
* @param attachment 附件文件
* @return
*/
public String mailSend(String subject, String mailContent, File attachment) {
return mailSend(subject, mailContent, attachment, null);
}
/**
* 发送邮件
*
* @param subject 邮件主题
* @param mailContent 邮件内容
* @param reciveList 收件人列表
* @return
*/
public String mailSend(String subject, String mailContent, List<String> receiveList) {
return mailSend(subject, mailContent, null, receiveList);
}
/**
* 发送邮件
*
* @param subject 邮件主题
* @param mailContent 邮件内容
* @param attachment 附件文件
* @param reciveList 收件人列表
* @return
*/
public String mailSend(String subject, String mailContent, File attachment, List<String> receiveList) {
ReturnCode returnCode = ReturnCode.MAIL_SEND_FAILED;
if (receiveList != null) {
receivers = receiveList;
}
if (receivers == null || receivers.size() == 0) {
returnCode = ReturnCode.MAIL_RECEIVERS_EMPTY;
return returnCode.getInformation();
}
try {
initProperties();
InternetAddress from = new InternetAddress(this.userName);
message.setFrom(from);
Address[] tos = new InternetAddress[receivers.size()];
for (int i = 0; i < receivers.size(); i++) {
tos[i] = new InternetAddress(receivers.get(i));
}
message.setRecipients(Message.RecipientType.TO, tos);
message.setSubject(subject);
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(mailContent, "text/html;charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(contentPart);
// 添加附件
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
message.setContent(multipart);
message.saveChanges();
transport.sendMessage(message, message.getAllRecipients());
LOGGER.info("send mail success!");
returnCode = ReturnCode.SUCCESS;
} catch (Exception e) {
returnCode.setInformation(e.toString());
LOGGER.error("send mail failed: {}", returnCode, e);
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException ex) {
LOGGER.error("transport close error ", ex);
}
}
}
return returnCode.getInformation();
}
/**
* 初始化通信信息
*/
private void initProperties() throws Exception {
String receiverString = "";
for (String str : receivers) {
receiverString += str + ",";
}
receiverString = receiverString.substring(0,
receiverString.length() - 1);
Properties properties = new Properties();
properties.setProperty(MAIL_HOST, host);
properties.setProperty(MAIL_AUTH, auth);
properties.setProperty(MAIL_SENDER_USERNAME, userName);
properties.setProperty(MAIL_SENDER_PASSWD, passWord);
properties.setProperty(MAIL_RECEIVES, receiverString);
session = Session.getInstance(properties);
session.setDebug(false);
message = new MimeMessage(session);
transport = session.getTransport(protocol);
transport.connect(host, userName, passWord);
}
/**
* 加载配置,没有则使用默认配置
*/
private void initConf() {
try {
// 可以通过配置文件修改默认配置
InputStream in = MailSender.class.getResourceAsStream("/mail.properties");
if (in != null) {
Properties properties = new Properties();
properties.load(in);
String auth = properties.getProperty(MAIL_AUTH);
String mailHost = properties.getProperty(MAIL_HOST);
String mailProtocol = properties.getProperty(MAIL_PROTOCOL);
String senderUsername = properties.getProperty(MAIL_SENDER_USERNAME);
String senderPasswd = properties.getProperty(MAIL_SENDER_PASSWD);
String receivers = properties.getProperty(MAIL_RECEIVES);
if (StringUtils.isNotBlank(auth)) {
this.auth = auth;
}
if (StringUtils.isNotBlank(mailHost)) {
this.host = mailHost;
}
if (StringUtils.isNotBlank(mailProtocol)) {
this.protocol = mailProtocol;
}
if (senderUsername != null && senderPasswd != null) {
this.userName = senderUsername;
this.passWord = senderPasswd;
}
if (receivers != null) {
List<String> list = new ArrayList<String>();
// 多个收件人以","隔开
for (String str : receivers.split(",")) {
list.add(str);
}
this.receivers = list;
}
}
} catch (Exception e) {
LOGGER.error("init configure error", e);
}
}
<span style="font-family: Arial, Helvetica, sans-serif;">public enum ReturnCode {</span>
SUCCESS(0, "success"),
MAIL_SEND_FAILED(30000, "邮件发送失败"),
MAIL_RECEIVERS_EMPTY(30001, "没有设置收件人");
private Integer code;
private String information;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
private ReturnCode(Integer code, String information) {
this.code = code;
this.information = information;
}
}