下面我将详细讲解“SpringBoot 集成短信和邮件的配置示例详解”的完整攻略。
1. 集成短信
1.1. 添加依赖
在 pom.xml
中添加阿里云短信 SDK 的依赖:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
1.2. 配置参数
在 application.yml
文件中添加阿里云短信相关的配置参数:
aliyun:
access-key-id: # 阿里云 AccessKeyId
access-key-secret: # 阿里云 AccessKeySecret
sms:
sign-name: # 签名名称
template-code: # 短信模板编号
1.3. 编写代码
@Service
public class SmsService {
@Autowired
private AliyunSmsProperties aliyunSmsProperties;
@Autowired
private IAcsClient acsClient;
public void send(String phone, Map<String, String> templateParam) throws ClientException {
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain(aliyunSmsProperties.getDomain());
request.setVersion(aliyunSmsProperties.getVersion());
request.setAction(aliyunSmsProperties.getAction());
// 设置手机号码和签名名称
request.putQueryParameter("PhoneNumbers", phone);
request.putQueryParameter("SignName", aliyunSmsProperties.getSignName());
// 设置模板编号和模板参数
request.putQueryParameter("TemplateCode", aliyunSmsProperties.getTemplateCode());
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(templateParam));
CommonResponse response = acsClient.getCommonResponse(request);
JSONObject jsonObject = JSONObject.parseObject(response.getData());
if (!"OK".equals(jsonObject.getString("Code"))) {
throw new RuntimeException("短信发送失败");
}
}
}
2. 集成邮件
2.1. 添加依赖
在 pom.xml
中添加邮件相关的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.2. 配置参数
在 application.yml
文件中添加邮件相关的配置参数:
spring:
mail:
host: # SMTP 主机名或 IP 地址
port: # SMTP 端口号
username: # 邮箱账户
password: # 邮箱密码
protocol: smtp
default-encoding: UTF-8
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.starttls.required: true
mail.smtp.ssl.protocols: TLSv1.2
2.3. 编写代码
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void send(String[] to, String subject, String text) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(javaMailSender.getUsername());
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(text, true);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
throw new RuntimeException("邮件发送失败", e);
}
}
}
以上就是 SpringBoot 集成短信和邮件的详细攻略,希望对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot 集成短信和邮件的配置示例详解 - Python技术站