springboot 集成邮箱 gmail

1,824 阅读1分钟

gmail可以免费发送 500 封邮件,是免费邮件中最多的。

1. gmail配置

登录gmail 开启 POP/IMAP

image.png

开启2步验证

绑定手机号

myaccount.google.com/u/1/securit…

image.png

配置密码

myaccount.google.com/u/1/securit…

image.png

image.png

2. springboot 配置

pom.xml

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

EmailConfig

@Data
public class EmailConfig implements Serializable {

  /** 邮箱名称 */
  private String name;

  /** SMTP服务 */
  private String host;

  /** 端口 */
  private Integer port;

  /** 账号 */
  private String username;

  /** 密码 */
  private String password;

  /** 是否开启debug) */
  private Boolean debug;

  /** 启用SSL */
  private Boolean enableSsl;
}

邮箱工具类 EmailUtils,

@Slf4j
public class EmailUtils {

  private final EmailConfig config;

  public EmailUtils(EmailConfig config) {
    this.config = config;
  }

  public static EmailUtils build(EmailConfig config) {
    return new EmailUtils(config);
  }

  /**
   * 发送文本邮件
   *
   * @param subject 邮件标题
   * @param text 内容
   * @param to 接收人
   */
  public void send(String subject, String text, String... to) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(config.getUsername());
    message.setText(text);
    message.setSubject(subject);
    message.setTo(to);
    this.buildMailSender(config).send(message);
  }

  private JavaMailSender buildMailSender(EmailConfig config) {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setHost(config.getHost());
    javaMailSender.setUsername(config.getUsername());
    javaMailSender.setPassword(config.getPassword());

    javaMailSender.setDefaultEncoding(StandardCharsets.UTF_8.name());
    if (null != config.getPort()) {
      javaMailSender.setPort(config.getPort());
    }

    Properties properties = new Properties();
    properties.put("mail.debug", Boolean.TRUE.equals(config.getDebug()));
    properties.put("mail.smtp.auth", true);
    properties.put("mail.smtp.connectiontimeout", 5000);
    properties.put("mail.smtp.writetimeout", 5000);
    properties.put("mail.smtp.starttls.enable", true);

    if (Boolean.TRUE.equals(config.getEnableSsl())) {
      properties.put("mail.smtp.ssl.enable", true);
      properties.put("mail.smtp.ssl.trust", config.getHost());
    }

    javaMailSender.setJavaMailProperties(properties);
    return javaMailSender;
  }
}

配置是放数据库数据字典的

{
	"debug": true,
	"enableSsl": true,
	"host": "smtp.gmail.com",
	"name": "gmail",
	"password": "gdfbppxavpzlhspy",
	"port": 465,
	"username": "xxx@gmail.com"
}

测试

@PostMapping("/sendMail")
@ApiOperation(value = "发送邮箱")
public void sendMail() {
  //上面的json字符串
  String emailStr = "";
  EmailConfig config = JSON.toJavaObject(emailStr,EmailConfig.class);
  EmailUtils.build(config).send("验证码", "验证码", "xxx@gmail.com");
}