当前位置:   article > 正文

Java SpringBoot集成阿里云短信与邮件服务_ com.aliyun

com.aliyun dysmsapi28178525

1.pom.xml导入jar包

  1. <!--阿里云短信 -->
  2. <dependency>
  3. <groupId>com.aliyun</groupId>
  4. <artifactId>aliyun-java-sdk-core</artifactId>
  5. <version>4.1.0</version>
  6. <exclusions>
  7. <exclusion>
  8. <artifactId>commons-codec</artifactId>
  9. <groupId>commons-codec</groupId>
  10. </exclusion>
  11. <exclusion>
  12. <artifactId>activation</artifactId>
  13. <groupId>javax.activation</groupId>
  14. </exclusion>
  15. </exclusions>
  16. </dependency>
  17. <dependency>
  18. <groupId>com.aliyun</groupId>
  19. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  20. <version>1.1.0</version>
  21. </dependency>
  22. <!--阿里云邮件 -->
  23. <dependency>
  24. <groupId>com.aliyun</groupId>
  25. <artifactId>aliyun-java-sdk-dm</artifactId>
  26. <version>3.1.0</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>javax.mail</groupId>
  30. <artifactId>mail</artifactId>
  31. <version>1.4.7</version>
  32. </dependency>

2.推送方法工具类封装

  1. import com.aliyuncs.DefaultAcsClient;
  2. import com.aliyuncs.IAcsClient;
  3. import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
  4. import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
  5. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
  6. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
  7. import com.aliyuncs.exceptions.ClientException;
  8. import com.aliyuncs.http.MethodType;
  9. import com.aliyuncs.profile.DefaultProfile;
  10. import com.aliyuncs.profile.IClientProfile;
  11. import com.jointech.pushserver.constants.AlibabaConstants;
  12. import lombok.extern.slf4j.Slf4j;
  13. import javax.activation.DataHandler;
  14. import javax.activation.FileDataSource;
  15. import javax.mail.*;
  16. import javax.mail.internet.*;
  17. import java.util.Properties;
  18. /**
  19. * 阿里服务方法封装
  20. * @author lenny
  21. */
  22. @Slf4j
  23. public class AlibabaUtil {
  24. /**
  25. * 邮件发送
  26. * @param toAddress 接收邮箱地址
  27. * @param fromAlias 发送邮箱名称
  28. * @param htmlBody 邮箱内容消息体
  29. * @param subject 邮箱主题
  30. * @return
  31. * @throws ClientException
  32. */
  33. public static SingleSendMailResponse sendEmail(String toAddress, String fromAlias, String htmlBody, String subject) {
  34. try {
  35. if (fromAlias == null || fromAlias.length() <= 0) {
  36. fromAlias = AlibabaConstants.ALI_EMAIL_CN_FROM_ALIAS;
  37. }
  38. IClientProfile profile = DefaultProfile.getProfile(AlibabaConstants.ALI_EMAIL_REGION_ID, AlibabaConstants.ALI_EMAIL_ACCESS_KEY_ID, AlibabaConstants.ALI_EMAIL_SECRET);
  39. IAcsClient client = new DefaultAcsClient(profile);
  40. SingleSendMailRequest request = new SingleSendMailRequest();
  41. request.setAccountName(AlibabaConstants.ALI_EMAIL_ACCOUNT_NAME);
  42. request.setFromAlias(fromAlias);
  43. request.setAddressType(1);
  44. request.setToAddress(toAddress);
  45. request.setReplyToAddress(true);
  46. //可以给多个收件人发送邮件,收件人之间用逗号分开
  47. request.setSubject(subject);
  48. //如果采用byte[].toString的方式的话请确保最终转换成utf-8的格式再放入htmlbody和textbody,若编码不一致则会被当成垃圾邮件。
  49. //注意:文本邮件的大小限制为3M,过大的文本会导致连接超时或413错误
  50. request.setHtmlBody(htmlBody);
  51. //若textBody、htmlBody或content的大小不确定,建议采用POST方式提交,避免出现uri is not valid异常
  52. request.setMethod(MethodType.POST);
  53. SingleSendMailResponse sendMailResponse = client.getAcsResponse(request);
  54. log.info("邮件发送失败:给邮箱为{},发送的内容为{},主题为{}", toAddress, htmlBody, subject);
  55. return sendMailResponse;
  56. }catch (Exception e) {
  57. log.error(e.getMessage());
  58. return null;
  59. }
  60. }
  61. /**
  62. * 给指定的手机号发送短信
  63. * @param phone 电话号码
  64. * @param signName 签名
  65. * @param templateCode 模板编码
  66. * @param content 发送内容
  67. * @return
  68. * @throws ClientException
  69. */
  70. public static SendSmsResponse sendSms(String phone, String signName, String templateCode, String content) {
  71. try {
  72. /* 超时时间,可自主调整 */
  73. System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
  74. System.setProperty("sun.net.client.defaultReadTimeout", "10000");
  75. /* 初始化acsClient,暂不支持region化 */
  76. IClientProfile profile = DefaultProfile.getProfile(AlibabaConstants.ALI_SMS_REGION_ID, AlibabaConstants.ALI_SMS_ACCESS_KEY_ID, AlibabaConstants.ALI_SMS_SECRET);
  77. DefaultProfile.addEndpoint(AlibabaConstants.ALI_SMS_REGION_ID, AlibabaConstants.ALI_SMS_PRODUCT, AlibabaConstants.ALI_SMS_DOMAIN);
  78. IAcsClient acsClient = new DefaultAcsClient(profile);
  79. /* 组装请求对象-具体描述见控制台-文档部分内容 */
  80. SendSmsRequest request = new SendSmsRequest();
  81. /* 必填:待发送手机号 */
  82. request.setPhoneNumbers(phone);
  83. /* 必填:短信签名-可在短信控制台中找到 */
  84. request.setSignName(signName);
  85. /* 必填:短信模板code-可在短信控制台中找到 */
  86. request.setTemplateCode(templateCode);
  87. /* 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为 */
  88. request.setTemplateParam(content);
  89. // hint 此处可能会抛出异常,注意catch
  90. SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
  91. if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
  92. log.info("短信发送成功:给号码为{},发送的内容为{}", phone, content);
  93. } else {
  94. log.info("短信发送失败:给号码为{},发送的内容为{}", phone, content);
  95. }
  96. return sendSmsResponse;
  97. }catch (Exception e) {
  98. log.error(e.getMessage());
  99. return null;
  100. }
  101. }
  102. /**
  103. * 发送SMTP邮件,含附件
  104. * @param toAddress
  105. * @param fromAlias
  106. * @param subject
  107. * @param bodyContent
  108. * @param attachPath
  109. * @return
  110. */
  111. public static boolean sendSMTPEmail(String toAddress,String fromAlias,String subject,String bodyContent,String attachPath){
  112. try {
  113. if (fromAlias == null || fromAlias.length() <= 0) {
  114. fromAlias = AlibabaConstants.ALI_EMAIL_CN_FROM_ALIAS;
  115. }
  116. Properties props = System.getProperties();
  117. props.setProperty("mail.smtp.host", AlibabaConstants.ALI_SMTP_HOST);
  118. props.setProperty("mail.smtp.socketFactory.fallback", "false");
  119. props.setProperty("mail.smtp.port", String.valueOf(AlibabaConstants.ALI_SMTP_PORT));
  120. props.setProperty("mail.smtp.socketFactory.port", String.valueOf(AlibabaConstants.ALI_SMTP_SSL_PORT));
  121. props.setProperty("mail.smtp.auth", "true");
  122. //建立邮件会话
  123. Session session = Session.getDefaultInstance(props, new Authenticator() {
  124. //身份认证
  125. @Override
  126. protected PasswordAuthentication getPasswordAuthentication() {
  127. return new PasswordAuthentication(AlibabaConstants.ALI_EMAIL_ACCOUNT_NAME, AlibabaConstants.ALI_SMTP_PASSWORD);
  128. }
  129. });
  130. //建立邮件对象
  131. MimeMessage message = new MimeMessage(session);
  132. //设置邮件的发件人
  133. message.setFrom(new InternetAddress(AlibabaConstants.ALI_EMAIL_ACCOUNT_NAME,fromAlias));
  134. //收件人
  135. message.setRecipients(Message.RecipientType.TO, toAddress);
  136. //主题
  137. message.setSubject(subject);
  138. //内容
  139. Multipart multipart = new MimeMultipart();
  140. //body部分
  141. BodyPart contentPart = new MimeBodyPart();
  142. contentPart.setContent(bodyContent, "text/html;charset=utf-8");
  143. multipart.addBodyPart(contentPart);
  144. //附件部分
  145. BodyPart attachPart = new MimeBodyPart();
  146. FileDataSource fileDataSource = new FileDataSource(attachPath);
  147. attachPart.setDataHandler(new DataHandler(fileDataSource));
  148. attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
  149. multipart.addBodyPart(attachPart);
  150. message.setContent(multipart);
  151. //发送邮件
  152. Transport.send(message);
  153. return true;
  154. } catch (Exception e) {
  155. log.error(e.toString());
  156. return false;
  157. }
  158. }
  159. }

3.常量定义

  1. /**
  2. * 阿里服务常量
  3. * @author lenny
  4. * @date 20210710
  5. */
  6. public class AlibabaConstants {
  7. private AlibabaConstants() {
  8. }
  9. /**
  10. * 阿里邮件发送账户
  11. */
  12. public static final String ALI_EMAIL_ACCOUNT_NAME = "xxxxx.xxxxxx.com";
  13. /**
  14. * 阿里邮件发送人名称
  15. */
  16. public static final String ALI_EMAIL_CN_FROM_ALIAS="xxx";
  17. /**
  18. * 阿里邮件发送人名称
  19. */
  20. public static final String ALI_EMAIL_EN_FROM_ALIAS = "xxx";
  21. /**
  22. *阿里邮件地区标识
  23. */
  24. public static final String ALI_EMAIL_REGION_ID = "cn-hangzhou";
  25. /**
  26. * 阿里邮件验证账户
  27. */
  28. public static final String ALI_EMAIL_ACCESS_KEY_ID = "xxx";
  29. /**
  30. *阿里邮件密钥
  31. */
  32. public static final String ALI_EMAIL_SECRET = "xxx";
  33. /**
  34. * 阿里邮件主题(中文)
  35. */
  36. public static final String ALI_EMAIL_CN_SUBJECT="【邮件提醒】";
  37. /**
  38. * 阿里邮件主题(英文)
  39. */
  40. public static final String ALI_EMAIL_EN_SUBJECT="[Email reminder]";
  41. /**
  42. * 阿里短信API产品名称
  43. */
  44. public static final String ALI_SMS_PRODUCT = "Dysmsapi";
  45. /**
  46. * 阿里短信API产品域名
  47. */
  48. public static final String ALI_SMS_DOMAIN = "dysmsapi.aliyuncs.com";
  49. /**
  50. * 阿里短信地区标识
  51. */
  52. public static final String ALI_SMS_REGION_ID = "cn-hangzhou";
  53. /**
  54. * 阿里短信验证账户
  55. */
  56. public static final String ALI_SMS_ACCESS_KEY_ID = "xxx";
  57. /**
  58. * 阿里短信密钥
  59. */
  60. public static final String ALI_SMS_SECRET = "xxxxxx";
  61. /**
  62. * 阿里短信签名(中文)
  63. */
  64. public static final String ALI_SMS_CN_SIGN_NAME="xxx";
  65. /**
  66. * 阿里短信签名(英文)
  67. */
  68. public static final String ALI_SMS_EN_SIGN_NAME="xxx";
  69. /**
  70. * 阿里短信模板(中文)
  71. */
  72. public static final String ALI_SMS_CN_MESSAGE_TEMPLATE="SMS_xxxxxx";
  73. /**
  74. * 阿里短信模板(英文)
  75. */
  76. public static final String ALI_SMS_EN_MESSAGE_TEMPLATE="SMS_xxxxxx";
  77. /**
  78. * 阿里短信模板(推送微信服务号订阅信息)
  79. */
  80. public static final String ALI_SMS_CN_SUBSCRIPTION_TEMPLATE="SMS_xxxxx";
  81. /**
  82. * 阿里SMTP邮件域名
  83. */
  84. public static final String ALI_SMTP_HOST = "smtpdm.aliyun.com";
  85. /**
  86. * 阿里SMTP邮件端口
  87. */
  88. public static final int ALI_SMTP_PORT = 80;
  89. /**
  90. * 阿里SMTP邮件SSL端口
  91. */
  92. public static final int ALI_SMTP_SSL_PORT = 465;
  93. /**
  94. * 阿里SMTP邮件用户名
  95. */
  96. public static final String ALI_SMTP_USER = "xxxx";
  97. /**
  98. * 阿里SMTP邮件密码
  99. */
  100. public static final String ALI_SMTP_PASSWORD = "xxxxxxx";
  101. /**
  102. * SMTP邮件内容(中文)
  103. */
  104. public static final String ALI_SMTP_CN_CONTENT="报告已送达,请查阅附件!";
  105. /**
  106. * SMTP邮件内容(英文)
  107. */
  108. public static final String ALI_SMTP_EN_CONTENT="The report has been delivered, please refer to the attachment!";
  109. }

4.方法调用

在调用的时候直接使用

  1. /**
  2. * 发送邮件
  3. * @param toAddress 接收人邮件地址
  4. * @param fromAlias 发送邮箱名称
  5. * @param htmlBody 消息体内容(用html格式发送效果更好)
  6. * @param subject 主题名称
  7. */
  8. AlibabaUtil.sendEmail(toAddress,fromAlias,htmlBody,subject);
  9. /**
  10. * 发送短信
  11. * @param phone 接收人手机号
  12. * @param signName 短信签名
  13. * @param templateCode 短信模板
  14. * @param content 符合模板的短信内容参数
  15. */
  16. AlibabaUtil.sendSms(phone,signName,templateCode,content);
  17. /**
  18. * smtp发送带附件的邮件
  19. * @param toAddress 接收人邮件地址
  20. * @param fromAlias 发送邮箱名称
  21. * @param subject 主题名称
  22. * @param bodyContent 邮件内容
  23. * @param filePath 邮件附件地址
  24. */
  25. AlibabaUtil.sendSMTPEmail(toAddress, fromAlias, subject, bodyContent, filePath);

5.效果截图

短信报警:

 普通邮件报警:

SMTP附件邮件

 

 

 

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/201236
推荐阅读
相关标签