SpringBoot发邮件

先来一个简单的邮件

1:首先我们需要在pom.xml中将mail的依赖导入:

<!--Java x.mail:配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2:在QQ邮箱中获取授权码

https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

3:在application.properties中进行配置

spring.mail.username=2840898428@qq.com  #用户名(发送的邮箱)
spring.mail.password=第二步获得的授权码
spring.mail.host=smtp.qq.com   #发送的服务器如果是163 就163开头 如果是新浪就是 sina
spring.mail.properties.mail.smtp.ssl.enable=true   #开启加密验证 

        或者在application.yml中配置

spring:
  mail:
    username: 2840898428@qq.com
    password: 第二步生成的授权码
    host: smtp.qq.com
    properties:
      mail:
        smtp:
          :ssl:
            :enable: true

4:测试

@SpringBootTest
class Springboot001ApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("你好!召唤师!!!");//发送主题
        mailMessage.setText("欢迎来到峡谷");//邮件内容
        mailMessage.setTo("377397360@qq.com");//发送给谁
        mailMessage.setFrom("2840898428@qq.com");//谁发送的
        mailSender.send(mailMessage);

    }

}

5:发送带有附件的邮件

@Test
    void contextLoads2() throws MessagingException {

        //创建一个mimeMessage
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装  是否支持多文本上传 true-->支持
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //设置主题
        helper.setSubject("你好!召唤师!!!");
        //是否可以解析html 还可以设置字体颜色等 类似于邮箱中富文本编辑
        helper.setText("欢迎来到峡谷~~", true);
        //附件
        helper.addAttachment("a.jpg", new File("D:\\img\\a.jpg"));
        helper.setTo("377397360@qq.com");//发送给谁
        helper.setFrom("2840898428@qq.com");//谁发送的
        mailSender.send(mimeMessage);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值