SpringBoot2.x邮件发送
作者:互联网
1、pom引入依赖
<!--邮件发送--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!--邮件模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2、application.yml增加配置
#邮件配置 mail: host: mail.qq.com default-encoding: UTF-8 username: test@qq.com password: 123456 recipients: 23323@qq.com properties: mail: smtp: auth: true ssl: enable: false starttls: enable: false required: false
3、封装邮件发送工具类
import com.alibaba.fastjson.JSONObject;import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.util.Date; import java.util.List; /** * @Description: 邮件发送工具类 * @Author: bug毁灭者 * @Date: 2022/4/21 13:49 * @Version: 1.0 */ @Component @Slf4j public class EmailUtil { @Resource private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String fromUser; public String getFromUser() { return fromUser; } public void setFromUser(String fromUser) { this.fromUser = fromUser; } /** * 邮件发送开关 */ @Value("${mail.send.enable}") private boolean enable; /** * 邮件发送开关 */ @Value("${mail.send.test}") private String testEmail; @Resource
//定义你自己的邮件发送失败记录表 private SwFailEmailRecordMapper swFailEmailRecordMapper; @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @Resource
//定义你自己的邮件服务配置数据表 private EmailServerMapper EmailServerMapper; /** * Description: 是否需要真实发送邮件 * * @param: to * @Author: bug毁灭者 * @Date: 2021/12/22 18:26 * @Return: java.lang.String * @throws: */ private String emailAddr(String to) { if (enable) { return to; } else { return testEmail; } } /** * @param to 收件人 多个逗号隔开 abc@qq.com,ssd@163.com * @param subject 主题 * @param content 邮件内容 * @return void * @description: 简单邮件发送 * @author: bug毁灭者 * @date: 2021/12/21 13:50 */ public void sendSimpleMail(String to, String subject, String content) { // 构建一个邮件对象 try { SimpleMailMessage message = new SimpleMailMessage(); // 设置邮件主题 message.setSubject(subject); // 设置邮件发送者, message.setFrom(fromUser); // 设置邮件接收者,可以有多个接收者,中间用逗号隔开,以下类似 if (StringUtils.isNotBlank(to)) { message.setTo(emailAddr(to).split(",")); } // 设置邮件发送日期 message.setSentDate(new Date()); // 设置邮件的正文 message.setText(content); // 发送邮件 javaMailSender.send(message); log.info("邮件发送成功--"); } catch (Exception e) { addErrorLog(to, null, subject, content, 0, 0); log.error("邮件发送失败--" + e.getMessage()); log.error("邮件发送失败--参数" + to + "---" + subject + "---" + content); //e.printStackTrace(); } } /** * Description: 发送邮件 * * @param: to 发送,多人逗号(,)隔开 * @param: cc 抄送,多人逗号(,)隔开 * @param: subject * @param: content * @Author: bug毁灭者 * @Date: 2021/12/22 16:13 * @Return: void * @throws: */ public void sendHtmlMail(String to, String cc, String subject, String content) throws Exception { try { //注意这里使用的是MimeMessage MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(fromUser); if (StringUtils.isNotBlank(to)) { helper.setTo(emailAddr(to).split(",")); } if (StringUtils.isNotBlank(cc)) { helper.setCc(emailAddr(cc).split(",")); } helper.setSubject(subject); //第二个参数:格式是否为html helper.setText(content, true); javaMailSender.send(message); } catch (Exception e) { addErrorLog(to, cc, subject, content, 0, 1); log.error("发送邮件时发生异常!", e); } } /** * 发送模板邮件 * * @param to * @param subject * @param template */ public void sendTemplateMail(String to, String cc, String subject, String template, Object object) throws Exception { try { // 获得模板 log.info("邮件模板参数--"+ JSONObject.toJSONString(object)); Template temp = freeMarkerConfigurer.getConfiguration().getTemplate(template); // 传入数据模型到模板,替代模板中的占位符,并将模板转化为html字符串 String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(temp, object); // 该方法本质上还是发送html邮件,调用之前发送html邮件的方法 this.sendHtmlMail(to, cc, subject, templateHtml); log.info("邮件发送成功--"); } catch (TemplateException e) { log.error("发送邮件时发生异常!", e); } catch (IOException e) { log.error("发送邮件时发生异常!", e); } } /** * Description: 记录邮件发送错误日志 * * @param: to * @param: cc * @param: subject * @param: content * @param: attachmentName * @param: attchmentUrl * @param: send * @param: sendType * @Author: bug毁灭者 * @Date: 2021/12/22 17:05 * @Return: void * @throws: */ public void addErrorLog(String to, String cc, String subject, String content, String attachmentName, String attchmentUrl, int send, int sendType) { try {
//定义你自己的失败记录表模型 FailEmailRecord record = new FailEmailRecord(); record.setRecipients(to); record.setCcEmails(cc); record.setContent(content); record.setSubject(subject); record.setSendTime(new Date()); record.setAttachmentName(attachmentName); record.setAttchmentUrl(attchmentUrl); record.setIsSend(send); record.setSendType(sendType); FailEmailRecordMapper.insertSelective(record); } catch (Exception e) { log.error(String.format("记录邮件错误日志失败%s", e.toString())); } } /** * Description: 记录邮件发送错误日志 * * @param: to * @param: cc * @param: subject * @param: content * @param: send * @param: sendType * @Author: bug毁灭者 * @Date: 2021/12/22 17:10 * @Return: void * @throws: */ public void addErrorLog(String to, String cc, String subject, String content, int send, int sendType) { addErrorLog(to, cc, subject, content, null, null, send, sendType); } /** * Description: 发送邮件,失败不加入记录 * * @param: to 发送,多人逗号(,)隔开 * @param: cc 抄送,多人逗号(,)隔开 * @param: subject * @param: content * @Author: bug毁灭者 * @Date: 2021/12/22 16:13 * @Return: boolean * @throws: */ public boolean sendHtmlMail2(String to, String cc, String subject, String content) { try { //注意这里使用的是MimeMessage MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(fromUser); if (StringUtils.isNotBlank(to)) { helper.setTo(to.split(",")); } if (StringUtils.isNotBlank(cc)) { helper.setCc(cc.split(",")); } helper.setSubject(subject); //第二个参数:格式是否为html helper.setText(content, true); javaMailSender.send(message); return true; } catch (MessagingException e) { log.error("发送邮件时发生异常!", e); return false; } } /** * Description: 获取邮箱配置 * * @Author: bug毁灭者 * @Date: 2021/12/28 13:31 * @Return: org.springframework.mail.javamail.JavaMailSenderImpl * @throws: */ public JavaMailSenderImpl restMail() {
//从数据库里取最新的邮箱账号配置 EmailServer EmailServer = EmailServerMapper.selectEmailConfig(); List<JavaMailSenderImpl> mailSenders = SpringContextUtils.getBeanListOfType(JavaMailSenderImpl.class); JavaMailSenderImpl javaMailSender = mailSenders.get(0); if (!(javaMailSender.getUsername().equals(EmailServer.getEmailUser()) && javaMailSender.getPassword().equals(EmailServer.getEmailPwd()) && javaMailSender.getHost().equals(EmailServer.getEmailServer()))) { javaMailSender.setHost(EmailServer.getEmailServer()); javaMailSender.setDefaultEncoding(CharEncoding.UTF_8); javaMailSender.setUsername(EmailServer.getEmailUser()); javaMailSender.setPassword(EmailServer.getEmailPwd()); } return javaMailSender; } }
标签:content,String,param,发送,SpringBoot2,import,邮件,subject 来源: https://www.cnblogs.com/guliang/p/16282081.html