SpringBoot--发邮件的方法(有示例)

原文网址:SpringBoot--发邮件的方法(有示例)_IT利刃出鞘的博客-CSDN博客

简介

本文介绍SpringBoot发邮件的方法(有示例)。

依赖

pom.xml

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

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

配置

163邮箱的配置

application.yml

spring:
  mail:
    default-encoding: UTF-8
    # 发送邮件服务器主机名,定值,来自QQ邮箱官网
    host: smtp.163.com
    # 163邮箱账号,你自己的奥
    username: [email protected]
    # 来自163邮箱官网的授权码,不是163邮箱密码奥
    password: yyyzzz
    # 端口号465或944,经过我的测试,发现两个都能用
    port: 465
    # 使用SSL方式
    properties:
      mail:
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory

163邮箱授权码的获取方式(对应上边的spring.mail.password)

开启IMAP/SMTP服务,可能需要使用手机发送验证码,按照要求发送就是了,如下:

QQ邮箱的配置

application.yml

spring:
  mail:
    default-encoding: UTF-8
    # 发送邮件服务器主机名,定值,来自QQ邮箱官网
    host: smtp.qq.com
    # 163邮箱账号,你自己的奥
    username: [email protected]
    # 来自QQ邮箱官网的授权码,不是QQ邮箱密码奥
    password: yyyzzz
    # 端口号465或587,但是经过我的测试,发现只有587能用
    port: 587
    # 使用SSL方式
    properties:
      mail:
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory

QQ邮箱授权码的获取方式(对应上边的spring.mail.password)

如果获取授权码过程中需要你进行手机认证或者QQ安全中心的手机令牌,去按照说明验证就是了,下面不在提醒。

在百度上搜索 “QQ邮箱” ,进入官网并登录,点击 设置 (也可以从QQ进入邮箱)

如下图:

点击账户,如下:

往下滑动页面,找到 “POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务” ,开启 “POP3/SMTP服务” 和 “IMAP/SMTP服务”,如下图:

点击生成授权码,并复制授权码,如下:

解释发送邮件服务器主机名

找到上面提到的开启服务的地方,点击链接如下图:

发送普通文本

代码

package com.example.knife.controller;

import com.example.knife.entity.User;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "发送邮件")
@RestController
@RequestMapping("mail")
public class MailController {
    @Autowired
    private JavaMailSender javaMailSender;

    // 发件人邮箱账号
    private String from = "[email protected]";

    // 收件人邮箱账号
    private String[] to = {"[email protected]"};

    // 抄送人邮箱账号
    private String[] cc = {"[email protected]"};

    // 隐秘抄送人邮箱账号
    private String[] bcc = {"[email protected]"};

    @ApiOperation("发送简单邮件")
    @PostMapping("sendSimpleMail")
    public String sendSimpleMail() {
        SimpleMailMessage message = new SimpleMailMessage();

        // 发件人,不能省略
        message.setFrom(from);
        // 收件人,可以是多个,不能省略
        message.setTo(to);
        // 邮件标题,可以省略,省略之后展示的是:<无标题>
        message.setSubject("简单邮件");
        // 邮件正文,一定不能少,不然会报错,不能省略
        message.setText("你好,您的验证码是:" + "123456");
        // 设置邮件抄送人,可以有多个,可以省略
        message.setCc(cc);
        // 设置隐秘抄送人,可以有多个,可以省略
        message.setBcc(bcc);
        // 发送时间,这样设置的目的:告诉你可以自由设置,可以省略

        try {
            message.setSentDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .parse("2028-06-06 00:00:00"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 发送
        javaMailSender.send(message);

        return "发送成功";
    }
}

测试

收到的邮件:

发送附件

代码

package com.example.knife.controller;

import com.example.knife.entity.User;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "发送邮件")
@RestController
@RequestMapping("mail")
public class MailController {
    @Autowired
    private JavaMailSender javaMailSender;

    // 发件人邮箱账号
    private String from = "[email protected]";

    // 收件人邮箱账号
    private String[] to = {"[email protected]"};

    // 抄送人邮箱账号
    private String[] cc = {"[email protected]"};

    // 隐秘抄送人邮箱账号
    private String[] bcc = {"[email protected]"};

    @ApiOperation("发送附件邮件")
    @PostMapping("sendAttachmentMail")
    public String sendAttachmentMail() {
        // 复杂邮件对象
        MimeMessage message = javaMailSender.createMimeMessage();

        try {
            // MimeMessageHelper对象,用来组装复杂邮件
            // 构建方法中第二个参数为true,代表支持替代文本、内联元素和附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 发件人,不能省略
            helper.setFrom(from);
            // 收件人,可以是多个,不能省略
            helper.setTo(to);
            // 邮件标题,可以省略,省略之后展示的是:<无标题>
            helper.setSubject("附件邮件");
            // 邮件正文,一定不能少,不然会报错,不能省略
            helper.setText("正文");
            // 添加附件,第一个参数是附件名称,第二个参数是附件对象
            helper.addAttachment("附件1.png", new File("E:\\tmp\\222.png"));
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        // 发送
        javaMailSender.send(message);

        return "发送成功";
    }
}

测试

收到的邮件:

HTML(FreeMarker模板)

代码

Controller

package com.example.knife.controller;

import com.example.knife.entity.User;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "发送邮件")
@RestController
@RequestMapping("mail")
public class MailController {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    // 发件人邮箱账号
    private String from = "[email protected]";

    // 收件人邮箱账号
    private String[] to = {"[email protected]"};

    // 抄送人邮箱账号
    private String[] cc = {"[email protected]"};

    // 隐秘抄送人邮箱账号
    private String[] bcc = {"[email protected]"};

    @ApiOperation("发送模板邮件")
    @PostMapping("sendTemplateMail")
    public String sendTemplateMail() {
        // 复杂邮件对象
        MimeMessage message = javaMailSender.createMimeMessage();

        try {
            // MimeMessageHelper对象,用来组装复杂邮件
            // 构建方法中第二个参数为true,代表支持替代文本、内联元素和附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 发件人,不能省略
            helper.setFrom(from);
            // 收件人,可以是多个,不能省略
            helper.setTo(to);
            // 邮件标题,可以省略,省略之后展示的是:<无标题>
            helper.setSubject("附件邮件");

            User user = new User();
            user.setName("托尼");
            user.setNickName("钢铁侠");
            user.setAge(30);

            Map<String, Object> model = new HashMap<>();
            model.put("user", user);

            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email.ftl");
            String emailHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

            // 邮件正文,一定不能少,不然会报错,不能省略。第二个参数表示是否是html
            helper.setText(emailHtml, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 发送
        javaMailSender.send(message);

        return "发送成功";
    }
}

模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title></title>
    <style>
        td {
            border: black 1px solid;
        }
    </style>
</head>
<body>
<h1>用户的信息</h1>
<table style="border: black 1px solid;width: 750px">
    <tr>
        <td>姓名</td>
        <td>昵称</td>
        <td>年龄</td>
    </tr>
    <tbody>
    <tr>
        <td>${user.name}</td>
        <td>${user.nickName}</td>
        <td>${user.age}</td>
    </tr>
    </tbody>
</table>
</body>
</html>

测试

收到的邮件:

 

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/128153621