实现Spring Boot 定时发送带附件邮件功能

文章目录

  • 版本说明:
  • 1、pom依赖
  • 2、配置
  • 3、通过EasyExcel 将数据导出为Excel
  • 4、发送邮件
  • 5、定时功能
  • 6、常用邮箱的服务器(SMTP/POP3)地址和端口总结

版本说明:

spring-boot-starter-parent 2.6.1

jdk-8u202 (jdk8 最后一个版本)download

本文不是源码,需要理解查看,耐心按顺序读完代码和注释,会使用应该不是问题!

1、pom依赖

<dependencies>
     <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-webartifactId>
     dependency>
     <dependency>
         <groupId>org.mybatis.spring.bootgroupId>
         <artifactId>mybatis-spring-boot-starterartifactId>
         <version>2.1.1version>
     dependency>
     <dependency>
         <groupId>com.alibabagroupId>
         <artifactId>easyexcelartifactId>
         <version>3.0.1version>
     dependency>
     <dependency>
         <groupId>com.microsoft.sqlservergroupId>
         <artifactId>mssql-jdbcartifactId>
         <scope>runtimescope>
     dependency>
     
     <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-mailartifactId>
     dependency>
     <dependency>
         <groupId>org.projectlombokgroupId>
         <artifactId>lombokartifactId>
         <optional>trueoptional>
     dependency>
     <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-testartifactId>
         <scope>testscope>
     dependency>
 dependencies>

2、配置

server:
  port: 8081
spring:
  application:
    name: data-export
  datasource:
    driver-class-name: 
    username: 
    password: 
    url: 
  mail:
  	cron: 0 30 8 * * ?
    subject: 明细
    #收件人,配置多条逗号隔开,自行填写
    to: 
    #抄送人,配置多条逗号隔开,目前根据业务,代码有判空,自行填写
    cc: 
    username: mr*****@163.com
    #此处填写授权码非密码
    password: ESWPOWBA*****
    port: 25
    host: smtp.163.com
    properties:
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
        #表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
        debug: true
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.dataexport.dto
  configuration:
    cache-enabled: false

3、通过EasyExcel 将数据导出为Excel

细节实现本文不做赘述

首先定义实体类,有两个作用 1、数据返回 2、excel表头规范

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

/**
 * @author Song Jiangtao
 * @date 2021/12/6
 * @description: 数据接口和表头设置
 */
@Data
public class WorkDetails {
	/**
	* 过多字段不在展示
	* value:定义表头内容
	* index:表头顺序
	*/
    @ExcelProperty(value = "单号",index = 0)
    private String repairNo;

    @ExcelProperty(value = "类型",index = 1)
    private String serviceType;

    @ExcelProperty(value = "来源",index = 2)
    private String serviceWay;
}

其次实现excel生成

/**
 * 生成excel
 *
 * @param list,该list是需要的数据
 */
private void generateExcel(ByteArrayOutputStream out, List<WorkDetails> list) {
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    //字体大小
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short) 10);
    headWriteCellStyle.setWriteFont(headWriteFont);
    HorizontalCellStyleStrategy horizontalCellStyleStrategy =
            new HorizontalCellStyleStrategy(headWriteCellStyle, (WriteCellStyle) null);
            
    //生成本地文件,此处为项目根目录/write.xlsx
    EasyExcel.write("write.xlsx", WorkDetails.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("明细").doWrite(list);
    //生成流
    //EasyExcel.write(out, WorkDetails.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("明细").doWrite(list);

//同时easyexcel支持多种多样的excel生成,不在赘述
}

4、发送邮件

携带附件

@Autowired
JavaMailSender javaMailSender;

private void sendMimeMessageMail(final String yesterdayTime, final MimeMessageMail mail) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("邮件标题");
        helper.setFrom("谁发的邮件");
        helper.setTo("发给谁");
        //设置邮件抄送人,可以有多个抄送人
        helper.setCc("抄送给谁");
        helper.setSentDate(new Date());
        helper.setText("邮件正文");
        // 此处使用本地文件发送
        File file = new File("write.xlsx");
        //可自行查看addAttachment其他重载方法
        helper.addAttachment("明细-" + yesterdayTime + ".xlsx", file);
        javaMailSender.send(mimeMessage);
    }

其他邮件


//简单邮件

@Autowired
JavaMailSender javaMailSender;
@Test
public void sendSimpleMail() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setSubject("这是一封测试邮件");
    message.setFrom("[email protected]");
    message.setTo("[email protected]");
    message.setCc("[email protected]");
    message.setBcc("[email protected]");
    message.setSentDate(new Date());
    message.setText("这是测试邮件的正文");
    javaMailSender.send(message);
}

//携带图片
@Test
public void sendAttachFileMail() throws MessagingException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
    helper.setSubject("这是一封测试邮件");
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.setCc("[email protected]");
    helper.setBcc("[email protected]");
    helper.setSentDate(new Date());
    helper.setText("这是测试邮件的正文");
    helper.addAttachment("javaboy.jpg",new File("C:\\Users\\sang\\Downloads\\javaboy.png"));
    javaMailSender.send(mimeMessage);
}

5、定时功能

记得启动类加注解@EnableScheduling

//注入的值
@Value("${spring.mail.username}")
private String username;

@Value("${spring.mail.to}")
private String to;

@Value("${spring.mail.cc}")
private String cc;

@Value("${spring.mail.subject}")
private String subject;

@Scheduled(cron = "${spring.mail.cron}")
public void export() throws MessagingException {
    //1、获取昨天时间
    String yesterdayTime = getYesterdayTime();
    String startTime = yesterdayTime + " 00:00:00";
    String endTime = yesterdayTime + " 23:59:59";
    //2、查找数据
    List<WorkDetails> list = mapper.getWorkDetails(startTime, endTime);
    //3、生成excel
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    generateExcel(out, list);
    //4、发送邮件
    if (to == null || "".equals(to)) {
        throw new InvalidParameterException("收件人不能为空");
    }
    if (cc == null || "".equals(cc)) {
        throw new InvalidParameterException("抄送人不能为空");
    }
    //这个是我自己封装请求参数的类
    MimeMessageMail mail = new MimeMessageMail();
    //设置邮件标题
    mail.setSubject(subject);
    //设置发送人
    mail.setFrom(username);
    //设置收件人
    mail.setTo(to.split(","));
    //设置抄送人
    mail.setCc(cc.split(","));
    sendMimeMessageMail(yesterdayTime, mail);
}

6、常用邮箱的服务器(SMTP/POP3)地址和端口总结

  • 163.com:

    • POP3服务器地址:pop.163.com(端口:110)

    • SMTP服务器地址:smtp.163.com(端口:25)

  • 126邮箱:

    • POP3服务器地址:pop.126.com(端口:110)

    • SMTP服务器地址:smtp.126.com(端口:25)

  • 139邮箱:

    • POP3服务器地址:POP.139.com(端口:110)

    • SMTP服务器地址:SMTP.139.com(端口:25)

  • QQ邮箱:

    • POP3服务器地址:pop.qq.com(端口:110)

    • SMTP服务器地址:smtp.qq.com (端口:25)

  • QQ企业邮箱 :

    • POP3服务器地址:pop.exmail.qq.com (SSL启用 端口:995)

    • SMTP服务器地址:smtp.exmail.qq.com(SSL启用 端口:587/465)

  • gmail(google.com) :

    • POP3服务器地址:pop.gmail.com(SSL启用 端口:995)

    • SMTP服务器地址:smtp.gmail.com(SSL启用 端口:587)

  • Foxmail:

    • POP3服务器地址:POP.foxmail.com(端口:110)

    • SMTP服务器地址:SMTP.foxmail.com(端口:25)

  • sina.com:

    • POP3服务器地址:pop3.sina.com.cn(端口:110)

    • SMTP服务器地址:smtp.sina.com.cn(端口:25)

  • sinaVIP:

    • POP3服务器:pop3.vip.sina.com (端口:110)

    • SMTP服务器:smtp.vip.sina.com (端口:25)

  • sohu.com:

    • POP3服务器地址:pop3.sohu.com(端口:110)

    • SMTP服务器地址:smtp.sohu.com(端口:25)

  • yahoo.com:

    • POP3服务器地址:pop.mail.yahoo.com

    • SMTP服务器地址:smtp.mail.yahoo.com

  • yahoo.com.cn:

    • POP3服务器地址:pop.mail.yahoo.com.cn(端口:995)

    • SMTP服务器地址:smtp.mail.yahoo.com.cn(端口:587 )

  • HotMail :

    • POP3服务器地址:pop3.live.com (端口:995)

    • SMTP服务器地址:smtp.live.com (端口:587)

  • 263.net:

    • POP3服务器地址:pop3.263.net(端口:110)

    • SMTP服务器地址:smtp.263.net(端口:25)

  • 263.net.cn:

    • POP3服务器地址:pop.263.net.cn(端口:110)

    • SMTP服务器地址:smtp.263.net.cn(端口:25)

  • x263.net:

    • POP3服务器地址:pop.x263.net(端口:110)

    • SMTP服务器地址:smtp.x263.net(端口:25)

  • 21cn.com:

    • POP3服务器地址:pop.21cn.com(端口:110)

    • SMTP服务器地址:smtp.21cn.com(端口:25)

  • china.com:

    • POP3服务器地址:pop.china.com(端口:110)

    • SMTP服务器地址:smtp.china.com(端口:25)

  • tom.com:

    • POP3服务器地址:pop.tom.com(端口:110)

    • SMTP服务器地址:smtp.tom.com(端口:25)

  • etang.com:

    • POP3服务器地址:pop.etang.com

    • SMTP服务器地址:smtp.etang.com

你可能感兴趣的:(Spring,全家桶,spring,boot,java,spring)