依赖的maven 或者 jar
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
调用方法(测试用)
String title = "测试邮件";
String text = "这个邮件正文就省略了了了";
String path = "C:\\Users\\72041860\\Desktop\\11.txt";
EmailUtil.sendEmail(to, title, text, path);
EmailUtil.java
package com.saosao3.yulisao3.util;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
public class EmailUtil {
public EmailUtil() {
}
/** -------------不同的发件箱 需修改以下三个配置--------------------- */
//默认发件邮箱
static final String FROM = "xxxx@163.com";
//发件箱密码 或者 授权码
static final String PWD = "123456";
//发件主机
static final String HOST = "smtp.163.com";
// 设置全局编码
static final String ENCONDING = "text/html;charset=utf-8";
/** ------------------------------------------------------------- */
public static void sendEmail(String to, String title, String text, String path) {
// 获取系统属性
Properties properties = System.getProperties();
// 设置发件箱主机
properties.setProperty("mail.smtp.host", HOST);
// 设置发件箱是否有身份认证
properties.put("mail.smtp.auth", true);
// 设置SSL加密
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
// 获取session
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM, PWD);
}
});
try {
// 创建Mime
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(FROM));
// 设置收件人
message.addRecipients(Message.RecipientType.TO, to);
// 邮件主题
message.setSubject(title);
// 设置发送时间
message.setSentDate(new Date());
File file = new File(path);
if (file.exists() && file.isFile()) { // 有附件模式
System.out.println("本邮件有附件需要发送...");
// 多重消息(正文+附件 两部分组成)
Multipart multipart = new MimeMultipart();
// 邮件正文
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(text,ENCONDING); // 写入邮件正文
multipart.addBodyPart(bodyPart);
// 添加附件
bodyPart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(path);
bodyPart.setDataHandler(new DataHandler(dataSource));
bodyPart.setFileName(file.getName());
multipart.addBodyPart(bodyPart);
// 正文+附件一起加入
message.setContent(multipart);
message.saveChanges();
} else { // 无附件模式
// 正文
message.setContent(text,ENCONDING);
}
// 发送
Transport.send(message);
System.out.println("发送成功。");
} catch (MessagingException e) {
e.printStackTrace();
} finally {
System.out.println("邮件已发送,请检查状态");
}
}
}
或者用HtmlEmail 来发邮件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.2</version>
</dependency>
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmailUtil {
private static final Logger LOG = LoggerFactory.getLogger(EmailUtil.class);
private static String MAIL_SMTP_HOST = "smtp.163.com"; // 邮件主机地址
private static String MAIL_FROM_EAMIL = "xxxx@163.com"; // 发件人邮箱
private static String MAIL_FROM_NAME = "系统通知邮件"; // 发件人名称
private static int MAIL_SMTP_PORT = 25; // 邮件服务端口
private static String MAIL_ENCODING = "GBK";
private static Boolean MAIL_SMTP_SSL = false;
/**
*
* @param message 邮件正文
* @param subject 邮件主题
* @param emailTo 收件人 多个收件人分号分隔
*/
public static void sendEmail(final String message,final String subject,String emailTo) {
try {
HtmlEmail email = new HtmlEmail();
email.setHostName(MAIL_SMTP_HOST);
email.setSmtpPort(MAIL_SMTP_PORT);
email.setCharset(MAIL_ENCODING);
email.setSSLOnConnect(MAIL_SMTP_SSL);
email.setFrom(MAIL_FROM_EAMIL, MAIL_FROM_NAME);
email.addTo(emailTo.split(";"));
email.setSubject(subject);
email.setMsg(message); // 类似的还有 setTextMsg setHtmlMsg
email.send();
} catch (Exception e) {
LOG.error("Email Error: {}", e.getMessage());
}
}
}
方法二的 email.setHtmlMsg(message); // message则是一段html代码
示例如下
html代码如下, 复制到文本保存后改.txt后缀为.html,双击浏览器打开查看效果,调整到满意效果后复制到代码里面去
<!DOCTYPE html>
<html>
<body>
<p>Dear team</p>
<p>XXX系统业务失败数据如下,请及时处理!</p>
<table style="border-collapse: collapse;">
<tr>
<th style="border: 1px solid black; padding: 8px;">序号</th>
<th style="border: 1px solid black; padding: 8px;">订单号</th>
</tr>
<tr>
<td style="border: 1px solid black; padding: 8px;">1</td>
<td style="border: 1px solid black; padding: 8px;">2022030400001</td>
</tr>
<tr>
<td style="border: 1px solid black; padding: 8px;">2</td>
<td style="border: 1px solid black; padding: 8px;">2022030400002</td>
</tr>
</table>
</body>
</html>
粘贴后代码
private String getMessageInfo(List<OrderRecord> failList) {
if (CollectionUtils.isEmpty(failList)) {
return null;
}
StringBuffer resp = new StringBuffer();
resp.append("<p>Dear team:</p>");
resp.append("<p> The failure data of order is as follows. Please handle it in a timely manner!</p>");
resp.append("<table style='border-collapse: collapse;'>");
resp.append("<tr>");
resp.append("<th style='border: 1px solid black; padding: 8px;'>序号</th>");
resp.append("<th style='border: 1px solid black; padding: 8px;'>订单号</th>");
resp.append("</tr>");
for (OrderRecord record : failList) {
resp.append("<tr>");
resp.append("<th style='border: 1px solid black; padding: 8px;'>"+ record.getId() +"</th>");
resp.append("<th style='border: 1px solid black; padding: 8px;'>"+ record.getOrderNo() +"</th>");
resp.append("</tr>");
}
resp.append("</table>");
return resp.toString();
}