springboot 邮箱邮件激活验证

1.添加依赖

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

2.配置文件application.properties

#邮件配置
spring.mail.host=smtp.qq.com
#默认编码格式,默认utf-8
spring.mail.default-encoding=utf-8
#发件邮箱
spring.mail.username=2572037297@qq.com
#邮箱授权码
spring.mail.password=ssflpcyntcmxdibc

3.发送简单邮件

    @Autowired
    JavaMailSender mailSender;
    //读取配置文件的发件人
    @Value("${spring.mail.username}")
    private String from ;
    @Test
    public void sendEmail(){
    	//自动装配就不用new了
        //MailSender mailSender = new JavaMailSenderImpl();
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //发件人
        simpleMailMessage.setFrom(from);
        //发件内容
        simpleMailMessage.setText("祝你幸福");
        //发送给谁
        simpleMailMessage.setTo("whh1874@163.com");
        //邮件主题
        simpleMailMessage.setSubject("测试");
        mailSender.send(simpleMailMessage);
    }

4.发送html格式的邮件

    @Autowired
    JavaMailSender mailSender;
    //读取配置文件的发件人
    @Value("${spring.mail.username}")
    private String from ;
    @Test
    public void sendHTMLEmail() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //此处multipart必须设置为true
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
        mimeMessageHelper.setFrom(from);
        //此处true为解析html标签,设置为false不生效
        mimeMessageHelper.setText("<h1>这是一封html格式的邮件</h1>",true);
        mimeMessageHelper.setTo("whh1874@163.com");
        mimeMessageHelper.setSubject("测试html格式邮件");
        mailSender.send(mimeMessage);
    }

5.发送邮件带附件

    @Autowired
    JavaMailSender mailSender;
    //读取配置文件的发件人
    @Value("${spring.mail.username}")
    private String from ;
    @Test
    public void testSendFileEmail() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setTo("whh1874@163.com");
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setText("一封自拍");
        FileSystemResource fileSystemResource = new FileSystemResource(new File("文件路径"));
        mimeMessageHelper.addAttachment("mhb.jpg",fileSystemResource);
        mimeMessageHelper.setSubject("这是HTML邮件");
        mailSender.send(mimeMessage);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值