SpringBoot 发送邮件

1、引入依赖

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

 

2、配置地址

spring:
  mail:
    # 配置 SMTP 服务器地址
    host: mail.xxxx.com
    # 发送者邮箱
    username: xxx@xxx.com
    # 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
    password: xxxxxxx
    # 端口号465或587
    port: 25
    # 默认的邮件编码为UTF-8
    default-encoding: UTF-8
    # 配置SSL 加密工厂
    properties:
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
        #表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
        debug: true

 

3、编写邮件类

 

package com.hiscene.has.sys.mail.service.impl;

import com.hiscene.has.sys.mail.service.MailService;
import com.hiscene.util.ThreadPoolUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    ResourceLoader resourceLoader;
    @Value("${spring.mail.username}")
    private String sender;

    @SneakyThrows
    @Override
    public Boolean sendSimpleMail(String receiver, String subject, String username, String pwd) {
        try {
            //创建message
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //
            //发件人
            helper.setFrom(  "发邮件中文名称"+" <"+sender+">");
            //收件人
            helper.setTo(receiver);
            //标题
            helper.setSubject(subject);

            HashMap map = new HashMap();
            map.put("username", username);
            //解析模板并替换动态数据,最终username将替换模板文件中的${username}标签。
             String contents = "<html><body>"+username+"<br>"+ pwd + "</body></html>";
            helper.setText(contents, true);
            //发送邮件
             javaMailSender.send(message);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

 

posted @ 2021-06-11 10:10  一文搞懂  阅读(231)  评论(0编辑  收藏  举报