Java SpringBoot项目邮件发送功能添加

一. pom.xml 文件导入依赖

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

<!--模板引擎beetl,发送html模板邮件时用到-->
<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.0.16.RELEASE</version>
</dependency>

二. application.yml 配置文件中配置相应邮箱信息

# 邮件服务器配置(方式1)
  mail:
    # 邮件服务地址
    host: smtp.qq.com
    # 用户名
    username: xxxxxx@xxx.com
    # 密码
    password: xxxxxxxx
    # 发件昵称
    nickname: MyAuth授权中心
    # 编码格式
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
            # 端口
            port: 465

  # 邮件服务器配置(方式2)
#  mail:
#    # 邮件服务地址
#    host: smtp.qq.com
#    # 用户名
#    username: xxxxxx@xxx.com
#    # 密码
#    password: xxxxxxxx
#    # 发件昵称
#    nickname: MyAuth授权中心
#    # 端口
#    port: 25
#    # 编码格式
#    default-encoding: UTF-8
#    properties:
#      mail:
#        smtp:
#          auth: true
#          starttls:
#            enable: true
#            required: true

三. 创建接口文件定义邮件发送功能接口(IEmailService.java)

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 邮件发送
 */
public interface IEmailService {
    /**
     * 发送普通邮件
     *
     * @param title    标题
     * @param content  内容
     * @param toEmails 收件人
     */
    void sendTextEmail(String title, String content, String[] toEmails) throws UnsupportedEncodingException, AddressException;

    /**
     * 发送富文本邮件
     *
     * @param title    标题
     * @param html     富文本
     * @param toEmails 收件人
     */
    void sendFullTextEmail(String title, String html, String[] toEmails) throws MessagingException, UnsupportedEncodingException;

    /**
     * 发送html模板邮件
     *
     * @param title    标题
     * @param htmlPath html路径
     * @param map      填充数据
     * @param toEmails 收件人
     * @throws MessagingException MessagingException
     * @throws IOException        IOException
     */
    void sendHtmlEmail(String title, String htmlPath, Map<String, Object> map, String[] toEmails) throws MessagingException, IOException;

}

四. 创建邮件发送接口的实现类(EmailServiceImpl.java)

import cn.daenx.myauth.main.service.IEmailService;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 发送邮件
 */
@Service
public class EmailServiceImpl implements IEmailService {
    @Value("${spring.mail.nickname}")
    private String nickname;
    @Value("${spring.mail.username}")
    private String formEmail;  // 发件人
    @Resource
    private JavaMailSender mailSender;

    @Override
    public void sendTextEmail(String title, String content, String[] toEmails) throws UnsupportedEncodingException, AddressException {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(new InternetAddress(MimeUtility.encodeText(nickname)+"<"+formEmail+">").toString());
        message.setTo(toEmails);
        message.setSubject(title);
        message.setText(content);
        mailSender.send(message);
    }

    @Override
    public void sendFullTextEmail(String title, String html, String[] toEmails) throws MessagingException, UnsupportedEncodingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(new InternetAddress(MimeUtility.encodeText(nickname)+"<"+formEmail+">").toString());
        helper.setTo(toEmails);
        helper.setSubject(title);
        // 发送邮件
        helper.setText(html, true);
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendHtmlEmail(String title, String htmlPath, Map<String, Object> map, String[] toEmails) throws MessagingException, IOException {
        ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("templates/");
        Configuration cfg = Configuration.defaultConfiguration();
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        Template t = gt.getTemplate(htmlPath);  // 加载html模板
        t.binding(map);  // 填充数据
        String html = t.render();  // 获得渲染后的html
        sendFullTextEmail(title, html, toEmails);  // 发送邮件
    }

}

Html文件模板例子(html模板存放在templates文件夹下)

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>

<body>
<div id="contentDiv" onmouseover="getTop().stopPropagation(event);"
     onclick="getTop().preSwapLink(event, 'html', 'ZC0006_aV_NqKSMOl8uiAEA8cu_Pc2');"
     style="position:relative;font-size:14px;height:auto;padding:15px 15px 10px 15px;z-index:1;zoom:1;line-height:1.7;"
     class="body">
    <div id="qm_con_body">
        <div id="mailContentContainer" class="qmbox qm_con_body_content qqmail_webmail_only"
             style="opacity: 1;">
            <div
                    style="width:100%;background:#49BDAD;color:#fff;border-radius:10px 10px 0 0;background-image:-moz-linear-gradient(0deg,#43c6b8,#ffd1f4);background-image:-webkit-linear-gradient(0deg,#43c6b8,#ffd1f4);height:66px">
                <p style="text-align:center;color:#231e1e;font-size:15px;word-break:break-all;padding:23px 32px;margin:0;background-color:hsla(0,0%,100%,.4);border-radius:10px 10px 0 0">
                    ${mailTitle!} <!--邮件标题-->
                </p>
            </div>
            <div style="margin:40px auto; width:90%">
                <p style="background:#fafafa repeating-linear-gradient(-45deg,#fff,#fff 1.125rem,transparent 1.125rem,transparent 2.25rem);box-shadow:0 2px 5px rgba(0,0,0,.15);margin:20px 0;padding:15px;border-radius:5px;font-size:14px;color:#555">
                    软件:${SoftName!} <!--软件名称-->
                    <br>
                    昵称:${name!} <!--用户昵称-->
                    <br>
                    用户:${username!} <!--用户-->
                    <br>
                    密码:${password!} <!--密码-->
                    <br>
                    使用卡密:${keyword!} <!--最后使用卡密-->
                    <br>
                    到期时间:${data!} <!--到期时间-->
                    <br>
                    剩余点数:${point!} <!--剩余点数-->
                    <br>
                    机器码:${DeviceCode!} <!--机器码-->
                    <br>
                    最后登录IP:${LastIp!} <!--最后登录IP-->
                    <br>
                    注册时间:${RegTime!} <!--注册时间-->
                    <br>
                    最后登录时间:${LastTime!} <!--最后登录时间-->
                    <br>
                    联系人QQ:${qq!} <!--QQ-->
                    <br><br>
                    温馨提示:该信息由MyAuth授权中心生成,请妥善保管。
                </p>
                <p style="text-align:center;font-size:13px;color:#666;line-height:20px;border-top:dashed 1px #666;border-bottom:dashed 1px #666;padding:20px 0">
                    ☉系统邮件由<a href="#" style="color:#12addb" rel="noopener" target="_blank">MyAuth授权中心</a>自动生成<br>☉如果内容不是您请求的,请及时删除此邮件!<br>
                </p>
            </div>
            <style type="text/css">
                .qmbox style,
                .qmbox script,
                .qmbox head,
                .qmbox link,
                .qmbox meta {
                    display: none !important;
                }
            </style>
        </div>
    </div>
    <style>
        #mailContentContainer .txt {
            height: auto;
        }
    </style>
</div>
</body>

</html>

模板邮件发送例子

try {
    Map<String, Object> map = new HashMap<>();  // 页面的动态数据
    map.put("mailTitle",MailTitle);
    map.put("name",user.getName());
    map.put("username", user.getUser());
    map.put("password", user.getPass());
    map.put("keyword", user.getCkey());
    map.put("DeviceCode",user.getDeviceCode());
    map.put("LastIp",user.getLastIp());
    map.put("RegTime",user.getRegTime());
    map.put("LastTime",user.getLastTime());
    map.put("SoftName",SoftName);
    map.put("data", user.getAuthTime());
    map.put("qq", user.getQq());
    map.put("point", user.getPoint());
    
    //模板邮件发送
    emailService.sendHtmlEmail(editInfoMailTheme , editInfoMailTemplates + ".html", map, new String[]{user.getQq()+"@qq.com"});

    } catch (Exception e) {
        e.printStackTrace();
        return Result.ok("邮箱提醒用户失败、请检查邮箱系统配置。");
    }

只有模板邮件发送需要修改一下html文件其余两种发送方式直接调用方法填写具体内容就行

最后附上模板图片

2

 

© 版权声明
THE END
喜欢就支持一下吧
点赞6赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容