springboot2之邮件发送

本文介绍如何在SpringBoot中实现文本、HTML、附件和图片邮件的发送,包括配置、原理及代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.引言
本文会实现以下几个功能,具体的demo请参考github项目地址链接

 发送文本邮件
 
 发送HTML邮件

 发送附件邮件

 发送带图片的邮件

 邮件模板

二.发送邮件的原理

1.邮件传输协议: SMTP(把邮件从一台服务器发送到另外一台服务器)协议和POP3(把邮件从服务器上拿下来看)协议
SMTP:
    简单邮件传输协议 (Simple Mail Transfer Protocol, SMTP) 是在Internet传输email的事实标准。
SMTP是一个相对简单的基于文本的协议。在其之上指定了一条消息的一个或多个接收者(在大多数情况下被确认是存在的),然后消息文本会被传输。可以很简单地通过telnet程序来测试一个SMTP服务器。SMTP使用TCP端口25。要为一个给定的域名决定一个SMTP服务器,需要使用MX (Mail eXchange) DNS。

POP3:
    POP3是Post Office Protocol 3的简称,即邮局协议的第3个版本,它规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议。它是因特网电子邮件的第一个离线协议标准,POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件,而POP3服务器则是遵循POP3协议的接收邮件服务器,用来接收电子邮件的。

2.内容不断发展: IMAP(保持客户端和服务器上的邮件的状态一致)协议和Mime(通过SMTP进行传输)协议

IMAP:
    IMAP(Internet Mail Access Protocol,Internet邮件访问协议)以前称作交互邮件访问协议(Interactive Mail Access Protocol)。IMAP是斯坦福大学在1986年开发的一种邮件获取协议。它的主要作用是邮件客户端(例如MS Outlook Express)可以通过这种协议从邮件服务器上获取邮件的信息,下载邮件等。当前的权威定义是RFC3501。IMAP协议运行在TCP/IP协议之上,使用的端口是143。它与POP3协议的主要区别是用户可以不用把所有的邮件全部下载,可以通过客户端直接对服务器上的邮件进行操作。

三.实践

1.在springboot的pom文件中引入以下依赖:

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

2.在application.properties配置邮箱参数:

spring.mail.host=smtp.qq.com   //采用smtp形式的传输方式
spring.mail.username=978719222@qq.com  //发送人的邮箱
spring.mail.password=          //第三方授权码
spring.mail.default-encoding=UTF-8   //编码格式

3.代码实现

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.internet.MimeMessage;
import java.io.File;
/**
 * Created by ${ligh} on 2018/12/7 上午9:08
 */
@Service
public class MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

/**
* 发送文本邮件
*
* @param to 接收人
* @param subject 主题
* @param content 邮件内容
*/

public void sendSimpleMail(String to,String subject,String content){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    message.setFrom(from);
    mailSender.send(message);

}

/**
* 发送HTML邮件
*
* @param to
* @param subject
* @param content
*/

public void sendHtmlMail(String to,String subject,String content) throws Exception {

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content,true);
    mailSender.send(mimeMessage);
}

/**
* 发送带副本的邮件
*
* @param to
* @param subject
* @param content
*/

public void sendAttachmentMail(String to,String subject,String content,String filepath) throws Exception {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message,true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content,true);

    //文件流:获取本地文件
    FileSystemResource file = new FileSystemResource(new File(filepath));
    String filename = file.getFilename();
    //可以发送多个
    helper.addAttachment(filename,file);
   // helper.addAttachment(filename+"_test",file);

    //进行发送
    mailSender.send(message);
}

/**
* 发送图片邮件
*
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
* @throws Exception
*/

public void sendImageMail(String to,String subject,String content,String rscPath,String rscId){
    logger.info("发送静态邮件开始: {},{},{},{},{}",to,subject,content,rscPath,rscId);
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    try{
        helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);

        FileSystemResource file = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId,file);
        mailSender.send(message);
        logger.info("发送静态图片邮件成功!");
    }catch (Exception e){
        logger.error("发送静态邮件失败!",e);
    }

  }
}

4.测试代码

import com.ligh.service.MailService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;

/**
 * Created by ${ligh} on 2018/12/7 上午9:23
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestSpringbootEmail {

    @Resource
    MailService mailService;

    @Resource
    TemplateEngine templateEngine;

/**
* 简单文本邮件发送
*/

@Test
 public void sendSimpleMailTest(){
     mailService.sendSimpleMail("liguohui@163.com","简单文本邮件","这是我的第一封邮件,哈哈...");
 }

/**
* HTML邮件发送
*
* @throws Exception
*/

@Test
 public void sendHtmlMailTest() throws Exception{

     String content = "<html>\n"+
                     "<body>\n" +
                         "<h1 style=\"color: red\"> hello world , 这是一封HTML邮件</h1>"+
                     "</body>\n"+
                     "</html>";


     mailService.sendHtmlMail("liguohui@163.com","Html邮件发送",content);
 }

/**
* 发送副本邮件
*
* @throws Exception
*/

@Test
 public void sendAttachmentMailTest() throws Exception{
     String filepath = "/Users/fish/Desktop/linux 常用命令.pdf";

     mailService.sendAttachmentMail("liguohui@163.com","发送副本","这是一篇带附件的邮件",filepath);

 }

/**
* 发送图片邮件
*
* @throws Exception
*/

 @Test
 public void sendImageMailTest() throws Exception{
     //发送多个图片的话可以定义多个 rscId,定义多个img标签

     String filePath = "/Users/fish/Desktop/test.png";
     String rscId = "ligh001";
     String content = "<html><body> 这是有图片的邮件: <img src=\'cid:"+rscId+"\'> </img></body></html>";

     mailService.sendImageMail("liguohui@huluwa.cc","这是一个带图片的邮件",content,filePath,rscId);
 }

/**
* 发送邮件模板
*
* @throws Exception
*/

@Test
public void sendTemplateEmailTest() throws Exception {
    Context context = new Context();
    context.setVariable("id","006");
    String emailContent = templateEngine.process("templates",context);
    mailService.sendHtmlMail("lighAsqh@163.com","这是一个模板文件",emailContent);
}

}

以上就完成了springboot2中邮箱的发送,详细的demo请参考github的项目。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值