SpringBoot 项目发邮件

本文介绍了如何在SpringBoot项目中集成邮件发送功能,包括添加mail starter依赖、配置application.yml、编写主入口程序及测试类。通过实例演示了如何使用JavaMailSender发送邮件。

SpringBoot 项目发邮件

1、建立项目springboot项目

image-20220712134527243

<!-- pom.xml 文件添加starter mail依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

项目pom.xml内容如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> 
    </parent>
    <groupId>org.example</groupId>
    <artifactId>sbootmail</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</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-maven-plugin</artifactId>
            <version>2.7.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、 建立项目配置文件yml

src/main/resources/application.yml

spring:
  mail:
    default-encoding: utf-8
    host: smtp.126.com
    username: webrx@126.com
    #此处为邮件服务器的授权码,不是密码
    password: XQUJQKBFBYWRFBKS

3、编写主入口程序

src/main/java/cn/webrx/App.java

package cn.webrx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

4、编写测试程序

src/test/java/cn/webrx/SendMail.java

package cn.webrx;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

@SpringBootTest
public class SendMail {
    @Autowired
    JavaMailSender sender;

    @Test
    void send() {
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setTo("7031633@qq.com");
        smm.setSubject("主题");
        smm.setText("正文");
        smm.setFrom("webrx@126.com");
        sender.send(smm);
    }

    @Test
    void test() {
        System.out.println("hello ");
        System.out.println(SpringBootVersion.getVersion());
    }
}

执行SendMail类的send()方法,测试通过。

image-20220712135315753

### 实现Spring Boot项目的邮件发送功能 #### 添加依赖项 为了使Spring Boot项目具备邮件发送能力,在`pom.xml`文件中需加入特定的依赖声明: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 此操作引入了必要的库来支持邮件发送特性[^1]。 #### 配置邮件服务器参数 接着,应在`application.properties`或`application.yml`文件内定义邮件服务器的相关设置。以下是采用`.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.default-encoding=UTF-8 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 这些属性指定了SMTP主机地址、端口号以及其他连接选项,确保程序能正确地与邮件服务器通信并验证身份。 #### 编写邮件发送服务类 创建一个新的Java类用于封装邮件发送逻辑。这里展示了一个简单的实现方式: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class EmailService { private final JavaMailSender mailSender; @Autowired public EmailService(JavaMailSender mailSender) { this.mailSender = mailSender; } public void sendSimpleEmail(String to, String subject, String text) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(text); mailSender.send(message); } } ``` 上述代码片段展示了如何利用`JavaMailSender`接口及其子组件`MimeMessageHelper`构建一封基础电子邮件,并调用`send()`方法将其发出[^2]。 #### 测试邮件发送功能 最后一步是在控制器或其他地方测试该服务是否正常工作。下面给出一段示例代码用来触发一次实际的邮件发送请求: ```java @RestController @RequestMapping("/api/email") public class EmailController { private final EmailService emailService; @Autowired public EmailController(EmailService emailService){ this.emailService = emailService; } @PostMapping("/send") public ResponseEntity<String> sendEmail(@RequestParam String recipient, @RequestParam String title, @RequestParam String content) { try{ emailService.sendSimpleEmail(recipient,title,content); return ResponseEntity.ok("邮件已成功发送!"); }catch (MessagingException e){ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } } ``` 这段代码提供了一个RESTful API端点,允许外部客户端通过HTTP POST请求向指定收件人发送自定义主题和正文内容的电子邮件。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值