springboot项目发送邮件

本文介绍如何使用 Spring Boot 发送不同类型的邮件,包括简单邮件、HTML 格式邮件、带附件邮件及包含图片的邮件,并提供了一个示例项目来演示整个过程。

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

最初的发送邮件要用javamail,后来spring提供了JavaMailsender接口简化了代码。springboot更是提供了spring-boot-starter-mail

Spring 的 JavaMailSenderImpl 提供了强大的邮件发送功能,可发送普通文本邮件、带附件邮件、HTML 格式邮件、带图片邮件,设置发送内容编码格式、设置发送人的显示名称。

简述几个概念:

Message 类:定义发送人。收件人。标题。内容。发送时间等信息的创建和解析邮件的核心API

Transport 类:发送邮件的核心 API 类。

Store 类:接收邮件的核心API类。

邮件相关协议内容如下。

  • SMTP 协议:发送邮件协议;
  • POP3 协议:获取邮件协议;
  • IMAP:接收信息的高级协议;
  • MIME:邮件拓展内容格式:信息格式,附件格式。

下图用于演示两帐户相互发送邮件的过程:

亲测代码如下:

引入依赖包

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

定义发送邮件的接口

public interface MailService {

    public void sendSimpleMail(String to, String subject, String content);//简单邮件

    public void sendHtmlMail(String to, String subject, String content);//html邮件

    public void sendAttachmentsMail(String to, String subject, String content, String filePath);//带附件邮件

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);//带静态资源文件(图片)的邮件

}
package com.neo.service.mail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * 邮件发送: 描述信息
 *
 * @author liyy
 * @date 2018-07-18 14:22
 */
@Component
public class MailServiceImpl implements MailService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);

        try {
            mailSender.send(simpleMailMessage);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }
    }

    @Override
    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.setSubject(subject);
            helper.setTo(to);
            helper.setText(content);
            helper.setCc("liyingying@heatedloan.com");//抄送
            mailSender.send(message);
            logger.info("html邮件已经发送。");
        } catch (MessagingException e) {
            logger.info("html邮件已经发送。");
            e.printStackTrace();
        }

    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setTo(to);
            helper.setText(content);
            helper.setCc("liyingying@heatedloan.com");//抄送
            //添加附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName,file);
            mailSender.send(message);
            logger.info("带附件邮件已经发送。");
        } catch (MessagingException e) {
            logger.info("带附件邮件已经发送。");
            e.printStackTrace();
        }
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setTo(to);
            helper.setText(content);
            helper.setCc("liyingying@heatedloan.com");//抄送
            //添加附件
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId,file);
            mailSender.send(message);
            logger.info("带静态资源文件邮件已经发送。");
        } catch (MessagingException e) {
            logger.info("带静态资源文件邮件已经发送。");
            e.printStackTrace();
        }
    }
}

测试类

package com.neo;

import com.neo.service.mail.MailService;
import org.junit.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.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testSimpleMail() throws Exception {
        mailService.sendSimpleMail("1132879189@qq.com","这是一封简单邮件","大家好,这是我的第一封邮件!");
    }

    @Test
    public void testHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail("1132879189@qq.com","这是一封HTML邮件",content);
    }

    @Test
    public void sendAttachmentsMail() {
        String filePath="C:\\bqs\\分期还打包目录\\test\\spring-boot-package-war.war";
        mailService.sendAttachmentsMail("1132879189@qq.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
    }


    @Test
    public void sendInlineResourceMail() {
        String rscId = "neo006";
        String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "C:\\bqs\\分期还打包目录\\test\\login-bg.jpg";

        mailService.sendInlineResourceMail("1132879189@qq.com", "主题:这是有图片的邮件", content, imgPath, rscId);
    }


    /**
     * 按照模板发送邮件
     */
    @Test
    public void sendTemplateMail() {
        //创建邮件正文
        Context context = new Context();
        context.setVariable("id", "006");
        String emailContent = templateEngine.process("template1", context);

        mailService.sendHtmlMail("1132879189@qq.com","主题:这是模板邮件",emailContent);
    }
}

template1对应html文件的名称。html作为模板邮件进行发送

例如一个template1.html如下:

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>邮件模板</title>
    </head>
    <body>
        您好,感谢您的注册,这是一封验证邮件,请点击下面的链接完成注册,感谢您的支持!<br/>
        <a href="#" th:href="@{http://www.ityouknow.com/register/{id}(id=${id}) }">激活账号</a>
    </body>
</html>

配置文件如下:

application.properties

spring.mail.host=smtp.qq.com
spring.mail.username=215682148@qq.com
spring.mail.password=iipjqncncrgvcbcf
spring.mail.default-encoding=UTF-8
spring.application.name=spirng-boot-mail

spring.mail.password=iipjqncncrgvcbcf  这里的密码并非登陆邮件的密码。而是第三方登陆邮件所需要的授权码。如果是qq邮箱则需要登陆qq邮箱进行授权。

 

### Spring Boot 中 JavaMailSender 的配置与使用 #### Maven 依赖引入 为了在 Spring Boot 应用程序中启用邮件发送功能,需先添加 `spring-boot-starter-mail` 作为项目的依赖项。该依赖包含了必要的库用于支持 SMTP 协议下的邮件传输服务[^4]。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` #### 配置邮件服务器参数 接着,在 application.properties 或者 application.yml 文件里定义具体的邮件服务器连接属性,比如主机地址、端口号以及认证凭证等信息。这些设置允许应用程序成功建立到指定邮件服务器的安全会话[^2]。 对于 properties 文件而言: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=user@example.com spring.mail.password=yourpassword spring.mail.protocol=smtp spring.mail.smtp.auth=true spring.mail.smtp.starttls.enable=true ``` 而对于 YAML 格式的配置,则如下所示: ```yaml spring: mail: host: smtp.example.com port: 587 username: user@example.com password: yourpassword protocol: smtp smtp: auth: true starttls: enable: true ``` #### 编写邮件发送逻辑 完成上述准备工作之后,就可以利用 `@Autowired` 注解自动装配 `JavaMailSender` 接口实例,并编写实际负责构建和发出邮件的方法了。下面给出一段简单的例子展示怎样创建一封纯文本形式的电子邮件并将其发送出去[^1]。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Service; @Service public class EmailService { private final JavaMailSender javaMailSender; @Autowired public EmailService(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; } public void sendSimpleEmail(String to, String subject, String text){ SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } } ``` 以上就是关于如何在 Spring Boot 环境下集成 JavaMailSender 来实现基本的邮件发送操作的大致流程介绍。值得注意的是,具体实施过程中可能还需要考虑更多细节问题,例如异常处理机制的设计或是针对不同类型的附件的支持等等[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值