SpringBoot发送Email

11 篇文章 0 订阅

SpringBoot发送Email邮件

导入依赖

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

<dependency>
   <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

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

定义邮件配置

# 发送人邮件
spring.mail.username=xxxx@foxmail.com
# 接收人邮件
spring.mail.toUser=xxxxx@qq.com
# 发送人邮件授权码
spring.mail.password=xxxxx
# 发送主机类型
spring.mail.host=smtp.qq.com
# 端口
spring.mail.port=465
# 字符集
spring.mail.default-encoding=UTF-8
# 发送邮件协议 全部开启
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

yml格式

spring:
  mail:
  	username: xxxx@foxmail.com
	toUser: xxxxx@qq.com
	password: xxxxxx
	host: smtp.qq.com
	port: 465
	default-encoding: UTF-8
	properties:
	  mail:
	    smtp:
	      ssl:
	        enable: true
		  auth: true
		  starttls:
		    enable: true
		  starttls:
		    required: true

发送邮件核心类

package cn.molu.email.service;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author molu
 * @date 2022/9/27 21:32
 * @apiNote
 */

@Service("sendMail")
public class SendMail {

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

    @Resource
    private JavaMailSender mailSender;

    /**
     * 发送简单邮件
     */
    public void sendSimpleMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("邮箱主题:主题");
        message.setText("邮件内容:异常登录提醒!");
        message.setTo(toUser);
        message.setFrom(fromUser);
        mailSender.send(message);
    }

    /**
     * 发送携带HTML标签的邮件
     */
    public void sendSimpleHtmlMail() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(fromUser);
        helper.setSubject("邮件主题:异常提醒");
        helper.setText("<h1 style='color:red'>异常提醒:登录异常!</h1>", true);
        helper.setTo(toUser);
        mailSender.send(mimeMessage);
    }

    /**
     * 发送携带img图片的邮件
     */
    public void sendSimpleImgMail() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 需要开启 multipart 文件支持
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        String id = "test";
        String imgPath = "C:\\Users\\dell\\Desktop\\test.png";
        helper.setSubject("邮件主题:图片消息");
        helper.setText("<a href='www.baidu.com'><img src='cid:" + id + "'/></a>", true);
        FileSystemResource resource = new FileSystemResource(new File(imgPath));
        helper.addInline(id, resource);
        helper.setTo(toUser);
        helper.setFrom(fromUser);
        mailSender.send(mimeMessage);
    }

    /**
     * 发送携带附件的邮件
     */
    public void sendSimpleResourceMail() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 需要开启 multipart 文件支持
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        String id = "test";
         String imgPath = "C:\\Users\\dell\\Desktop\\test.png";
        helper.setSubject("邮件主题:图片消息");
        helper.setText("<a href='www.baidu.com'><img src='cid:" + id + "'/></a>", true);
        FileSystemResource resource = new FileSystemResource(new File(imgPath));
        helper.addInline(id, resource);
        // 发送附件
        helper.addAttachment("test.png",resource);
        helper.setTo(toUser);
        helper.setFrom(fromUser);
        mailSender.send(mimeMessage);
    }

    /**
     * 异步发送简单邮件
     */
    @Async // 开启异步注解方法
    public void asyncSendSimpleMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("邮箱主题:主题");
        message.setText("邮件内容:异常登录提醒!");
        message.setTo(toUser);
        message.setFrom(fromUser);
        mailSender.send(message);
    }
}

发送邮件控制层

package cn.molu.email.controller;
import cn.molu.email.service.SendMail;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.mail.MessagingException;

/**
 * @author molu
 * @date 2022/9/27 21:32
 * @apiNote
 */
@RestController
@RequestMapping("/index/*")
public class IndexController {

    @Resource
    private SendMail sendMail;

    /**
     * 发送简单文本邮件
     */
    @GetMapping("sendText")
    public void sendSimpleMail() {
        sendMail.sendSimpleMail();
    }

    /**
     * 发送html邮件
     */
    @GetMapping("sendHtmlMail")
    public void sendSimpleHtmlMail() throws MessagingException {
        sendMail.sendSimpleHtmlMail();
    }

    /**
     * 发送图片邮件
     */
    @GetMapping("sendImgMail")
    public void sendSimpleImgMail() throws MessagingException {
        sendMail.sendSimpleImgMail();
    }

    /**
     * 发送附件邮件
     */
    @GetMapping("sendResourceMail")
    public void sendSimpleResourceMail() throws MessagingException {
        sendMail.sendSimpleResourceMail();
    }

    /**
     * 异步发送邮件
     */
    @GetMapping("asyncSendMail")
    public void asyncSendSimpleMail() throws MessagingException {
        sendMail.asyncSendSimpleMail();
    }
}

项目启动类开启异步

package cn.molu.email;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync // 开启异步支持
@SpringBootApplication
public class EmailApplication {
    public static void main(String[] args) {
        SpringApplication.run(EmailApplication.class, args);
    }
}
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、付费专栏及课程。

余额充值