SpringBoot 实现邮件发送功能

1.知识点疏通

邮件再项目中经常会被用到,比如邮件发送通知,比如通过邮件注册,认证,找回密码,系统报警通知,报表信息等。 接下来先了解一下邮件协议。

1.1 SMTP、POP、IMAP4协议

  • SMIP协议
    SMTP全称"SImple MAil Transfer Protocol",即简单邮件传输协议。它是一组用于从源地地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式,它的一个重要特点是它能够在传送中接力传送邮件,即邮件可以通过不同网络上的主机接力式传送。

  • POP协议
    POP邮局协议负责从邮件服务器中检索电子邮件。它要求邮件服务器完成下面集中任务之一:从邮件服务器中检索邮件并从服务器中删除这个邮件;从邮件服务器中检索邮件但不删除它;不检索邮件,只是询问是否有新邮件到达。
    POP协议支持多用户互联网邮件扩展,也就是说允许用户进行任何格式文件传输,包括图片喝声音文件等,在用户阅读邮件时,POP协议会将所有的邮件信息立即下载到用户的计算机上,不在服务器上保留。
    POP3是因特网电子邮件的第一个离线协议标准。

  • IMAP协议
    互联网信息访问协议(IMAP)是一种优于POP的新协议,和POP一样,IMAP可以下载邮件,从服务器中删除邮件或询问是否有新的邮件,但IMAP克服了一些POP的缺点,例如,它可以决定客户机请求邮件服务器提交所收到邮件方式,请求邮件服务器只下载所选中的邮件而不是全部邮件,客户机可先阅读邮件信息的标题和发送者名字再决定是否下载这个邮件。

2. springboot集成mail

2.1 配置依赖

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

2.2 配置application.yml

全部配置大全 properties版

#发件人邮件服务器地址
spring.mail.host=smtp.163.com
#发件人邮件服务器端口
spring.mail.port=465
#发件人邮件登录用户
spring.mail.username=jerome_wzy@163.com
#发件人邮件登录授权码
spring.mail.password=BWWREEWSEBGSSKU
#邮件登录字符集编码
spring.mail.default-encoding=UTF-8
#邮件发送的加密方式
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
#是否开启SSL访问邮件服务器
spring.mail.properties.mail.smtp.ssl.enable=true
#邮件发送的调试模式,打开后查看邮件发送的详细日志
spring.mail.properties.mail.debug=true

常见的邮件服务器地址:https://blog.youkuaiyun.com/ning521513/article/details/79217203

本项目配置的application.yml

spring:
  mail:
    host: smtp.qq.com  #qq邮件服务器地址 有其他地址
    username: 123456@qq.com #发件人邮箱
    password: 123456 #授权码
    default-encoding: UTF-8 #邮件登录字符集编码
    port: 25 #发件人邮件服务器端口

授权码获取方式(qq为例)
点击设置

点击账户

在下面找到“POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务”,选择第二项中的“IMAP/SMTP服务”,进行开启

2.3 启动类

@SpringBootApplication
public class SpringbootMailApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMailApplication.class, args);
    }

}

2.4 邮件工具类(MailUtil)

package com.example.springbootmail.util;

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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * <p><p/>
 *
 * @Author: porridge
 * @Date:2022/3/30 10:17
 */
@Component
public class MailUtil {
    @Value("${spring.mail.username}")
    String from;

    @Autowired
    JavaMailSender mailSender;
    //简单邮件
    public void sendSimpleMail(String to, String subject, String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); //发件人
        message.setTo(to);//收件人
        message.setSubject(subject); //标题
        message.setText(content);   //文件内容

        try {
            mailSender.send(message);
            System.out.println("简单邮件发送成功!");
        } catch (Exception e){
            System.out.println("发送简单邮件时发生异常!"+e);
        }
    }
    //html格式邮件
    public void sendHtmlMail(String to, String subject, String content){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            System.out.println("html邮件发送成功!");
        } catch (MessagingException e) {
            System.out.println("发送html邮件时发生异常!"+e);
        }
    }

    //带附件的邮件
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        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 file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            System.out.println("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            System.out.println("发送带附件的邮件时发生异常!" + e);
        }
    }

    //带静态资源的邮件
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        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 res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            System.out.println("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            System.out.println("发送嵌入静态资源的邮件时发生异常!" + e);
        }
    }
}

2.5 测试

@SpringBootTest
class SpringbootMailApplicationTests {

    @Autowired
    MailUtil mailUtil;

    //发送简单邮件测试
    @Test
    void contextLoads() {
        mailUtil.sendSimpleMail("123456@qq.com","标题","内容");

    }
    //发送带附件的邮件
    @Test
    void testHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封Html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailUtil.sendHtmlMail("123456@qq.com","test simple mail",content);
    }
    //发送带附件的邮件
    @Test
    void sendAttachmentsMail() {
        String filePath="D:\\photo\\head_img\\1.jpg";
        mailUtil.sendAttachmentsMail("123456@qq.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
    }

    //发送带静态资源(图片)
    @Test
    void sendInlineResourceMail() {
        String rscId = "neo006";
        String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "D:\\photo\\head_img\\1.jpg";
        mailUtil.sendInlineResourceMail("123456@qq.com", "主题:这是有图片的邮件", content, imgPath, rscId);
        //添加多个图片可以使用多条 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 来实现
    }

}

简单

html

带附件

静态资源

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值