springboot邮件任务

1application.properties配置
spring.mail.host=smtp.qq.com
spring.mail.username=你的QQ号码
spring.mail.password=此处填写你的SMTP服务密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

2在Test类下测试
package com.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private JavaMailSender mailSender;

    @Test
    public void contextLoads() {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo("[email protected]");
        message.setSubject("主题:简单邮件");
        message.setText("哈哈哈哈哈哈哈哈啊哈哈");

        mailSender.send(message);
    }

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


                helper.setSubject("通知今晚开会");
                helper.setText("hello world!",true);

                helper.setFrom("[email protected]");
                helper.setTo("[email protected]");

                helper.addAttachment("新福音战士",new File("C:\\Users\\polo\\Desktop\\新福音战士 (1).png"));

                mailSender.send(mimeMessage);
            }
}

springboot邮件任务_第1张图片
图片.png

码云仓库地址:https://gitee.com/zdwbmw/springboot_Task

你可能感兴趣的:(springboot邮件任务)