SpringBoot企业开发(夜的第十三章)-邮件发送

准备工作完成开始撸代码

1.引入依赖

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

配置文件

spring:
  thymeleaf:
    cache: true  #是否开启缓存,开发时可设置为false,默认为true
    check-template: true  #检查模板是否存在,默认为true
    check-template-location: true  #检查模板位置是否存在,默认为true
    encoding: UTF-8  #模板文件编码
    prefix: classpath:/templates/ #模板文件位置
    servlet:
      content-type: text/html  #content-type配置
    suffix: .html  #模板文件后缀
  mail:
    host: smtp.163.com
    port: 465
    username: pr@163.com
    password: 123
    default-encoding: UTF-8
    properties.mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
    properties.mail.debug: true

发送邮件

@Component
public class MailService {
    @Autowired
    JavaMailSender javaMailSender;

    public void sendSimpleMail(String from,String to,String cc,String subject,String content){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from); //发送人
        simpleMailMessage.setTo(to); //收件人
        simpleMailMessage.setCc(cc);  //抄送人
        simpleMailMessage.setSubject(subject); //邮件主题
        simpleMailMessage.setText(content); //邮件内容
        javaMailSender.send(simpleMailMessage);
    }
}
@RunWith(SpringRunner.class)
@SpringBootTest
class EmailApplicationTests {
    @Autowired
    MailService mailService;


    @Test
    void contextLoads() {
        mailService.sendSimpleMail("prettykangkang@163.com","prettykangkang@163.com","prettykangkang@163.com","测试邮件主题","测试内容");
    }
}

发送带附件的邮件

  /**
     * 添加附件
     * @param from 发送者
     * @param to   接受者
     * @param subject  主题
     * @param content  内容
     * @param file     附件
     */
    public void sendAttachFileMail(String from, String to, String subject, String content, File file){
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            //MimeMessageHelper简化了邮件的配置,他的构造方法的第二个参数true表示构造一个multipart message类型的邮件
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            //添加附件
            helper.addAttachment(file.getName(),file);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    @Test
    void sendAttachFileMail() {
        mailService.sendAttachFileMail("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题","测试内容",new File("C:\\Users\\user\\Desktop\\111111111111\\kemanman\\NC商户同步.wps"));
    }

发送带图片的邮件

    /**
     * 发送带图片的邮件
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param srcPath
     * @param resIds
     */
    public void sendMailWithImg(String from,String to,String subject,String content,String[] srcPath,String[] resIds){
        if(srcPath.length != resIds.length){
            System.out.println("发送失败");
            return;
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //第二个参数为true说明是HTML格式的
            helper.setText(content,true);
            for (int i = 0; i < srcPath.length; i++) {
                FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
                helper.addInline(resIds[i],res);
            }
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void sendMailWithImg(){
        mailService.sendMailWithImg("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题(图片)"," <div>\n" +
                "        <h1>hello,这是一封带图片的资源的邮件:</h1>\n" +
                "        这是图片1:<div><img src=\"cid:p01\"></div>\n" +
                "        这是图片2:<div><img src=\"cid:p02\"></div>\n" +
                "    </div>",new String[]{"C:\\Users\\user\\Desktop\\111111111111\\kemanman\\p1.png","C:\\Users\\user\\Desktop\\111111111111\\kemanman\\p2.png"},new String[]{"p01","p02"});
    }

 

使用FreeMarker编辑邮件模板

依赖

        <!--FreeMarker模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
/**
     * 使用FreeMarker模板
     * @param from
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String from,String to,String subject,String content){
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //第二个参数为true说明是HTML格式的
            helper.setText(content,true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            System.out.println("发送失败");
        }
    }

<div>邮箱激活</div>
<div>你的注册信息是:
    <table border="1">
        <#--行-->
        <tr>
            <#--列-->
            <td>用户名</td>
            <td>${username}</td>
        </tr>
        <tr>
            <td>用户性别</td>
            <td>${gender}</td>
        </tr>
    </table>
</div>
<div>
    <a href="www.baidu.com">核对无误请点击本连接激活邮箱</a>
</div>
package com.example.email.entity;

public class User {
    private String username;
    private String gender;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}
    /**
     * FreeMarker
     */
    @Test
    public void sendHtmlMail(){
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            ClassLoader loader = EmailApplication.class.getClassLoader();
            configuration.setClassLoaderForTemplateLoading(loader,"ftl");
            Template template = configuration.getTemplate("mailtemplate.ftl");
            StringWriter mail = new StringWriter();
            User user = new User();
            user.setGender("男");
            user.setUsername("他妈的");
            template.process(user,mail);
            mailService.sendHtmlMail("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题",mail.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

thymeleaf模板

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    /**
     * 使用FreeMarker模板
     * @param from
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String from,String to,String subject,String content){
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //第二个参数为true说明是HTML格式的
            helper.setText(content,true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            System.out.println("发送失败");
        }
    }

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件</title>
</head>
<body>
    <div>邮箱激活</div>
    <div>你的注册信息是:
        <table border="1">
            <#--行-->
            <tr>
                <#--列-->
                <td>用户名</td>
                <td th:text="${username}"></td>
            </tr>
            <tr>
                <td>用户性别</td>
                <td th:text="${gender}"></td>
            </tr>
        </table>
    </div>
    <div>
        <a href="www.baidu.com">核对无误请点击本连接激活邮箱</a>
    </div>
</body>
</html>
package com.example.email;

import com.example.email.entity.User;
import com.example.email.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

@SpringBootTest
class EmailApplicationTests {
    @Autowired
    MailService mailService;

    @Autowired
    TemplateEngine templateEngine;


    @Test
    void contextLoads() {
        mailService.sendSimpleMail("prettykangkang@163.com","prettykangkang@163.com","prettykangkang@163.com","测试邮件主题","测试内容");
    }

    @Test
    void sendAttachFileMail() {
        mailService.sendAttachFileMail("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题","测试内容",new File("C:\\Users\\user\\Desktop\\111111111111\\kemanman\\NC商户同步.wps"));
    }

    @Test
    public void sendMailWithImg(){
        mailService.sendMailWithImg("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题(图片)"," <div>\n" +
                "        <h1>hello,这是一封带图片的资源的邮件:</h1>\n" +
                "        这是图片1:<div><img src=\"cid:p01\"></div>\n" +
                "        这是图片2:<div><img src=\"cid:p02\"></div>\n" +
                "    </div>",new String[]{"C:\\Users\\user\\Desktop\\111111111111\\kemanman\\p1.png","C:\\Users\\user\\Desktop\\111111111111\\kemanman\\p2.png"},new String[]{"p01","p02"});
    }

    /**
     * FreeMarker
     */
    @Test
    public void sendHtmlMail(){
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            ClassLoader loader = EmailApplication.class.getClassLoader();
            configuration.setClassLoaderForTemplateLoading(loader,"ftl");
            Template template = configuration.getTemplate("mailtemplate.ftl");
            StringWriter mail = new StringWriter();
            User user = new User();
            user.setGender("男");
            user.setUsername("他妈的");
            template.process(user,mail);
            mailService.sendHtmlMail("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题",mail.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Thymeleaf
     */
    @Test
    public void sendHtmlMailThymeleaf(){
        Context ctx = new Context();
        ctx.setVariable("username","sang");
        ctx.setVariable("gender","男");
        String mail = templateEngine.process("mailtemplate.html",ctx);
        mailService.sendHtmlMail("prettykangkang@163.com","prettykangkang@163.com","测试邮件主题",mail);
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值