SpringBoot发送邮件 普通邮件 Html邮件 附件邮件

首先是我们的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wuyou.email</groupId>
    <artifactId>email</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>email</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

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

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

        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

然后是我们的application.yml文件

发送邮件端口默认是25端口,因为政策,各大服务器运营商都关闭了这个端口,我们这里采用qq邮箱 qq邮箱支持465端口我们就采用465端口

spring:
  mail:
    host: smtp.qq.com #发送邮件服务器 
    port: 465
    username: higanbana.msg@foxmail.com #发送邮件的邮箱地址 
    password: aaaaaaaaaaaaaaaaaaa     #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
    default-encoding: UTF-8
    from: higanbana.msg@foxmail.com # 发送邮件的地址,和上面username一致
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enabled: true
          starttls:
            enabled: true
            required: true
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory
            fallback: false

有人看到上面的邮箱可能不是很理解,这里我解释说明一下,我这里在qq邮箱里申请开了Foxmail邮箱。
快看傻子

包的结构
快看傻子

定义一个业务层的接口 EmailService

package com.wuyou.email.service;

import java.io.File;

/**
 * @Package com.wuyou.email.service
 * @date: 2020/2/29 9:55
 */
public interface EmailService {

    /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 发送HTML邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendHtmlMail(String to, String subject, String content);



    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param file 附件
     */
    void sendAttachmentsMail(String to, String subject, String content, File file);
}

实现 EmailService

package com.wuyou.email.service.impl;

import com.wuyou.email.service.EmailService;
import lombok.extern.slf4j.Slf4j;
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.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Package com.wuyou.email.service.impl
 * @date: 2020/2/29 9:56
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.from}")
    private String from;
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        mailSender.send(message);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        log.info("开始发送邮件。to:{},subject:{},content:{}",to,subject,content);
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容,html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);
            //日志信息
            log.info("邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, File file) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource fileSystemResource = new FileSystemResource(file);
            String fileName = file.getName();
            helper.addAttachment(fileName, fileSystemResource);
            mailSender.send(message);
            //日志信息
            log.info("邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        }
    }
}

mail.html内容 ,这里采用的是thymeleaf

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<body lang=ZH-CN style='tab-interval:21.0pt;text-justify-trim:punctuation'>

<div class=WordSection1 style='layout-grid:15.6pt'>

    <p class=MsoNormal align=left style='text-align:left;mso-pagination:widow-orphan;background:white'>
        <b>
            <span style='mso-bidi-font-size:10.5pt;font-family:"Microsoft YaHei UI",sans-serif;
mso-bidi-font-family:宋体;color:#4D4D4D;mso-font-kerning:0pt' th:text="${tips}">
                您好!您的某某平台的企业账号已经开通,密码是:<span lang=EN-US>&nbsp;</span>
            </span>
        </b>
        <b>
            <span lang=EN-US style='font-size:18.0pt;
font-family:"Microsoft YaHei UI",sans-serif;mso-bidi-font-family:宋体;color:#FF6600;
mso-font-kerning:0pt' th:text="${password}"></span>
        </b>
        <b>
            <span style='mso-bidi-font-size:10.5pt;font-family:"Microsoft YaHei UI",sans-serif;mso-bidi-font-family:宋体;color:#4D4D4D;mso-font-kerning:0pt'>,请及时修改密码。<span style='mso-bidi-font-size:10.5pt;font-family:"Microsoft YaHei UI",sans-serif;
mso-bidi-font-family:宋体;color:#4D4D4D;mso-font-kerning:0pt' th:text="${addr}"></span>
                <span lang=EN-US th:text="${loginUrl}"></span>
            </span>
        </b>
        <span lang=EN-US style='mso-bidi-font-size:10.5pt;font-family:"Microsoft YaHei UI",sans-serif;
mso-bidi-font-family:宋体;color:#4D4D4D;mso-font-kerning:0pt'>
    <p></p></span></p>


    <p class=MsoNormal align=left style='text-align:left;mso-pagination:widow-orphan;
background:white'><span style='font-size:9.0pt;font-family:"Microsoft YaHei UI",sans-serif;
mso-bidi-font-family:宋体;color:#747474;mso-font-kerning:0pt'>注意:该密码为系统初始密码,请及时登录系统并修改密码以保证<span
            class=GramE>帐户</span>安全<span lang=EN-US>&nbsp;<br>
</span>(工作人员不会向你索取密码,请勿泄漏!<span lang=EN-US>)
    <p></p></span></span></p>

    <p class=MsoNormal align=left style='text-align:left;line-height:15.6pt;
mso-pagination:widow-orphan;background:white'><span style='font-size:9.0pt;
font-family:"Microsoft YaHei UI",sans-serif;mso-bidi-font-family:宋体;color:#747474;
mso-font-kerning:0pt'>此为系统邮件,请勿回复<span lang=EN-US><br>
</span>请保管好您的邮箱,避免账号被他人盗用<span lang=EN-US>
    <p></p></span></span></p>

    <p class=MsoNormal><span lang=EN-US>
    <p>&nbsp;</p></span></p>

</div>

</body>

</html>

测试单元 EmailServiceTest

package com.wuyou.email.service;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @Package com.wuyou.email.service.impl
 * @date: 2020/2/29 10:19
 */
@SpringBootTest
@RunWith(SpringRunner.class)
class EmailServiceTest {

    @Autowired
    private EmailService emailService;

    @Autowired
    private TemplateEngine templateEngine;

    public static final String TO_MAIL="418199968@qq.com";

    public static final String SUBJECT="Java发送邮件";

    public static final String PLATFORM_PWD_TIP= "您好!您的某某平台账号已经开通,密码是:";

    public static final String PLATFORM_ADDR= "某某平台地址:";
    /**
     * 发送普通邮件测试
     */
    @Test
    void sendSimpleMail() {
        emailService.sendSimpleMail(TO_MAIL,SUBJECT,"这是一份测试邮件");
    }

    @Test
    void sendHtmlMail() {
        Map<String,Object> parapMap=new HashMap<>();
        parapMap.put("password","123456");
        parapMap.put("tips",PLATFORM_PWD_TIP);
        parapMap.put("addr",PLATFORM_ADDR);
        parapMap.put("loginUrl","https://www.baidu.com");
        Context context=new Context();
        context.setVariables(parapMap);
        String content = this.templateEngine.process("mail", context);
        emailService.sendHtmlMail(TO_MAIL,SUBJECT,content);
    }

    @Test
    void sendAttachmentsMail() {
        File file=new File("C:\\Users\\Administrator\\Desktop\\nginx配置中文详解.rar");
        String content="<h1>这是一份带着附件的Html邮件测试</h1>";
        emailService.sendAttachmentsMail(TO_MAIL,SUBJECT,content,file);
    }
}

测试这三个方法都通过

快看傻子
快看傻子
带附件的html邮件
快看傻子
普通邮件
快看傻子
Html邮件
快看傻子

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值