springboot 集成短信和邮件的配置示例详解-亚博电竞手机版
目录
- 依赖
- 配置
- 编码
- 1、邮件
- 2、短信
准备工作
1、集成邮件
以qq邮箱为例
在发送邮件之前,要开启pop3和smtp协议,需要获得邮件服务器的授权码,获取授权码:
1、设置>账户
在账户的下面有一个开启smtp协议的开关并进行密码验证:
2、获取成功的授权码
2、集成短信
以阿里云短信服务为例
1、登陆阿里云—>进入控制台—>开通短信服务
进入后根据提示开通短信服务即可。
2、充值
后期发短信测试需要,暂时可以跳过此步骤。
3、获取accesskey和accesssercet
文档使用指引: https://help.aliyun.com/document_detail/59210.html?spm=a2c6h.13066369.0.0.4b3516b4kn0052
4、api
openapi地址: https://next.api.aliyun.com/document/dysmsapi/2017-05-25/overview
依赖
1、邮件
2、短信
配置
1、配置邮箱基本信息
spring: mail: # 配置 smtp 服务器地址 host: smtp.qq.com # 发送者邮箱 username: 742354529@qq.com # 配置密码,注意不是真正的密码,而是申请的授权码 password: vjstfghblprwbdbd # 端口号465或587 port: 587 # 默认的邮件编码为utf-8 default-encoding: utf-8 # 配置ssl 加密工厂 properties: mail: smtp: socketfactoryclass: javax.net.ssl.sslsocketfactory # 表示开启debug模式,邮件发送过程的日志会在控制台打印出来 debug: true
smtp 服务器地址
- 126邮箱smtp服务器地址:smtp.126.com,端口号:465或者994
- 2163邮箱smtp服务器地址:smtp.163.com,端口号:465或者994
- yeah邮箱smtp服务器地址:smtp.yeah.net,端口号:465或者994
- qq邮箱smtp服务器地址:smtp.qq.com,端口号465或587*
2、短信配置
# 阿里云短信配置 sms: access-id: ltai5tdp3sdqc9yvcguiifdr access-key: egsdqslxcvs5dwjs8dcxmyq124xysv sign-name: endpoint: dysmsapi.aliyuncs.com
编码
1、邮件
1.1、mailservice.java
package com.tanersci.service; import com.tanersci.dto.mailmessagedto; import com.tanersci.vo.messagevo; /** * @classname: mailservice.java * @classpath: com.tanersci.service.mailservice.java * @description: 邮件 * @author: tanyp * @date: 2021/6/7 9:18 **/ public interface mailservice { /** * @monthname: sendsimple * @description: 普通邮件发送 * @author: tanyp * @date: 2021/6/7 9:30 * @param: [dto] * @return: void **/ messagevo sendsimple(mailmessagedto dto); * @monthname: sendattachfile * @description: 带附件的邮件 messagevo sendattachfile(mailmessagedto dto); * @monthname: sendimgres * @description: 带图片资源的邮件 messagevo sendimgres(mailmessagedto dto); }
1.2、mailserviceimpl.java
package com.tanersci.service.impl; import com.alibaba.fastjson.json; import com.tanersci.dto.mailmessagedto; import com.tanersci.vo.messagevo; import com.tanersci.constant.constants; import com.tanersci.service.mailservice; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.annotation.value; import org.springframework.core.io.filesystemresource; import org.springframework.mail.mailexception; import org.springframework.mail.simplemailmessage; 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.time.localdatetime; import java.util.date; import java.util.objects; /** * @classname: mailserviceimpl.java * @classpath: com.tanersci.service.impl.mailserviceimpl.java * @description: 邮件 * @author: tanyp * @date: 2021/6/7 9:18 **/ @slf4j @service public class mailserviceimpl implements mailservice { @value("${spring.mail.username}") private string sender; @autowired private javamailsender javamailsender; /** * @monthname: sendsimple * @description: 普通邮件发送 * @author: tanyp * @date: 2021/6/7 9:30 * @param: [dto] * @return: void **/ @override public messagevo sendsimple(mailmessagedto dto) { try { log.info("=======普通邮件发送开始,请求参数:{}", json.tojson(dto)); // 构建一个邮件对象 simplemailmessage message = new simplemailmessage(); // 设置邮件主题 message.setsubject(dto.getsubject()); // 设置邮件发送者,这个跟application.yml中设置的要一致 message.setfrom(sender); // 设置邮件接收者,可以有多个接收者,中间用逗号隔开,以下类似 // message.setto("10*****16@qq.com","12****32*qq.com"); message.setto(dto.getrecipient()); // 设置邮件抄送人,可以有多个抄送人 if (objects.nonnull(dto.getcc())) { message.setcc(dto.getcc()); } // 设置隐秘抄送人,可以有多个 if (objects.nonnull(dto.getbcc())) { message.setbcc(dto.getbcc()); // 设置邮件发送日期 message.setsentdate(new date()); // 设置邮件的正文 message.settext(dto.gettext()); // 发送邮件 javamailsender.send(message); log.info("=======普通邮件发送结束"); return messagevo.builder().code(constants.news_success_code).message(constants.news_success_message).build(); } catch (mailexception e) { log.error("====邮件====sendsimple=====异常:{}", e); return messagevo.builder().code(constants.news_fail_code).message(constants.news_fail_message).build(); } } * @monthname: sendattachfile * @description: 带附件的邮件 public messagevo sendattachfile(mailmessagedto dto) { log.info("=======带附件的邮件开始,请求参数:{}", json.tojson(dto)); mimemessage mimemessage = javamailsender.createmimemessage(); // true表示构建一个可以带附件的邮件对象 mimemessagehelper message = new mimemessagehelper(mimemessage, true); // 第一个参数是自定义的名称,后缀需要加上,第二个参数是文件的位置 dto.getattachments().foreach(file -> { try { message.addattachment(file.getname(), file); } catch (messagingexception e) { log.error("=========邮件附件解析异常:{}", e); } }); javamailsender.send(mimemessage); log.info("=======带附件的邮件结束"); } catch (messagingexception e) { log.error("==========邮件====sendattachfile=====异常:{}", e); * @monthname: sendimgres * @description: 带图片资源的邮件 public messagevo sendimgres(mwww.cppcns.comailmessagedto dto) { log.info("=======带图片资源的邮件开始,请求参数:{}", json.tojson(dto)); // 第一个参数指的是html中占位符的名字,第二个参数就是文件的位置 message.addinline(file.getname(), new filesystemresource(file)); log.error("=========邮件图片解析异常:{}", e); log.info("=======带图片资源的邮件结束"); log.error("====邮件====sendimgres=====异常:{}", e); }
1.3、vo、dto及常量类
mailmessagedto.java
package com.tanersci.dto; import io.swagger.annotations.apimodel; import io.swagger.annotations.apimodelproperty; import lombok.allargsconstructor; import lombok.builder; import lombok.data; import lombok.noargsconstructor; import java.io.file; import java.io.serializable; import java.util.list; /** * @classname: mailmessagedto.java * @classpath: com.tanersci.dto.mailmessagedto.java * @description: 邮件消息 * @author: tanyp * @date: 2021/6/7 9:20 **/ @data @allargsconstructor @noargsconstructor @builder @apimodel(value = "邮件消息") public class mailmessagedto implements serializable { private static final long serialversionuid = 5483400172436286831l; @apimodelproperty(value = "邮件主题") private string subject; @apimodelproperty(value = "接收者:可以有多个接收者,中间用逗号隔开") private string recipient; @apimodelproperty(value = "抄送人:可以有多个抄送人,中间用逗号隔开") private string cc; @apimodelproperty(value = "隐秘抄送人:可以有多个抄送人,中间用逗号隔开") private string bcc; @apimodelproperty(value = "正文") private string text; @apimodelproperty(value = "模板编码") private string code; @apimodelproperty(value = "附件、图片") private list
messagevo.java
pack恰卡编程网age com.tanersci.vo; import io.swagger.annotations.apimodel; import io.swagger.annotations.apimodelproperty; import lombok.allargsconstructor; import lombok.builder; import lombok.data; import lombok.noargsconstructor; import java.io.serializable; /** * @classname: messagevo.java * @classpath: com.tanersci.vo.messagevo.java * @description: 短信、邮件消息返回值 * @author: tanyp * @date: 2021/6/7 11:35 **/ @data @allargsconstructor @noargsconstructor @builder @apimodel(value = "短信、邮件消息返回值") public class messagevo implements serializable { private static final long serialversionuid = 5287525465339500144l; @apimodelproperty(value = "状态码") private string code; @apimodelproperty(value = "状态码的描述") private string message; @apimodelproperty(value = "请求id") private string requestid; @apimodelproperty(value = "发送回执id") private string bizid; @apimodelproperty(value = "模板编码") private string templatecode; }
constants.java
package com.tanersci.constant; /** * @classname: constants.java * @classpath: com.tanersci.constant.constants.java * @description: 常量 * @author: tanyp * @date: 2021/5/22 15:54 **/ public class constants { /** * 消息发送状态码 */ public final static string news_success_code = "ok"; public final static string news_success_message = "发送成功"; public final static string news_fail_code = "fail"; public final static string news_fail_message = "发送失败"; }
2、短信
2.1、smsservice.java
package com.tanersci.service; import com.tanersci.dto.smsmessagedto; import com.tanersci.dto.smstemplatedto; import com.tanersci.vo.messagevo; /** * @classname: smsservice.java * @classpath: com.tanersci.service.smsservice.java * @description: 短信 * @author: tanyp * @date: 2021/6/7 10:56 **/ public interface smsservice { /** * @monthname: send * @description: 发短信 * @author: tanyp * @date: 2021/6/7 14:50 * @param: [dto] * @return: com.tanersci.vo.messagevo **/ messagevo send(smsmessagedto dto); * @monthname: addsmstemplate * @description: 申请短信模板 * @param: [template] messagevo addsmstemplate(smstemplatedto template); * @monthname: deletesmstemplate * @description: 删除短信模板 messagevo deletesmstemplate(smstemplatedto template); * @monthname: modifysmwww.cppcns.comstemplate * @description: 修改未通过审核的短信模板 messagevo modifysmstemplate(smstemplatedto template); * @monthname: querysmstemplate * @description: 查询短信模板的审核状态 messagevo querysmstemplate(smstemplatedto template); }
2.2、smsserviceimpl.java
package com.tanersci.service.impl; import com.alibaba.fastjson.json; import com.aliyun.dysmsapi20170525.client; import com.aliyun.dysmsapi20170525.models.*; import com.aliyun.teaopenapi.models.config; import com.tanersci.dto.smsmessagedto; import com.tanersci.dto.smstemplatedto; import com.tanersci.vo.messagevo; import com.tanersci.config.smsconfig; import com.tanersci.constant.constants; import com.tanersci.service.smsservice; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import java.time.localdatetime; import java.util.objects; import java.util.uuid; /** * @classname: smsserviceimpl.java * @classpath: com.tanersci.service.impl.smsserviceimpl.java * @description: 短信 * @author: tanyp * @date: 2021/6/7 10:57 **/ @slf4j @service public class smsserviceimpl implements smsservice { @autowired private smsconfig smsconfig; /** * @monthname: createclient * @description: sk初始化账号client * @author: tanyp * @date: 2021/6/7 15:44 * @param: [accessid, accesskey, endpoint] * @return: com.aliyun.teaopenapi.client **/ public client createclient() throws exception { config config = new config(); config.accesskeyid = smsconfig.getaccessid(); config.accesskeysecret = smsconfig.getaccesskey(); config.endpoint = smsconfig.getendpoint(); return new client(config); } * @monthname: send * @description: 发短信 * @date: 2021/6/7 14:50 * @param: [dto] * @return: com.tanersci.vo.messagevo @override public messagevo send(smsmessagedto dto) { try { log.info("======发送短信开始,请求参数:{}", json.tojson(dto)); client client = createclient(); // 组装请求对象 sendsmsrequest request = new sendsmsrequest(); // 外部流水扩展字段 string outid = uuid.randomuuid().tostring(); request.setoutid(outid); // 支持对多个手机号码发送短信,手机号码之间以英文逗号(,)分隔。上限为1000个手机号码。批量调用相对于单条调用及时性稍有延迟。 request.setphonenumbers(dto.getphone()); // 短信签名名称 request.setsignname(smsconfig.getsignname()); // 短信模板id request.settemplatecode(dto.gettemplatecode()); // 短信模板变量对应的实际值,json格式。如果json中需要带换行符,请参照标准的json协议处理。 request.settemplateparam(json.tojsonstring(dto.getparam())); // 发送短信 sendsmsresponse res = client.sendsms(request); messagevo message = messagevo.builder().build(); if (objects.equals(constants.news_success_code, res.body.getcode())) { log.info("======发送短信成功,返回值:{}www.cppcns.com", json.tojson(res.body)); message.setcode(constants.news_success_code); message.setmessage(constants.news_success_message); } else { log.info("======发送短信失败,返回值:{}", json.tojson(res.body)); message.setcode(constants.news_fail_code); message.setmessage(constants.news_fail_message); } return message; } catch (exception e) { log.error("======发送短信异常:{}", e.getmessage()); e.printstacktrace(); return messagevo.builder().code(constants.news_fail_code).message(constants.news_fail_message).build(); } * @monthname: addsmstemplate * @description: 申请短信模板 * @param: [template] public messagevo addsmstemplate(smstemplatedto template) { log.info("======申请短信模板,请求参数:{}", json.tojson(template)); addsmstemplaterequest request = new addsmstemplaterequest(); request.settemplatetype(template.gettemplatetype()); request.settemplatename(template.gettemplatename()); request.settemplatecontent(template.gettemplatecontent()); request.setremark(template.getremark()); addsmstemplateresponse res = client.addsmstemplate(request); if (objects.equals(teamconstants.news_success_code, res.body.getcode())) { log.info("======申请短信模板,返回值:{}", json.tojson(res.body)); return messagevo.builder() .code(constants.news_success_code) .message(constants.news_success_message) .templatecode(res.getbody().templatecode) .build(); return messagevo.builder().code(constants.news_fail_code).message(constants.news_fail_message).build(); log.error("======申请短信模板,异常:{}", e.getmessage()); * @monthname: deletesmstemplate * @description: 删除短信模板 public messagevo deletesmstemplate(smstemplatedto template) { log.info("======删除短信模板,请求参数:{}", json.tojson(template)); deletesmstemplaterequest request = new deletesmstemplaterequest(); request.settemplatecode(template.gettemplatecode()); deletesmstemplateresponse res = client.deletesmstemplate(request); log.info("======删除短信模板,返回值:{}", json.tojson(res.body)); return messagevo.builder().code(constants.news_success_code).message(constants.news_success_message).build(); log.error("======删除短信模板,异常:{}", e); * @monthname: modifysmstemplate * @description: 修改未通过审核的短信模板 public messagevo modifysmstemplate(smstemplatedto template) { log.info("======修改未通过审核的短信模板,请求参数:{}", json.tojson(template)); modifysmstemplaterequest request = new modifysmstemplaterequest(); modifysmstemplateresponse res = client.modifysmstemplate(request); log.info("======修改未通过审核的短信模板,返回值:{}", json.tojson(res.body)); log.error("======修改未通过审核的短信模板,异常:{}", e.getmessage()); * @monthname: querysmstemplate * @description: 查询短信模板的审核状态 public messagevo querysmstemplate(smstemplatedto template) { log.info("======查询短信模板的审核状态,请求参数:{}", json.tojson(template)); querysmstemplaterequest request = new querysmstemplaterequest(); querysmstemplateresponse res = client.querysmstemplate(request); log.info("======查询短信模板的审核状态,返回值:{}", json.tojson(res.body)); log.error("======查询短信模板的审核状态,异常:{}", e.getmessage()); }
2.3、smsconfig.java
package com.tanersci.config; import lombok.data; import org.springframework.beans.factory.annotation.value; import org.springframework.boot.context.properties.configurationproperties; import org.springframework.context.annotation.configuration; import org.springframework.stereotype.component; /** * @classname: smsconfig.java * @classpath: com.tanersci.config.smsconfig.java * @description: 短信配置 * @author: tanyp * @date: 2021/6/7 16:41 **/ @data @component public class smsconfig { @value("${sms.access-id}") private string accessid; @value("${sms.access-key}") private string accesskey; @value("${sms.sign-name}") private string signname; @value("${sms.endpoint}") private string endpoint; }
2.4、vo、dto类
messagevo 同用邮件的
mailmessagedto.java
package com.tanersci.dto; import io.swagger.annotations.apimodel; import io.swagger.annotations.apimodelproperty; import lombok.allargsconstructor; import lombok.builder; import lombok.data; import lombok.noargsconstructor; import java.io.serializable; /** * @classname: mailmessagedto.java * @classpath: com.tanersci.dto.smsmessagedto.java * @description: 短信 * @author: tanyp * @date: 2021/6/7 9:20 **/ @data @allargsconstructor @noargsconstructor @builder @apimodel(value = "短信消息") public class smsmessagedto implements serializable { private static final long serialversionuid = 3427970548460798908l; @apimodelproperty(value = "手机号,多个以逗号隔开") private string phone; @apimodelproperty(value = "模板编码") private string templatecode; @apimodelproperty(value = "模板参数") private templateparamdto param; private string code; }
smstemplate.java
package com.tanersci.dto; import lombok.allargsconstructor; import lombok.builder; import lombok.data; import lombok.noargsconstructor; import java.io.serializable; /** * @classname: smstemplate.java * @classpath: com.tanersci.dto.smstemplatedto.java * @description: 短信模板 * @author: tanyp * @date: 2021/6/7 15:02 **/ @data @allargsconstructor @noargsconstructor @builder public class smstemplatedto implements serializable { private static final long serialversionuid = -8909531614461840038l; /** * 模板类型:0:验证码,1:短信通知,2:推广短信,3:国际/港澳台消息。 */ private integer templatetype; * 模板名称,长度为1~30个字符 private string templatename; * 模板内容,长度为1~500个字符 private string templatecontent; * 短信模板code private string templatecode; * 短信模板申请说明。请在申请说明中描述您的业务使用场景,长度为1~100个字符 private string remark; }
注意
项目中使用lombok插件和swagger依赖,无相关依赖的请自行修改。
到此这篇关于springboot集成短信和邮件的文章就介绍到这了,更多相关springboot集成短信和邮件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!