Spring-boot邮件发送

本文介绍如何使用 Spring Boot 发送多种类型的邮件,包括文本、HTML、带附件及图片邮件,并提供完整的代码示例。

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

1.pom.xml依赖

		<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>
        </dependency>

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

application.properties代码;

spring.mail.host=smtp.qq.com
spring.mail.username=//自己邮箱账号(发件人)
spring.mail.password=ladgtaxnwdotbbeg  //为授权码,比如若账号是自己qq邮箱,这里的密码不是qq密码而是授权码
spring.mail.default-encoding=UTF-8


service层代码:

package com.feng.email.service;
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.Service;

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

@Service
public class EmailService {

    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);
        }

    }


}

测试类 EmailApplicationTests

package com.feng.email;

import com.feng.email.service.EmailService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailApplicationTests {
    @Resource
    EmailService mailService;
    /**
     * 简单文本邮件发送
     */
    @Test
    public void contextLoads() {
        mailService.sendSimpleMail("dpfenglei@dfl.com.cn","简单文本邮件","这是我的第一封邮件,哈哈...");
    }
    /**
     * 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("dpfenglei@dfl.com.cn","Html邮件发送",content);
    }
    /**
     * 发送副本邮件
     *
     * @throws Exception
     */
    @Test
    public void sendAttachmentMailTest() throws Exception{
        String filepath = "C:\\Users\\95892\\Desktop\\笔记.txt";
        mailService.sendAttachmentMail("dpfenglei@dfl.com.cn","发送副本","这是一篇带附件的邮件",filepath);

    }
    /**
     * 发送图片邮件
     *
     * @throws Exception
     */
    @Test
    public void sendImageMailTest() throws Exception{
        //发送多个图片的话可以定义多个 rscId,定义多个img标签
        String filePath = "C:\\Users\\95892\\Pictures\\Saved Pictures\\8800276_184927469000_2.png";
        String rscId = "ligh001";
        String content = "<html><body> 这是有图片的邮件: <img src=\'cid:"+rscId+"\'> </img></body></html>";
        mailService.sendImageMail("dpfenglei@dfl.com.cn","这是一个带图片的邮件",content,filePath,rscId);
    }

}

友情提示:

如采qq邮箱当发件人这需要qq邮箱开通:(进入qq邮箱,点击设置->进入账户开通即可)
在这里插入图片描述

Spring Boot Starter Mail是一个轻量级的启动器,它包含了发送电子邮件所需的基本依赖,使得在Spring Boot应用中集成邮箱功能变得更加简单。要使用这个组件,首先你需要添加`spring-boot-starter-mail`到你的项目的`pom.xml`或者`build.gradle`文件中。 以下是基本步骤: 1. 添加依赖:在Maven中,添加到`<dependencies>`标签内: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 在Gradle中,添加到`dependencies`块中: ```groovy implementation 'org.springframework.boot:spring-boot-starter-mail' ``` 2. 配置邮件服务器:在`application.properties`或`application.yml`中设置发件人的邮箱地址、SMTP服务器信息,例如: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=myemail@example.com spring.mail.password=mypassword spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建Java配置类,如`MailSenderConfiguration`,并注入`JavaMailSender`: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; @Configuration public class MailSenderConfig { @Autowired private JavaMailSender javaMailSender; // 省略其他配置方法... } ``` 4. 实现发送邮件的Service或者Repository,调用`javaMailSender`实例的方法,比如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @Autowired private JavaMailSender mailSender; public void sendEmail(SimpleMailMessage message) { mailSender.send(message); } ``` 5. 使用`SimpleMailMessage`构造函数构建邮件内容: ```java SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo("recipient@example.com"); mailMessage.setSubject("测试邮件"); mailMessage.setText("这是一封测试邮件的内容."); sendEmail(mailMessage); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值