配置com.alibaba easyexcel2.2.11 org.springframework.boot spring-boot-starter-mailorg.projectlombok lomboktrue
此处的协议为 smtps,且配置了各种超时时间,若超时时间不起作用,请移步 springboot java mail 超时配置不生效。
spring: mail: protocol: smtps host: smtp.mxhichina.com port: 465 username: xxx@xxxt.com password: xxxxxx properties: mail.smtps.connectiontimeout: 150000 mail.smtps.timeout: 250000 mail.smtps.writetimeout: 5000 mail.smtp.auth: true mail.smtp.auth.starttls.required: true mail.smtp.auth.starttls.enable: true代码
package com.example.mailexcel; import com.alibaba.excel.EasyExcel; import lombok.SneakyThrows; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.core.io.ByteArrayResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.mail.internet.MimeMessage; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/mail") public class MailController { private final JavaMailSender javaMailSender; private final MailProperties mailProperties; public MailController(JavaMailSender javaMailSender, MailProperties mailProperties) { this.javaMailSender = javaMailSender; this.mailProperties = mailProperties; } @PostMapping("/send") public String send() { byte[] bytes = excelToByteArray(data()); email(bytes); return "OK"; } @SneakyThrows private void email(byte[] attachment) { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(mailProperties.getUsername()); helper.setTo("xxx@xxx.com"); helper.setText("内容:测试"); helper.setSubject("主题:测试"); // 附件 helper.addAttachment("测试.xlsx", new ByteArrayResource(attachment)); javaMailSender.send(message); } private byte[] excelToByteArray(Listlist) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); EasyExcel.write(outputStream, User.class).sheet("测试").doWrite(list); return outputStream.toByteArray(); } public static List data() { List list = new ArrayList<>(); list.add(new User(1, "小明", 18)); list.add(new User(2, "小红", 20)); list.add(new User(3, "小华", 25)); return list; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)