码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot 发送邮件

时间:2021-06-11 18:37:22      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:模板   cto   ext   frame   mail   cat   catch   ESS   use   

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;
        }
    }
}

 

SpringBoot 发送邮件

标签:模板   cto   ext   frame   mail   cat   catch   ESS   use   

原文地址:https://www.cnblogs.com/easyidea/p/14874008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!