springboot发送邮件

springboot发送邮件

springboot发送邮件

导入依赖

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

application.properties配置

spring.mail.username=xxxxxxxxxxxxxx@qq.com
spring.mail.password=xxxxxxxxxxxxxxxxxxxx
spring.mail.host=smtp.qq.com
#QQ邮箱需要 开启qq加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

发送邮件

package com.kai;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    JavaMailSenderImpl javaMailSender;

    @Test
    void contextLoads() {
        //发送一个简单的邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        mailMessage.setSubject("通知");//设置邮件主题
        mailMessage.setText("谢谢你的爱");//设置邮件内容
        mailMessage.setTo("xxxxxxxxx@outlook.com");//发给谁
        mailMessage.setFrom("xxxxxxxxxxxx@qq.com");//谁发的

        javaMailSender.send(mailMessage);//执行发送
    }

    @Test
    void contextLoads2() throws MessagingException {
        //发送一个复杂的邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        helper.setSubject("通知");//设置邮件主题
        helper.setText("<p>谢谢你的爱<p/>",true);//设置邮件内容,设置为true开启HTML解析
        helper.addAttachment("1.png",new File("C:\\Users\\xxx\\Desktop\\1.png"));//添加附件
        helper.setTo("xxxxxxxxxx@outlook.com");//发给谁
        helper.setFrom("xxxxxxxxxxxxx@qq.com");//谁发的

        javaMailSender.send(mimeMessage);//执行发送
    }
}