1.引入邮箱依赖
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-mail</artifactid>
</dependency>2.配置邮箱
spring:
mail:
host: smtp.qq.com
username: 你的qq邮箱@qq.com
password: 你的授权码 #需要自己去邮箱内开启smtp服务
default-encoding: utf-8
port: 465
protocol: smtp
properties:
mail:
smtp:
auth: true
ssl:
enable: true
socketfactory:
class: javax.net.ssl.sslsocketfactory3.测试发送一封简单的邮件:
@autowired
javamailsender javamailsender;
@test
public void test() throws exception {
// 创建一个邮件消息
mimemessage message = javamailsender.createmimemessage();
// 创建 mimemessagehelper
mimemessagehelper helper = new mimemessagehelper(message, false);
// 发件人邮箱和名称
helper.setfrom("747692844@qq.com", "springdoc");
// 收件人邮箱
helper.setto("admin@springboot.io");
// 邮件标题
helper.setsubject("hello");
// 邮件正文,第二个参数表示是否是html正文
helper.settext("hello <strong> world</strong>! ", true);
// 发送
javamailsender.send(message);
}实际代码-前置条件:
1.将邮件发送功能封装在一个公共类里,方便其他地方调用
- 依赖:工具类在 common → 所有子服务不用重复导 mail 依赖;
- yml 配置:无论工具放哪,每个要发邮件的微服务都必须自己配 mail 配置;
- 调用:其他服务注入 mailutil 直接调用,不用再写创建 mimemessage 那套底层代码
package com.bite.common.utils;
import jakarta.mail.internet.mimemessage;
import org.springframework.boot.autoconfigure.mail.mailproperties;
import org.springframework.mail.javamail.javamailsender;
import org.springframework.mail.javamail.mimemessagehelper;
import java.util.optional;
public class mail {
private javamailsender javamailsender;
private mailproperties mailproperties;
public mail(javamailsender javamailsender, mailproperties mailproperties) {
this.javamailsender = javamailsender;
this.mailproperties = this.mailproperties;
}
public void send(string to, string subject, string content) throws exception {
mimemessage mimemessage = javamailsender.createmimemessage();
mimemessagehelper helper = new mimemessagehelper(mimemessage, false);
//发件人名称
string personal = optional.ofnullable(mailproperties.getproperties().get("personal"))
.orelse(mailproperties.getusername());
helper.setfrom(mailproperties.getusername(), personal);
helper.setto(to); //收件人
helper.setsubject(subject); //邮件主题
helper.settext(content, true);
javamailsender.send(mimemessage);
}
}
2.写spring 邮件配置类,哪个服务需要就写在哪个服务里,也可以提出来写在服务的公共类里
package com.bite.common.config;
import com.bite.common.utils.mail;
import org.springframework.boot.autoconfigure.condition.conditionalonproperty;
import org.springframework.boot.autoconfigure.mail.mailproperties;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.mail.javamail.javamailsender;
@configuration
public class mailconfig {
@bean
@conditionalonproperty(prefix="spring.mail",name="username")
//只有配置文件中存在spring.data.redis.host配置项时,
// 才会把 redis 工具类注册为 bean 放入 spring 容器;
// 没配置该属性就不创建这个 bean,防止未配置 redis 时报错
//如blog服务配置没有redis相关配置,所以该服务就不创建这个bean,而user服务则有这个redis配置,则创建这个bean
public mail mail(javamailsender javamailsender, mailproperties mailproperties) {
return new mail(javamailsender,mailproperties);
}
}
例子展示:
某服务的注册业务(service)代码:
@override
public integer register(userinforegisterrequest registerrequest) {
//校验参数:
checkuserinfo(registerrequest);
//校验通过,才是用户注册,插入数据库
userinfo userinfo = beanconvert.convertuserinfobyencrypt(registerrequest);
try{
int result = userinfomapper.insert(userinfo);
if(result==1){
//存储数据到redis中
//若redis存储失败,会导致查询时查不到信息,那么就从数据库中去查询,所以此处的异常暂不处理
redis.set(buildkey(userinfo.getusername()), jsonutil.tojson(userinfo),expire_time);
//⭐注册成功主动推送用户数据到 rabbitmq,交给消费者异步处理发邮件,不阻塞注册接口响应速度,这就是引入mq的作用
userinfo.setpassword("");
rabbittemplate.convertandsend(constants.user_exchange_name,"",jsonutil.tojson(userinfo));
return userinfo.getid();
}else{
throw new blogexception("用户注册失败");
}
}catch (exception e){
log.error("用户注册失败,e:",e);
throw new blogexception("用户注册失败");
}
}通过这段代码主动推送用户数据到 rabbitmq
(⭐)rabbittemplate.convertandsend(constants.user_exchange_name,"",jsonutil.tojson(userinfo));
生产者
注册成功主动推送用户数据到 rabbitmq,交给消费者异步处理发邮件,不阻塞注册接口响应速度
消费者
消费收到的用户数据并做出下一步操作,如:发送邮箱
package com.bite.user.listener;
import com.bite.common.constant.constants;
import com.bite.common.utils.jsonutil;
import com.bite.common.utils.mail;
import com.bite.user.dataobject.userinfo;
import com.rabbitmq.client.channel;
import lombok.extern.slf4j.slf4j;
import org.springframework.amqp.core.exchangetypes;
import org.springframework.amqp.core.message;
import org.springframework.amqp.rabbit.annotation.exchange;
import org.springframework.amqp.rabbit.annotation.queue;
import org.springframework.amqp.rabbit.annotation.queuebinding;
import org.springframework.amqp.rabbit.annotation.rabbitlistener;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;
import java.io.ioexception;
@slf4j
@component
public class userqueuelistener {
//⭐
@autowired
private mail mail;
//写法二(消费注解内直接声明交换机 / 队列 / 绑定,服务启动自动创建,无需额外配置类;缺点是 mq 资源分散在各个监听类):
@rabbitlistener(bindings=@queuebinding(
value=@queue(value=constants.user_queue_name,durable="true"),
exchange=@exchange(value=constants.user_exchange_name,type= exchangetypes.fanout)
))
public void handler(message message, channel channel) throws ioexception {
long deliverytag=message.getmessageproperties().getdeliverytag();
try{
string body = new string(message.getbody());
log.info("收到用户信息,body:{}",body);
//todo 发送注册成功邮件
userinfo userinfo= jsonutil.parsejson(body, userinfo.class);
//⭐发送邮箱
mail.send(userinfo.getemail(),"恭喜加入xm博客社区",buildcontent(userinfo.getusername()));
//确认
channel.basicack(deliverytag,true);
}catch(exception e){
//否定确认
channel.basicnack(deliverytag,true,true);
log.error("邮件发送失败,e:",e);
}
}
//发送的邮箱内容
private string buildcontent(string username){
stringbuilder builder=new stringbuilder();
builder.append("尊敬的").append(username).append(",您好!").append("<br/>");
builder.append("感谢您注册成为我们博客社区的一员!我们很高兴您加入我们的大家庭!<br/>");
builder.append("您的注册信息如下:用户名: ").append(username).append("<br/>");
builder.append("为了您的账号安全,请妥善保管您的登录信息.如果使用过程中,遇到任何问题,欢迎联系我们的支持团队. xxxx@bxm.com <br/>");
builder.append("再次感谢您的加入,我们期待看到您的精彩内容!<br/>")
.append("最好的祝愿<br/>")
.append("xm博客团队");
return builder.tostring();
}
}
发送邮件前置条件:公共类里的:
①⭐把 mail 工具类创建成spring bean,放进容器:
- 这行代码把
mail工具类创建成spring bean,放进容器; - 自动注入 spring 自带的邮件工具
javamailsender+ 读取 yml 邮箱配置的mailproperties; @conditionalonproperty:只有业务服务 yml 配置了spring.mail.username,才会创建 mail 对象,没配邮箱就不生成,避免报错。
package com.bite.common.config;
import com.bite.common.utils.mail;
import org.springframework.boot.autoconfigure.condition.conditionalonproperty;
import org.springframework.boot.autoconfigure.mail.mailproperties;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.mail.javamail.javamailsender;
@configuration
public class mailconfig {
@bean
@conditionalonproperty(prefix="spring.mail",name="username")
public mail mail(javamailsender javamailsender, mailproperties mailproperties) {
return new mail(javamailsender,mailproperties);
}
}
②:⭐邮箱发送操作实现逻辑:
封装底层发邮件逻辑:创建邮件、设置发件人 / 收件人 / html 正文、调用发送 api。 提供对外暴露的方法:send(string to, string subject, string content)。
package com.bite.common.utils;
import jakarta.mail.internet.mimemessage;
import org.springframework.boot.autoconfigure.mail.mailproperties;
import org.springframework.mail.javamail.javamailsender;
import org.springframework.mail.javamail.mimemessagehelper;
import java.util.optional;
public class mail {
private javamailsender javamailsender;
private mailproperties mailproperties;
public mail(javamailsender javamailsender, mailproperties mailproperties) {
this.javamailsender = javamailsender;
this.mailproperties = mailproperties;
}
public void send(string to, string subject, string content) throws exception {
mimemessage mimemessage = javamailsender.createmimemessage();
mimemessagehelper helper = new mimemessagehelper(mimemessage, false);
//发件人名称
string personal = optional.ofnullable(mailproperties.getproperties().get("personal"))
.orelse(mailproperties.getusername());
helper.setfrom(mailproperties.getusername(), personal);
helper.setto(to); //收件人
helper.setsubject(subject); //邮件主题
helper.settext(content, true);
javamailsender.send(mimemessage);
}
}
三者关系:
- 消费者类写
;
@autowired private mail mail;
- spring 会从容器中找到 mailconfig注册好的 mail bean 注入进来;--②
- 调用
mail.send(邮箱,标题,正文),本质就是执行工具类里封装好的邮件发送代码.--①
以上就是springboot集成邮件服务的完整实现方案的详细内容,更多关于springboot集成邮件服务的资料请关注代码网其它相关文章!
发表评论