先看怎么在spring boot发邮件,我们通过一个service来实现:
import lombok.extern.slf4j.Slf4j;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class MailService {
@Autowired
JavaMailSender javaMailSender;
@Value("${mail.from}")
private String mailFrom;
@Value("${mail.to}")
private String mailTo;
@Async
public void sendSimpleMail(String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(mailFrom);
message.setTo(mailTo);
message.setSubject(subject);
message.setText(content);
try {
javaMailSender.send(message);
log.info("邮件已经发送");
} catch (Exception e) {
log.error("发送邮件异常", e);
}
}
}
我们在application.properties文件中配置邮件参数,给mait.to配置多个邮箱,并用分号分隔
#邮件
spring.mail.host=smtp.163.com
spring.mail.username=tangseng2019@163.com
spring.mail.password=wlf123
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.starttls.required=true
spring.mail.properties.mail.starttls.enable=true
spring.mail.default-encoding=UTF-8
mail.from=${spring.mail.username}
mail.to=sunwukong2019@126.com;zhubajie2019@126.com
注意spring.mail.password不是邮箱密码,而是授权码,需要在邮箱的“设置”中启用授权码:

本文介绍了如何在Spring Boot应用中实现邮件群发功能。首先在`application.properties`配置邮件参数,使用授权码而非邮箱密码。通过邮件服务接口发送简单邮件,但在实际操作中遇到MimeMailMessage类的分隔符问题,导致群发失败。解决方案是将分号分隔的邮箱地址分别传入setTo方法。然而,邮件服务器可能会将此类批量邮件视为垃圾邮件,这可能导致`MailSendException`异常。
最低0.47元/天 解锁文章
5385

被折叠的 条评论
为什么被折叠?



