springboot 发送邮件

本文介绍如何在 Spring Boot 应用中配置并实现邮件发送功能,包括文本邮件、带附件邮件及包含静态资源的邮件。通过示例代码演示了如何配置邮件服务器、设置邮件属性,并展示了不同类型的邮件发送方式。

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

1、添加依赖

      <!-- 发送邮件. -->

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

 

2、添加配置

# 设置邮箱主机

spring.mail.host= smtp.qq.com

# 设置用户名,需要注意的是username是登陆邮箱是的用户名而不是邮箱,password是登陆邮箱的密码

spring.mail.username=邮箱登录用户名

# 设置密码

spring.mail.password=登录密码

# 设置是否需要认证,如果为true,那么用户名和密码就必须的,

#如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。

spring.mail.properties.mail.smtp.auth=ture

# STARTTLS[1]  是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。

spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.properties.mail.smtp.starttls.required=true

spring.mail.properties.mail.smtp.connectiontimeout=5000

spring.mail.properties.mail.smtp.timeout=3000

spring.mail.properties.mail.smtp.writetimeout=5000

 

3、测试代码       

         /**

          * 修改application.properties的用户,才能发送。

          */

         @Test
         @Ignore
         public void sendSimpleEmail() {
                   SimpleMailMessage message = new SimpleMailMessage();
                   message.setFrom("xxxx@126.com ");// 发送者.
                   message.setTo("xxxx@126.com");// 接收者.
                   String[] ccList = new String[] { "xxxx@126.com", "yang.junming@xxxx.com" };
                   // 这里添加抄送人名称列表
                   message.setCc(ccList);
                   String[] bccList = new String[] { "yyyy@126.com", "yjmyzz@xxxx.com" };//
                   // 这里添加密送人名称列表
                   message.setBcc(bccList);
                   message.setSubject("测试邮件(邮件主题)");// 邮件主题.
                   message.setText("这是邮件内容");// 邮件内容.
                   mailSender.send(message);// 发送邮件
         }



         /**

          * 测试发送附件.(这里发送图片.)

          *

          * @throws MessagingException

          */

         @Test
         @Ignore
         public void sendAttachmentsEmail() throws MessagingException {
                   // 这个是javax.mail.internet.MimeMessage下的,不要搞错了。
                   MimeMessage mimeMessage = mailSender.createMimeMessage();
                   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                   // 基本设置.
                   helper.setFrom("xxxx@126.com ");// 发送者.
                   helper.setTo(new String[] { " xxxx@126.com ", " xxxx@163.com " });// 接收者.

                   // helper.setTo("1354737677@163.com");// 接收者.
                   helper.setSubject("测试附件(邮件主题)");// 邮件主题.
                   helper.setText("这是邮件内容(有附件哦.)");// 邮件内容.
                   // org.springframework.core.io.FileSystemResource下的:
                   // 附件1,获取文件对象.
                   FileSystemResource file1 = new FileSystemResource(new File("E:/文档/图片/git.png"));
                   // 添加附件,这里第一个参数是在邮件中显示的名称,也可以直接是head.jpg,但是一定要有文件后缀,不然就无法显示图片了。
                   helper.addAttachment("git.png", file1);
                   // 附件2
                   // FileSystemResource file2 = new FileSystemResource(
                   // new File("E:/spring boot/Spring Boot中使用Swagger2构建强大的RESTful
                   // API文档.docx"));
                   File file2 = new File("E:/技术/spring boot/Test邮件附件测试.docx");
                   String filename = null;
                   try {
                            filename = MimeUtility.encodeWord(file2.getName());
                            // filename = MimeUtility.encodeText(file2.getName());
                   } catch (UnsupportedEncodingException e1) {
                            e1.printStackTrace();
                   }

                   byte bytes[] = { (byte) 0xC2, (byte) 0xA0 };
                   String UTFSpace = null;
                   try {
                            UTFSpace = new String(bytes, "utf-8");
                   } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                   }
                   filename = filename.replaceAll(UTFSpace, "&nbsp;");
                   filename = filename.replaceAll("\r", "").replaceAll("\n", "");
                   System.out.println("fileName>" + file2.getName());
                   helper.addAttachment(filename, file2);
                   // 邮件正文显示图片 第二个参数指定发送的是HTML格式,同时cid:是固定的写法
                   helper.setText("<body>这是图片:<img src='cid:head' /></body>", true);
                   FileSystemResource file = new FileSystemResource(new File("E:/文档/图片/spring.png"));
                   helper.addInline("head", file);
                   mailSender.send(mimeMessage);
         }



         /**

          * 邮件中使用静态资源.

          *

          * @throws Exception

          */

         @Test
         @Ignore
         public void sendInlineMail() throws Exception {
                   MimeMessage mimeMessage = mailSender.createMimeMessage();
                   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                   // 基本设置.
                   helper.setFrom("xxxx@126.com ");// 发送者.
                   helper.setTo("xxxx@126.com ");// 接收者.
                   helper.setSubject("测试静态资源(邮件主题)");// 邮件主题.
                   // 邮件内容,第二个参数指定发送的是HTML格式
                   // 说明:嵌入图片<img src='cid:head'/>,其中cid:是固定的写法,而aaa是一个contentId。
                   helper.setText("<body>这是图片:<img src='cid:head' /></body>", true);
                   FileSystemResource file = new FileSystemResource(new File("E:/文档/图片/spring.png"));
                   helper.addInline("head", file);
                   mailSender.send(mimeMessage);

         }

 

Spring Boot发送邮件通常通过JavaMail API实现,Spring Boot提供了一个方便的集成方式,无需额外配置SMTP服务器。以下是使用Spring Boot发送邮件的基本步骤: 1. 添加依赖:在`pom.xml`文件中添加Spring Boot Actuator和JavaMail的相关依赖,例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 配置邮箱服务:在application.properties或application.yml文件中设置SMTP服务器的信息,如主机名、端口、用户名、密码等: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=your-email@example.com spring.mail.password=your-password spring.mail.protocol=smtp spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建邮件消息:创建一个Java类,继承`AbstractMessageConverter`或使用`SimpleMailMessage`来构建邮件内容: ```java import org.springframework.mail.SimpleMailMessage; SimpleMailMessage message = new SimpleMailMessage(); message.setTo("recipient@example.com"); message.setFrom("sender@example.com"); message.setSubject("Hello from Spring Boot"); message.setText("This is a test email."); ``` 4. 使用Java配置或注解:在Spring Boot应用中,你可以使用Java配置类配置一个`JavaMailSender`实例,然后在需要的地方发送邮件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; @Autowired private JavaMailSender javaMailSender; public void sendEmail(SimpleMailMessage message) { javaMailSender.send(message); } ``` 或者使用`@Autowired`自动注入并在方法上使用`@SendMail`注解: ```java @RestController public class EmailController { @Autowired private JavaMailSender javaMailSender; @PostMapping("/send-email") @SendMail public ResponseEntity<String> sendMessage(SimpleMailMessage message) { // ...处理并返回响应 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值