SpringBoot之JavaMailSender大批量定时发送html内容邮件

tech2023-10-04  93

1、maven依赖

<!-- 发送邮件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>

2、邮件服务与实现

/** * 邮件service */ public interface MailService { /** * 发送文本邮件 * @param to 收件邮箱 * @param subject 邮件主题 * @param html 邮件内容(分为普通内容与html) */ void sendMail(String to, String subject, String html); } /** * 邮件ServiceImpl */ @Service public class MailServiceImpl implements MailService { private static final Logger log = LoggerFactory.getLogger(MailServiceImpl.class); @Autowired private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String from; // 发送者 @Override public void sendMail(String to, String subject, String html) { try { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); //防止成为垃圾邮件,披上outlook的马甲 message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869"); helper.setSentDate(new Date()); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); //注意此处,sendText是个重载函数,也可以不带后面这个参数,为true时表示发送html格式的邮 件,为false是为文本模式的邮件,默认为false,也就是文本模式的邮件,最开始就是没注意这一点儿导致发送出去的html格式的邮件全都显示不出来 helper.setText(html,true); javaMailSender.send(message); log.info("success:" + to); } catch (Exception e) { log.error("fail:" + to + "failed\r\n", e); } } }

3、配置文件

# 发送邮件配置 spring.mail.host=smtp.exmail.qq.com spring.mail.port=465 spring.mail.protocol=smtp spring.mail.username=*** spring.mail.password=*** spring.mail.default-encoding=utf-8 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.ssl.enable=true spring.mail.properties.mail.debug=false spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true

4、测试 

try { for(EMailbox eMailbox : eMailboxes){ mailService.sendMail(eMailbox.getMailbox(),subject,html); Thread.sleep(4000); } }catch (Exception e){ e.printStackTrace(); }

 

最新回复(0)