springboot任务之邮件任务

1-邮件发送需要引入spring-boot-starter-mail

pm.xml中添加

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

2-springboot自动配置MailSenderAutoConfiguration

3-定义MailProperties内容,配置在application.properties中

spring.mail.username=xxx@aliyun.com
  #给谁发邮件
spring.mail.password=xxxxx
  #阿里云的smtp授权码就是密码
spring.mail.host=smtp.aliyun.com
  #阿里云邮箱smtp服务器地址

生成授权码

开启服务

 

 

 

4-自动装配JavaMailSender

测试类中写入

package com.example.springboottask;

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;

@SpringBootTest
class SpringbootTaskApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();

        //邮件设置
        message.setSubject("通知-今晚开会");
        message.setText("今晚7:30开会");

        message.setTo("xxx@qq.com");  //可以设置多个,给哪个邮箱发
        message.setFrom("xxx@aliyun.com");     //用这个邮箱发送邮件

        mailSender.send(message);
    }

}

5-测试邮件发送

可能需要开启ssl

6-发送复杂的消息邮件

测试类中添加方法

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

        //邮件设置
        helper.setSubject("通知-今晚开车");
        helper.setText("<b style='color:red'>今晚8:30开会</b>",true);

        helper.setTo("986588471@qq.com");  //可以设置多个
        helper.setFrom("prettypretty@aliyun.com");

        //上传文件
        helper.addAttachment("1.jpg",new File("C:\\Users\\Administrator\\Downloads\\b216b5dbb62f9ea5920f32836fbfc46c.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\Administrator\\Downloads\\b216b5dbb62f9ea5920f32836fbfc46c.jpg"));

        mailSender.send(mimeMessage);
    }

运行测试方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值