spring-boot 速成(10) -【个人邮箱/企业邮箱】发送邮件

时间:2022-04-22
本文章向大家介绍spring-boot 速成(10) -【个人邮箱/企业邮箱】发送邮件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

发邮件是一个很常见的功能,代码本身并不复杂,有坑的地方主要在于各家邮件厂家的设置,下面以qq个人邮箱以及腾讯企业邮箱为例,讲解如何用spring-boot发送邮件:

一、添加依赖项

compile 'org.springframework.boot:spring-boot-starter-mail'

二、application.yml配置

2.1 QQ个人邮箱

spring:
  application:
    name: mail-demo
  mail:
    host: smtp.qq.com
    username: xxxx@qq.com # 这里填写个人的qq邮箱
    password: ***** # 注:这里不是qq邮箱的密码,而是授权码
    properties:
      mail.smtp.auth: true
      mail.smtp.starttls.enable: true
      mail.smtp.starttls.required: true

生成授权码的方法参考下图:

2.3 QQ企业邮箱

spring:
  application:
    name: mail-demo
  mail:
    host: smtp.exmail.qq.com
    username: xxxx@puscene.com # 这里填写企业邮箱
    password: **************** # 这里填写企业邮箱登录密码
    properties:
      mail.smtp.auth: true
      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      mail.smtp.socketFactory.fallback: false
      mail.smtp.socketFactory.port: 465  

 企业邮箱如果未开启安全登录,就不需要授权码了,直接填写登录密码即可。如果开启了安全登录,参考下图:

则password这里,需要填写客户端专用密码

三、 发送代码示例

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

/**
 * Created by 菩提树下的杨过 on 12/08/2017.
 */
@SpringBootApplication
public class MailDemo {

    public static void main(String[] args) {
        
        ConfigurableApplicationContext context = SpringApplication.run(MailDemo.class, args);
        JavaMailSender mailSender = context.getBean(JavaMailSender.class);

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("菩提树下的杨过<xxxxxxxx@xxx.com>"); //注意这里的发送人邮箱,要与yml配置中的username相同,否则验证不通过

        message.setTo("xxx@126.com");
        String[] ccList = new String[]{"xxxx@126.com", "yang.junming@xxxx.com"};//这里添加抄送人名称列表
        message.setCc(ccList);
        String[] bccList = new String[]{"yyyy@126.com", "yjmyzz@xxxx.com"};//这里添加密送人名称列表
        message.setBcc(bccList);
        message.setSubject("主题:简单邮件(QQ个人邮件)-抄送,密送测试");
        message.setText("测试邮件内容");
        mailSender.send(message);
        System.out.println("发送成功!");
    }
}