import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
public class EmailUtil {
private static Logger logger = LoggerFactory.getLogger(EmailUtil.class);
private static Properties properties;
static {
InputStream in;
try {
properties = new Properties();
in = EmailUtil.class.getResourceAsStream("/application.properties");
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String dir = "D:/rpt/number";
File dirFile = new File(dir);
if (!dirFile.exists())
dirFile.mkdirs();
String file = dir + "/test.txt";
sendEmail(file, "****", "2020期");
}
public static boolean sendEmail(String filename, String subject, String msg) {
try {
new Thread(new Runnable() {
public void run() {
sendEmailz(filename, subject, msg);
}
}).start();
} catch (Exception e) {
logger.info("异步发送邮件失败!", e);
return false;
}
return true;
}
public static boolean sendEmailz(String filename, String subject, String msg) {
try {
Properties prop = EmailUtil.getConfig("application-" + EmailUtil.getProp("spring.profiles.active") + ".properties");
String sender = EmailUtil.getPropValue(prop, "sender");
String cc = EmailUtil.getPropValue(prop, "cc");
String bcc = EmailUtil.getPropValue(prop, "bcc");
String password = EmailUtil.getPropValue(prop, "password");
boolean s;
File file2 = new File(filename);
if (!file2.exists()) {
logger.info("要发送文件不存在!");
return true;
}
String[] c = cc.split(",");
List listCC = Arrays.asList(c);
String[] b = bcc.split(",");
List listBCC = Arrays.asList(b);
String host = "smtp.163.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender, password);
}
});
if (!cc.isEmpty()) {
s = sendMailC(listCC, subject, msg, filename, sender, session);
if (s == false) {
logger.error("明发邮件失败,检查邮件格式是否正确!");
return false;
}
} else {
logger.info("邮件发送未设置收件人(明发)!");
}
if (!bcc.isEmpty()) {
s = sendMailB(listBCC, subject, msg, filename, sender, session);
if (s == false)
logger.error("密发邮件失败,检查邮件格式是否正确!");
} else {
logger.info("邮件发送未设置收件人(密发)!");
}
} catch (Exception e) {
logger.info("检查邮件发送过程错误!", e);
}
return true;
}
private static boolean sendMailC(List<String> receive, String subject, String msg, String filename, String sender, Session session) throws Exception {
MimeMessage message = new MimeMessage(session);
Address[] internetAddressTo = new InternetAddress[receive.size()];
for (int i = 0; i < internetAddressTo.length; i++) {
internetAddressTo[i] = new InternetAddress(receive.get(i));
}
message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
send(message, subject, msg, filename, sender);
return true;
}
private static boolean sendMailB(List<String> receive, String subject, String msg, String filename, String sender, Session session) throws Exception {
MimeMessage message = new MimeMessage(session);
Address[] internetAddressTo = new InternetAddress[receive.size()];
for (int i = 0; i < internetAddressTo.length; i++) {
internetAddressTo[i] = new InternetAddress(receive.get(i));
message.setRecipients(MimeMessage.RecipientType.BCC, receive.get(i));
send(message, subject, msg, filename, sender);
}
return true;
}
public static boolean send(MimeMessage message, String subject, String msg, String filename, String sender) {
try {
message.setFrom(new InternetAddress(sender));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(msg);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
String fileN = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
messageBodyPart.setFileName(MimeUtility.encodeText(fileN));
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
} catch (Exception e) {
logger.info("邮件准备发送失败", e);
return false;
}
return true;
}
public static String getProp(String key) {
return properties.getProperty(key);
}
public static Properties getConfig(String name) {
Properties props = null;
try {
props = new Properties();
InputStream in = EmailUtil.class.getClassLoader().getResourceAsStream(name);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
props.load(bf);
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return props;
}
public static String getPropValue(Properties prop, String key) {
if (key == null || "".equals(key.trim())) {
return null;
}
String value = prop.getProperty(key);
if (value == null) {
return null;
}
value = value.trim();
if (value.startsWith("${") && value.endsWith("}") && value.contains(":")) {
int indexOfColon = value.indexOf(":");
String envName = value.substring(2, indexOfColon);
String envValue = System.getenv(envName);
if (envValue == null) {
return value.substring(indexOfColon + 1, value.length() - 1);
}
return envValue;
}
return value;
}
}
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.6</version>
</dependency>