springboot实现邮件任务

8次阅读

共计 1190 个字符,预计需要花费 3 分钟才能阅读完成。

导入关键 jar 包:

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

在 application.properties 中添加邮件配置:

# 发送者的邮箱
spring.mail.username=27553140@qq.com
#邮箱秘钥
spring.mail.password=nxnoashhoanvdfaf
#邮箱主机
spring.mail.host=smtp.qq.com
#开启 qq 邮箱的安全认证
spring.mail.properties.mail.smtp.ssl.enable=true

在测试类中测试简单邮件任务

@SpringBootTest
class SpringbootShrioApplicationTests {
   
    // 引入邮件实现类
    @Autowired
    JavaMailSenderImpl mailSender;
    @Test
    void contextLoads() {SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("第一个邮件 test");
        mailMessage.setText("你好");
        mailMessage.setTo("27553140@qq.com");
        mailMessage.setFrom("27553140@qq.com");

        mailSender.send(mailMessage);

    }

会在 QQ 邮箱中收到相应的信息

在测试类中测试复杂邮件任务,比如可以支持附件的传输

@Test
    void contextLoads2() throws MessagingException {MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("复杂邮件");
        helper.setText("<p style='color:red'> 复杂邮件测试内容 </p>",true);
        helper.addAttachment("奥特.png",new File("E:\\ 桌面 \\ 奥特.png"));
        helper.setTo("151442642@163.com");
        helper.setFrom("27553140@qq.com");


        mailSender.send(mimeMessage);

    }

至此,springboot 就简单的使用的邮件功能

正文完
 0