SpringBoot实现发送邮件功能

1.添加依赖

Maven引入

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Gradle引入

implementation 'org.springframework.boot:spring-boot-starter-mail:2.4.3'

2.添加配置

以qq邮箱为例

spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxx@qq.com
#这个是SMTP,而不是QQ密码
spring.mail.password=xxoo
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true

3.编码实现

@Component
@Data
public class MailClient {

    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

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

    public void sendMail(String to, String subject, String content) {

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败:" + e.getMessage());
        }

    }

}

4.测试

@Test
public void testTextMail() {
   mailClient.sendMail("xxx@qq.com", "您好", "您好");
}

注:恶意发送邮件会被屏蔽且被服务器拉黑。

Q.E.D.


这个人很懒,什么都没有写