SpringBoot uses Alibaba Cloud email service to realize account sharing

1. Alibaba Cloud email integration

For details, see:Java SpringBoot integrates Alibaba Cloud SMS and email services_Alibaba Cloud SMS jar package_Big Fish>'s blog-CSDN blog

2. Use Html template to implement email content style

2.1.Introduce pom

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

2.2.Create html template

Create a template folder template under resources

Add the introduction of the contents of the template folder under the spring node of the configuration file yml

  thymeleaf:
    prefix: classpath:/template/

 Create an html file in the template folder, such as Cn_UserShare.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>账户分享</title>
</head>
<body>
<p>尊敬的用户:<span th:text="${userName}"></span></p>
<p> 您收到一个账户的分享,分享链接为:</p>
<a th:href = "${url}">点击登录</a>
<br>
<p> 访问地址:<span th:text="${url}"></span></p>
<p> 到期时间:<span th:text="${expireTime}"></span></p>
<p> 请使用:Chrome、Edge、Safari、Firefox等浏览器</p>
<br>
如有疑问,请致电24小时客服热线 +86 139xxxxxxxx
</body>
</html>

Among them: ${userName}, "${url}", "${expireTime}" are the contents that need to be dynamically replaced.

 2.3. Dynamically replace html content

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * 账户分享服务
 * @author Mr.Lee
 * @date 20230222
 */
@Service
@Slf4j
public class UserShareService {
    @Value("${gnss.share.url}")
    private String baseUrl;
    @Autowired
    private UserShareDao userShareDao;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TemplateEngine templateEngine;
    
    /**
     * 添加分享记录
     * @param userShare
     * @return
     */
    public String addUserShare(UserShare userShare){
        String id= CommonUtils.getUUID();
        String url=String.format("%s?id=%s&userId=%s&language=%s",baseUrl,id,userShare.getUserId(),userShare.getLanguage());
        userShare.setId(id);
        userShare.setUrl(url);
        userShare.setCreatorId(tokenService.getTokenInfo().getUserId());
        //后续对接邮件推送
        if(StringUtils.isNotBlank(userShare.getEmail())&&CommonUtils.checkEmailAddress(userShare.getEmail())){
            String subject = "";
            if (userShare.getLanguage() ==1) {
                subject = "账户分享";
            } else {
                subject = "Account sharing";
            }
            Context context = new Context();
            // 设置模板中的变量
            context.setVariable("userName", userShare.getShareUser());
            context.setVariable("url",url);
            context.setVariable("expireTime",userShare.getExpireTime());
            // 第一个参数为模板的名称
            String htmlBody;
            if(userShare.getLanguage() ==1) {
                htmlBody = templateEngine.process("Cn_UserShare.html", context);
            }else{
                htmlBody = templateEngine.process("En_UserShare.html", context);
            }
            AliPushUtils.sendEmail(userShare.getEmail(),"",htmlBody,subject);
        }
        int status = userShareDao.addUserShare(userShare);
        if(status>0){
            return url;
        }else{
            return null;
        }
    }
}

2.4. Alibaba Cloud email delivery method

    /**
     * 发送HTML格式邮件
     * @param toAddress
     * @param fromAlias
     * @param htmlBody
     * @param subject
     * @return
     */
    public static SingleSendMailResponse sendEmail(String toAddress, String fromAlias, String htmlBody, String subject) {
        try {
            if (fromAlias == null || fromAlias.length() <= 0) {
                fromAlias = AliPushConstants.ALI_EMAIL_CN_FROM_ALIAS;
            }
            IClientProfile profile = DefaultProfile.getProfile(AliPushConstants.ALI_EMAIL_REGION_ID, AliPushConstants.ALI_EMAIL_ACCESS_KEY_ID, AliPushConstants.ALI_EMAIL_SECRET);
            IAcsClient client = new DefaultAcsClient(profile);
            SingleSendMailRequest request = new SingleSendMailRequest();
            request.setAccountName(AliPushConstants.ALI_EMAIL_ACCOUNT_NAME);
            request.setFromAlias(fromAlias);
            request.setAddressType(1);
            request.setToAddress(toAddress);
            request.setReplyToAddress(true);
            //可以给多个收件人发送邮件,收件人之间用逗号分开
            request.setSubject(subject);
            //如果采用byte[].toString的方式的话请确保最终转换成utf-8的格式再放入htmlbody和textbody,若编码不一致则会被当成垃圾邮件。
            //注意:文本邮件的大小限制为3M,过大的文本会导致连接超时或413错误
            request.setHtmlBody(htmlBody);
            //若textBody、htmlBody或content的大小不确定,建议采用POST方式提交,避免出现uri is not valid异常
            request.setMethod(MethodType.POST);
            SingleSendMailResponse sendMailResponse = client.getAcsResponse(request);
            log.info("邮件发送失败:给邮箱为{},发送的内容为{},主题为{}", toAddress, htmlBody, subject);
            return sendMailResponse;
        }catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

 3.Finally achieve the effect

 

Guess you like

Origin blog.csdn.net/qq_17486399/article/details/129929544