4.邮件任务

邮件发送在我们的日常开发中也非常的多,Springboot帮我们做了支持

我们去找一下关于Mail的自动配置类,发现有一个MailSenderAutoConfiguration,点进去

@EnableConfigurationProperties({MailProperties.class})

有关Mail的配置属性都在MailProperties.class中定义好了

@ConfigurationProperties(
    prefix = "spring.mail"
)
public class MailProperties {
    private static final Charset DEFAULT_CHARSET;
    private String host;
    private Integer port;
    private String username;
    private String password;
    private String protocol = "smtp";
    private Charset defaultEncoding;
    private Map<String, String> properties;
    private String jndiName;
    ......
}

那么这些配置属性又是被哪些Bean获取的呢

回到MailSenderAutoConfiguration这个类,发现它并没有注册Bean

@Import({MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class})

点进导入的这两个类,发现MailSenderPropertiesConfiguration中注册了一个Bean,JavaMailSenderImpl

	@Bean
    @ConditionalOnMissingBean({JavaMailSender.class})
    JavaMailSenderImpl mailSender(MailProperties properties) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        this.applyProperties(properties, sender);
        return sender;
    }

引入pom依赖

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

开启邮箱的POP3/SMTP服务

配置相关属性

spring.mail.username=你的邮箱地址
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true

单元测试

@SpringBootTest
class Springboot05ApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    public void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("通知");
        message.setText("今晚20:30开会");

        message.setTo("邮箱地址");
        message.setFrom("邮箱地址");
        mailSender.send(message);
    }

    @Test
    public void contextLoads2() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject("你有新消息了");
        helper.setText("<b style='color:red'>今天 17:30来开会</b>",true);
        helper.addAttachment("1.jpg",new File("E:\\1.jpg"));
        helper.setTo("邮箱地址");
        helper.setFrom("邮箱地址");

        mailSender.send(mimeMessage);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值