前言:最近接到一个需求,需要根据所监控设备的信息,在出现问题时发送企业微信进行预警。
POM依赖
<!-- 邮件 -->
<dependency><groupId>com.sun.mail</groupId><artifactId>jakarta.mail</artifactId><version>1.6.7</version>
</dependency>
yml配置项
mail:service:smtpSslEnable: truesmtpAuth: truesmtpHost: smtp.exmail.qq.com # 企业微信的hostsmtpPort: 465account: 发信人邮箱名password: 发信人邮箱密码
邮箱工具类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Data
@Component
@ConfigurationProperties(prefix = "mail.service")
public class MailServiceProperties {private String account;/*** 登录密码*/private String password;/*** 邮件服务器地址*/private String smtpHost;/*** 发信端口*/private String smtpPort;/*** 是否认证*/private String smtpAuth;private String smtpSslEnable;}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class MailContent {private String aliasName;private String recipients;private String subject;private String content;
}
import com.ruoyi.common.config.MailServiceProperties;
import com.ruoyi.common.constant.MailContent;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.activation.DataHandler;
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.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;@Slf4j
@Component
public class MailUtils {@Autowiredprivate MailServiceProperties properties;/*** 批量发送邮件** @param aliasName 别名* @param subject 主题* @param content 内容*/public void batchSendEmail(String recipientList, String aliasName, String subject, String content) {if (!StringUtils.isEmpty(recipientList)) {String[] arrs = recipientList.split(",");for (String arr : arrs) {send(new MailContent(aliasName, arr, subject, content));}} else {log.error("收件人为空,发送失败。");}}/*** 批量发送邮件 带图片** @param aliasName 别名* @param subject 主题* @param content 内容* @param is 图片*/public void batchSendEmail(String recipientList, String aliasName, String subject, String content,InputStream is) {if (!StringUtils.isEmpty(recipientList)) {String[] arrs = recipientList.split(",");for (String arr : arrs) {send(new MailContent(aliasName, arr, subject, content),is);}} else {log.error("收件人为空,发送失败。");}}/*** 发送邮件** @param content*/private void send(MailContent content) {// 设置邮件属性Properties prop = new Properties();prop.setProperty("mail.transport.protocol", "smtp");prop.setProperty("mail.smtp.host", properties.getSmtpHost());prop.setProperty("mail.smtp.port", properties.getSmtpPort());prop.setProperty("mail.smtp.auth", properties.getSmtpAuth());prop.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");MailSSLSocketFactory sslSocketFactory = null;try {sslSocketFactory = new MailSSLSocketFactory();sslSocketFactory.setTrustAllHosts(true);} catch (GeneralSecurityException e1) {log.error("开启 MailSSLSocketFactory 失败", e1);}if (sslSocketFactory == null) {log.error("开启 MailSSLSocketFactory 失败");} else {prop.put("mail.smtp.ssl.enable", properties.getSmtpSslEnable());prop.put("mail.smtp.ssl.socketFactory", sslSocketFactory);// 创建邮件会话(注意,如果要在一个进程中切换多个邮箱账号发信,应该用 Session.getInstance)Session session = Session.getDefaultInstance(prop, new MyAuthenticator(properties.getAccount(), properties.getPassword()));try {MimeMessage mimeMessage = new MimeMessage(session);// 设置发件人别名(如果未设置别名就默认为发件人邮箱)if (content.getAliasName() != null && !content.getAliasName().trim().isEmpty()) {mimeMessage.setFrom(new InternetAddress(properties.getAccount(), content.getAliasName()));} else {mimeMessage.setFrom(new InternetAddress(properties.getAccount(), properties.getAccount()));}// 设置主题和收件人、发信时间等信息mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(content.getRecipients()));mimeMessage.setSubject(content.getSubject());mimeMessage.setSentDate(new Date());// 添加正文信息MimeMultipart multipart = new MimeMultipart();MimeBodyPart body = new MimeBodyPart();body.setContent(content.getContent(), "text/html; charset=UTF-8");multipart.addBodyPart(body);mimeMessage.setContent(multipart);// 开始发信mimeMessage.saveChanges();Transport.send(mimeMessage);} catch (Exception e) {log.error("发送邮件错误:", e);}}}/*** 发送邮件(带图片)** @param content 文本内容* @param inputStream 图片内容*/private void send(MailContent content, InputStream inputStream) {// 设置邮件属性Properties prop = new Properties();prop.setProperty("mail.transport.protocol", "smtp");prop.setProperty("mail.smtp.host", properties.getSmtpHost());prop.setProperty("mail.smtp.port", properties.getSmtpPort());prop.setProperty("mail.smtp.auth", properties.getSmtpAuth());prop.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");MailSSLSocketFactory sslSocketFactory = null;try {sslSocketFactory = new MailSSLSocketFactory();sslSocketFactory.setTrustAllHosts(true);} catch (GeneralSecurityException e1) {log.error("开启 MailSSLSocketFactory 失败", e1);}if (sslSocketFactory == null) {log.error("开启 MailSSLSocketFactory 失败");} else {prop.put("mail.smtp.ssl.enable", properties.getSmtpSslEnable());prop.put("mail.smtp.ssl.socketFactory", sslSocketFactory);// 创建邮件会话(注意,如果要在一个进程中切换多个邮箱账号发信,应该用 Session.getInstance)Session session = Session.getDefaultInstance(prop, new MyAuthenticator(properties.getAccount(), properties.getPassword()));try {MimeMessage mimeMessage = new MimeMessage(session);// 设置发件人别名(如果未设置别名就默认为发件人邮箱)if (content.getAliasName() != null && !content.getAliasName().trim().isEmpty()) {mimeMessage.setFrom(new InternetAddress(properties.getAccount(), content.getAliasName()));} else {mimeMessage.setFrom(new InternetAddress(properties.getAccount(), properties.getAccount()));}// 设置主题和收件人、发信时间等信息mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(content.getRecipients()));mimeMessage.setSubject(content.getSubject());mimeMessage.setSentDate(new Date());// 添加正文信息MimeMultipart multipart = new MimeMultipart();//邮件内容//准备图片数据MimeBodyPart image=new MimeBodyPart();File tmpFile =File.createTempFile("123",".jpg");Files.copy(inputStream,tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);DataHandler dh=new DataHandler(new FileDataSource(tmpFile));image.setDataHandler(dh);//id自己设置image.setContentID("123");//image.setFileName("999.png");//正文MimeBodyPart text=new MimeBodyPart();text.setContent(content.getContent()+"<br/><a><img src='cid:123'></a>","text/html;charset=UTF-8");// text.setContent("<h1 style='color:red'>带图片的邮件<img src='cid:bz.jpg'></h1>","text/html;charset=UTF-8");MimeMultipart mmTextImage = new MimeMultipart();mmTextImage.addBodyPart(text);mmTextImage.addBodyPart(image);// 关联关系mmTextImage.setSubType("related");MimeBodyPart textImage = new MimeBodyPart();textImage.setContent(mmTextImage);multipart.addBodyPart(textImage);multipart.setSubType("mixed");mimeMessage.setContent(multipart);// 开始发信mimeMessage.saveChanges();Transport.send(mimeMessage);tmpFile.deleteOnExit();} catch (Exception e) {log.error("发送邮件错误:", e);}}}/*** 认证信息*/static class MyAuthenticator extends Authenticator {/*** 用户名*/String username = null;/*** 密码*/String password = null;/*** 构造器** @param username 用户名* @param password 密码*/public MyAuthenticator(String username, String password) {this.username = username;this.password = password;}@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}}}
Controller
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/aicut")
@Slf4j
public class MailController {@Autowiredprivate MailUtils mailUtils;@PostMapping("/sendMail")public R sendMail() {String recipientList = "xxx@xx.com"; //收件人邮箱,以逗号分割,可同时发给多个人String aliasName = "测试邮件";String subject = "邮件主题";String content = "邮件内容";mailUtils.batchSendEmail(recipientList, aliasName, subject, content);return R.ok();}
}
测试结果