1、配置依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2、工具类
package com.thorgene.clinical.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
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.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
public class MailUtil {
private static final String ALIDM_SMTP_HOST = "smtp.企业域名.com";
private static final int ALIDM_SMTP_PORT = 25;// 或80
private static String user; //发件人的账号
private static String password; //发件人的密码
private static String receiveUser; //收件人
private static String ccUser; //抄送人
//配置文件读取
static {
InputStream is = MailUtil.class.getResourceAsStream("/application.properties");
Properties prop = new Properties();
try {
prop.load(is);
} catch (IOException e1) {
e1.printStackTrace();
}
user = prop.getProperty("mail.user");
password = prop.getProperty("mail.password");
receiveUser = prop.getProperty("mail.receiveUser");
ccUser = prop.getProperty("mail.ccUser");
}
public static void main(String[] args) {
List<String> fileList = new ArrayList<String>();
fileList.add("/private/tmp/11111.docx");
fileList.add("/private/tmp/22222.docx");
send("测试主题", "测试正文", fileList);
}
/**
* 发送邮件
* @param toEmail 收件人邮箱地址
* @param subject 邮件标题
* @param content 邮件内容 可以是html内容
* @param filePath 附加路径
*/
public static void send(String subject, String content, List<String> fileList) {
Session mailSession = loadMailSession();//获取session,设置发送邮件属性
mailSession.setDebug(true);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
try {
// 设置发件人
message.setFrom(new InternetAddress(user));
//可选,设置回信地址
Address[] a = new Address[1];
a[0] = new InternetAddress(user);
message.setReplyTo(a);
// 设置收件人
//InternetAddress to = new InternetAddress("xxxx@qq.com");
//message.setRecipient(MimeMessage.RecipientType.TO, to);
//如果同时发给多人,才将上面两行替换为如下(因为部分收信系统的一些限制,尽量每次投递给一个人;同时我们限制单次允许发送的人数是30人)
String[] receives = receiveUser.split(",");
InternetAddress[] adds = new InternetAddress[receives.length];
for (int i = 0; i < adds.length; i++) {
adds[i] = new InternetAddress(receives[i]);
}
message.setRecipients(MimeMessage.RecipientType.TO, adds);
// 设置多个抄送地址
//if(null != ccUser && !ccUser.isEmpty()){
// @SuppressWarnings("static-access")
// InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
// message.setRecipients(MimeMessage.RecipientType.CC, internetAddressCC);
//}
Multipart multipart = new MimeMultipart();
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(content);
multipart.addBodyPart(mbpContent);
//往邮件中添加附件
for (int i = 0; i < fileList.size(); i++) {
MimeBodyPart mbpFile = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList.get(i));
mbpFile.setDataHandler(new DataHandler(fds));
try {
mbpFile.setFileName(MimeUtility.encodeText(fds.getName()));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
multipart.addBodyPart(mbpFile);
}
message.setContent(multipart);
message.setSentDate(new Date());
// 设置邮件标题
message.setSubject(subject);
// 发送邮件
Transport.send(message);
} catch (MessagingException e) {
String err = e.getMessage();
// 在这里处理message内容, 格式是固定的
System.out.println(err);
}
}
/**
* 获取session,设置发送邮件属性
* @return
*/
private static Session loadMailSession() {
try {
// 配置发送邮件的环境属性
final Properties props = new Properties();
// 表示SMTP发送邮件,需要进行身份验证
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", ALIDM_SMTP_HOST);
// props.put("mail.smtp.port", ALIDM_SMTP_PORT);
// 如果使用ssl,则去掉使用25端口的配置,进行如下配置,
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.port", "465");
// 发件人的账号
props.put("mail.user", user);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", password);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
return Session.getInstance(props, authenticator);
} catch (Exception e) {
e.printStackTrace();
System.out.println("mail session is null");
}
return null;
}
}