SpringBoot实现自动发送邮件功能

【应用场景】:

在很多网站注册页面中,我们都能看到网站实现了一个自动发送邮件的功能,给你发送验证码。那么这个过程是如何实现的呢?本次实验采用SpringBoot框架。

【解决步骤】:

实现这个功能大致就是以下5个步骤:

  1. 导入支持邮件发送功能的依赖
  2. 对邮箱进行一些设置,使其具有自动发送功能
  3. 在application.properties文件下进行相应的配置
  4. 编写邮件服务的核心类(重点)
  5. 测试

【导入依赖】:

在pom.xml中导入spring-boot-starter-mail依赖:

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

【开启邮箱支持】:

我用的是腾讯邮箱。
登陆邮箱之后,点击设置->账户,拉到比较下面的位置来,看到以下设置:
在这里插入图片描述
前两个随便开启一个就行了,我两个都开启了。
然后根据它的指引操作,你会获得一个授权码 。这个授权码记录下来,很重要,后面要使用。你的邮箱之所以能完成自动发送,就是因为有这个授权码授权。

【配置文件】:

在application.properties中进行相应的主配置。

#这里指明发送方的邮箱
spring.mail.username=XXX@qq.com

#password填我们刚刚说的授权码
spring.mail.password=填写你的授权码
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
spring.mail.properties.mail.smtp.starttls.required=true

spring.application.name=spirng-boot-mail
spring.mail.host=smtp.qq.com

#这个是非必须,我自己自定义的,可以便于程序中取值
mail.fromMail.addr=XXX@qq.com

配置文件就这样写,除了发送方和授权码那里自己设置以下,其他地方不动即可。

【实现发送功能】:

终于可以开始编写Service类了,这是最关键的一步。

为了贯彻SpringBoot中的面向接口编程思想,我们先定义一个接口:

package com.example.demo.serviceInterface;

public interface MailService {

    /**
     * 发送简单邮件
     * @param to
     * @param subject
     * @param content
     */
    void sendMail(String to,String subject,String content);
}

接下来就是把这个接口实现掉
定义一个MailServiceImpl类来实现

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.example.demo.serviceInterface.MailService;

@Service
public class MailServiceImpl implements MailService{
	@Autowired
	private JavaMailSender javaMailSender;
	@Value("${mail.fromMail.addr}")
	private String from;
	
	 /**
	 * 发送简单邮件
	 * @param to 接受者。邮件的接受方
	 * @param subject 主题。邮箱标题
	 * @param content 内容。是邮箱的Text
	 */
	 public void sendMail(String to, String subject, String content) {
	        SimpleMailMessage mailMessage=new SimpleMailMessage();
	        mailMessage.setFrom(from);//发起者
	        mailMessage.setTo(to);//接受者
	        //多人mailMessage.setTo("1xx.com","2xx.com","3xx.com");
	        mailMessage.setSubject(subject);
	        mailMessage.setText(content);
	        try {
	        	javaMailSender.send(mailMessage);
	            System.out.println("发送简单邮件");
	        }catch (Exception e){
	            System.out.println("发送简单邮件失败");
	        }
	    }
}

详细解释一下实现过程:

  1. JavaMailSender是mail依赖包中的一个类,我们需要它来send邮件,因此注入进来
  2. form的值直接通过properties文件中的配置注入进来了
  3. SimpleMailMessage这个类也是mail依赖中的一个消息类,我们需要用它来包装我们发送的邮件信息
  4. 通过JavaMailSender发送SimpleMailMessage

【测试代码】:

package com.example.demo.service;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.demo.serviceInterface.MailService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestMailServiceImpl {
	@Autowired
	MailServiceImpl mailServiceImpl;
	 
	@Test
	public void testSendMail() throws Exception{
		//设置你想要将邮件发送到哪个邮箱
		String to = "XXX@qq.com";
		//后面两个参数,设置邮件的主题、邮件的文本内容
		mailServiceImpl.sendMail(to, "简单邮件", "SpringBoot的邮件实现");
	}
}

【测试结果】:

确实发送了
在这里插入图片描述
控制台也有打印:
在这里插入图片描述

【总结】:

整个过程走下来,可能会遇到一些bug,细心调试,要学会查看错误信息中的Cause By,都可以成功的,实际上并没有什么特别难的地方。像这些小功能的学习,如果找到一篇对的参考博客,给出一个简单的demo,那么将事半功倍!
我的参考博客:https://blog.csdn.net/weixin_39220472/article/details/80208125#commentBox

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
适用人群通用各大网易系,腾讯QQ系,新浪系,阿里系等主流邮箱;同时也适用于企业开发的企业邮箱,进行收件和发件。课程概述通用各大网易系,腾讯QQ系,新浪系,阿里系等主流邮箱;同时也适用于企业开发的企业邮箱,进行收件和发件。POP3是Post Office Protocol 3的简称,即邮局协议的第3个版本,它规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议。它是因特网电子邮件的第一个离线协议标准,POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件,而POP3服务器则是遵循POP3协议的接收邮件服务器,用来接收电子邮件的SMTP 的全称是“Simple Mail Transfer Protocol”,即简单邮件传输协议。它是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP 协议属于 TCP/IP 协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循 SMTP 协议的发送邮件服务器。   SMTP 认证,简单地说就是要求必须在提供了账户名和密码之后才可以登录 SMTP 服务器,这就使得那些垃圾邮件的散播者无可乘之机。。【开发者如何进行快速开发邮件发送系统???本课程系统进行快速研发,项目实战】 部分截图如下:完整版请查看课件或者视频
首先,你需要在 Spring Boot 项目中添加 Redis 和 Spring Mail 的依赖。 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 然后,你需要在 application.properties 文件中配置 Redis 和 Mail 相关的属性。 ``` # Redis spring.redis.host=127.0.0.1 spring.redis.port=6379 # Mail spring.mail.host=smtp.gmail.com spring.mail.port=587 [email protected] spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 接着,你需要创建一个 Redis 队列,用于存储待发送邮件的信息。可以使用 RedisTemplate 来操作 Redis 队列。 ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void sendEmail(String to, String subject, String content) { Email email = new Email(to, subject, content); redisTemplate.opsForList().leftPush("email_queue", email); } ``` 最后,你需要创建一个定时任务,从 Redis 队列中取出邮件信息,并使用 JavaMailSender 发送邮件。 ``` @Autowired private JavaMailSender javaMailSender; @Scheduled(fixedDelay = 1000) public void sendEmailFromQueue() { Email email = (Email) redisTemplate.opsForList().rightPop("email_queue"); if (email != null) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(email.getTo()); message.setSubject(email.getSubject()); message.setText(email.getContent()); javaMailSender.send(message); } } public class Email { private String to; private String subject; private String content; public Email(String to, String subject, String content) { this.to = to; this.subject = subject; this.content = content; } // getters and setters } ``` 这样,你就可以使用 Redis 自动发送邮件了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值