SpringBoot邮件发送

Scroll Down

1、下面是使用QQ发送邮件,首先去qq邮箱中的设置->账号中开启以下服务,然后生成授权码

2、接着在Springboot中导入jar包

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

3、在配置文件中进行配置

spring:
  mail:
    username: 账号
    password: 授权码
    host: smtp.qq.com
    properties: mail.smtp.ssl.enable=true

4、编写发送代码

public class SpringbootModelApplicationTests {
    @Autowired
    JavaMailSenderImpl mailSender;

     //简单邮件发送
    @Test
    public void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件设置
        message.setSubject(“通知-今晚开会”);//标题
        message.setText(“今晚7:30开会”);//内容
        message.setTo(“xxx”);//发给谁
        message.setFrom(“xxx”);//来自谁
        mailSender.send(message);
    }

    @Test
    public void test02() throws MessagingException {
        //1、创建一个复杂的消息邮件
        MimeMessage mimeMessage=mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        //邮件设置
        helper.setSubject(“通知-今晚开会”);//标题
        helper.setText(“<b style=’color:red’>今晚7:30开会</b>”,true);//内容 true 设置内容为html
        helper.setTo(“xxx”);//发给谁
        helper.setFrom(“xxx”);//来自谁
        //发送文件
        helper.addAttachment(“附件1.png”,new File(“G:\1.png”));
        helper.addAttachment(“附件2.jpg”,new File(“G:\2.jpg”));
        mailSender.send(mimeMessage);
    }
}

5、查看结果