javamail - QQ邮箱 + 163邮箱

说明:该方法目前仅支持发送邮件,整体目录如下

1. 准备邮件html模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org:">
<head>
    <meta charset="UTF-8">
    <title>邮件</title>
</head>
<body>

<div>
    邮件激活
</div>
<span th:text="${username}"></span>
<a href="http://www.baidu.com">核对无误请点击本链接激活邮箱</a>
</body>
</html>

2. 添加邮件依赖:Maven

        <!-- 邮件服务 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.3.7.RELEASE</version>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <!--thymeleaf模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.4.4</version>
        </dependency>

3. 添加配置

spring.messages.basename=i18n/Messages,i18n/Pages


# QQ邮箱:password为邮箱内的单独秘钥,不会设置看最后
spring.mail.host=smtp.qq.com
spring.mail.username=1160247691@qq.com
spring.mail.password=qpgbrfniqcsyjcii
# 网易邮箱:password为邮箱内的单独秘钥,不会设置看最后
#spring.mail.host=smtp.163.com
#spring.mail.username=MojiWork@163.com
#spring.mail.password=XXPYLXMUDPNNOEAW

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

# liunx部署是配置 - 否则无法发送邮件
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.ssl.enable=true

4. 工具类

package com.example.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * @author :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in  19:29
 * @description : 邮件相关工具类
 */
@Component
@Slf4j
public class MailUtils {
    @Value("${spring.mail.username}")
    private String MAIL_SENDER; //邮件发送者

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 发送文本邮件
     * @param mailTo 收件人, subject 邮件主题, content 邮件正文
     * @return void
     */
    public  void sendSimpleMail(String mailTo,String subject,String content) throws Exception {
        if (StringUtils.isEmpty(mailTo) || StringUtils.isEmpty(subject) || StringUtils.isEmpty(content)){
            throw new Exception("邮件参数缺失,请检查请求参数!!!");
        }
        try {
            SimpleMailMessage mailMessage= new SimpleMailMessage();
            mailMessage.setFrom(MAIL_SENDER);
            mailMessage.setTo(mailTo);
            mailMessage.setSubject(subject);
            mailMessage.setText(content);
            javaMailSender.send(mailMessage);
        } catch (Exception e) {
            log.error("邮件发送失败", e.getMessage());
        }
    }


    /**
     * 发送带附件的文本邮件
     * @param mailTo 收件人, subject 主题, content 正文, file 附件
     * @return void
     */
    public void sendAttachFileMail(String mailTo, String subject, String content, File file) throws Exception {
        if (StringUtils.isEmpty(mailTo) || StringUtils.isEmpty(subject)
                || StringUtils.isEmpty(content) || file == null){
            throw new Exception("邮件参数缺失,请检查请求参数!!!");
        }

        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setTo(mailTo);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);
            mimeMessageHelper.addAttachment(file.getName(),file);
            javaMailSender.send(mimeMessage);
            deleteTempFile(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        log.debug("发送带附件的文本邮件 ---> 成功!");
    }

    /**
     * 带图片的邮件(只能用于QQ邮箱)
     * @param mailTo 收件人, subject 主题, content 正文, srePAth, resIds
     * @return void
     */
    public void sendMailWithImg(String mailTo,String subject,String content,String [] srePAth,String[]resIds){
        if (srePAth.length!=resIds.length){
            System.out.println("发送失败");
            return;
        }
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setTo(mailTo);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content,true);
            for (int i = 0; i < srePAth.length; i++) {
                FileSystemResource res = new FileSystemResource(new File(srePAth[i]));
                mimeMessageHelper.addInline(resIds[i],res);
            }
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用thymeleaf模板
     * @param mailTo 收件人, subject 主题, content 正文
     * @return void
     */
    public void sendHtmlMail(String mailTo ,String subject,String context){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setTo(mailTo);
            mimeMessageHelper.setText(context);
            mimeMessageHelper.setSubject(subject);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * MultipartFile 转 File
     * @param file
     * @return java.io.File
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     * 获取流文件
     * @param ins, file
     * @return void
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}

5. 测试类

package com.example.controller;

import com.example.utils.MailUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Date;

import static com.example.utils.MailUtils.multipartFileToFile;

/**
 * @author :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in  19:27
 * @description :邮件功能测试
 */
@RestController
public class EmailController {
    @Resource
    MailUtils mailUtil;
    @Resource
    TemplateEngine templateEngine;


    /**
     * 发送文本邮件
     */
    @RequestMapping("sendSimpleMail")
    public void sendSimpleMail() throws Exception {
        mailUtil.sendSimpleMail("1334390020@qq.com","Moji Work 注册认证","注册时间:" + new Date());
    }

    /**
     * 发送带附件的文本邮件
     */
    @RequestMapping("sendAttachFileMail")
    public void sendAttachFileMail(MultipartFile file) throws Exception {
        mailUtil.sendAttachFileMail("1334390020@qq.com","Moji Work 附件邮件","发送时间:" + new Date(), multipartFileToFile(file));
    }

    /**
     * 发送带图片的文本邮件
     */
    @RequestMapping("sendMailWithImg")
    public void sendMailWithImg(){
        mailUtil.sendMailWithImg("1334390020@qq.com","带图片的邮件","图片1:<div><img src='cid:p01'/></div>图片2:<div><img src='cid:p02'/></div>",new String[]{"D:\\file\\122.jpg","D:\\file\\123.jpg"},new String[]{"p01","p02"});
    }

    /**
     * 发送Thymeleaf模板邮件
     */
    @RequestMapping("sendHtmlMailThymeleaf")
    public void sendHtmlMailThymeleaf(){
        Context context = new Context();
        context.setVariable("username","cyc");
        String mail = templateEngine.process("mailtemplate.html",context);
        mailUtil.sendHtmlMail("1334390020@qq.com","sendHtmlMailThymeleaf",mail);
    }
}

番外:邮箱秘钥的设置和获取