163邮箱为例
1、添加依赖
<!-- mail-starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
2、编写配置,smtp默认端口25,smtps端口465 或587
登录邮箱,找到设置,开通邮箱 IMAP/SMTP等服务,复制授权码!!!
mail:host: smtp.163.comusername: c2134a@163.compassword: 123345 #授权码,不是密码properties:mail:smtp:auth: truestarttls:enable: truerequired: true
3、发送邮件工具类,可直接用
package org.jeecg.modules.ycgl.util;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;/*** 邮箱工具*/
@Slf4j
@Component
public class MailUtils {@Autowiredprivate JavaMailSender mailSender;/*** 配置文件中我的qq邮箱*/@Value("${spring.mail.username}")private String username;/*** 发送邮件-不包含附件** @param fromAliasName 别名* @param toMail 发送目标邮箱* @param subject 主题* @param content 内容*/public void sendMail(String fromAliasName, String toMail, String subject, String content) {sendMailOssFile(fromAliasName, toMail, subject, content, null);}/*** 发送邮件工具-OSS在线文件** @param fromAliasName 别名* @param toMail 发送目标邮箱* @param subject 主题* @param content 内容* @param fileList 附件OSS地址*/public void sendMailOssFile(String fromAliasName, String toMail, String subject, String content, List<String> fileList) {try {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);// 设置发件人别名(如果未设置别名就默认为发件人邮箱)if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {helper.setFrom(new InternetAddress(username, fromAliasName));} else {helper.setFrom(username);}helper.setTo(toMail);helper.setSubject(subject);helper.setText(content, true);if (fileList != null && !fileList.isEmpty()) {for (String filePath : fileList) {String[] split = filePath.split("/");// 将输入流转换为ResourceURL url = new URL(filePath);DataSource dataSource = new URLDataSource(url);helper.addAttachment(split[split.length - 1], dataSource);}}//发送邮件mailSender.send(message);log.info("邮件已经发送。");} catch (MalformedURLException e) {log.error("URL 格式错误: {}", e.getMessage(), e);} catch (MessagingException | UnsupportedEncodingException e) {log.error("发送邮件时发生异常: {}", e.getMessage(), e);}}/*** 发送邮件工具-普通文件** @param fromAliasName 别名* @param toMail 发送目标邮箱* @param subject 主题* @param content 内容* @param fileList 附件*/public void sendMailFile(String fromAliasName, String toMail, String subject, String content, List<File> fileList) {try {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);// 设置发件人别名(如果未设置别名就默认为发件人邮箱)if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {helper.setFrom(new InternetAddress(username, fromAliasName));} else {helper.setFrom(username);}helper.setTo(toMail);helper.setSubject(subject);helper.setText(content, true);if (fileList != null && !fileList.isEmpty()) {for (File file : fileList) {helper.addAttachment(file.getName(), new FileSystemResource(file));}}//发送邮件mailSender.send(message);log.info("邮件已经发送。");} catch (MessagingException | UnsupportedEncodingException e) {log.error("发送邮件时发生异常!", e);}}}
4、调用工具栏,定时任务使用quarz,实现Job
@Slf4j
public class ChzyExcelJob implements Job {@Autowiredprivate IMailUserService mailUserService;@Autowiredprivate IBaseApi posApi;@Autowiredprivate IChzyExcelService chzyExcelService;@Value(value = "${jeecg.path.upload}")private String uploadpath;@Autowiredprivate MailUtils mailUtils;@Overridepublic void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {log.info("【定时任务】-【生成excel定时任务】-【开始】!");JSONObject jsonObject = new JSONObject();//jsonObject.put("deTye", "11");//jsonObject.put("sipBssTpe", "1");//jsonObject.put("shiMaial", "1");//jsonObject.put("spTye", "xx");HashMap<Object, Object> listMap = posApi.shpcreenWkSpaceExcelByTasks(jsonObject);if (StaticMethod.isNotEmpty(listMap)) {ChzyExcel excel = new ChzyExcel();excel.setFileName((String) listMap.get("fileName"));excel.setFilePath((String) listMap.get("path"));excel.setRq(new Date());chzyExcelService.save(excel);List<MailUser> users = mailUserService.list();List<File> list = new ArrayList<>();File file = new File(uploadpath + listMap.get("path"));list.add(file);LocalDate currentDate = LocalDate.now();DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String data = currentDate.format(formatter);for (MailUser user : users) {mailUtils.sendMailFile("", user.getUserMail(), data + "数据统计", data + "船数据统计,详情请见附件!", list);}}log.info("【定时任务】-【生成excel定时任务】-【结束】!");}