SpringCloud mail tool class

Introduction

The mail tools used by SpringCloud are the same as those in Springboot, and can be spring-boot-starter-mailimplemented using starter dependencies. This article will provide two mail tool methods, namely the method of sending with a single attachment and the method of sending with multiple attachments, the two are only different in the parameters. This article will also introduce the problems and solutions encountered in actual use.

1. Add Maven dependencies

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

2. Add mail configuration in the configuration file Properties.xml

The configuration file needs to modify the first three lines of configuration. You need to specify an email account and password to send emails. This account can be a QQ mailbox or a Netease mailbox, either.

Depending on the selected mailbox, the host attribute value may also be different. This place needs to be debugged. If the first time seems to be successful, just fill in the QQ mailbox account password below. I have given the host, and when you run the program, Come to test or replace it with your company's official email address.

spring.mail.host=smtp.exmail.qq.com
spring.mail.username=填写你的邮箱账号(格式:[email protected]
spring.mail.password=填写你的邮箱密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# 连接时间限制(毫秒)
spring.mail.mail.smtp.connectiontimeout=10000
# 发送时间限制(毫秒)
spring.mail.mail.smtp.writetimeout=5000
# 本地不配置端口,默认端口25也可以发送,上线若连接失败,改下端口
#spring.mail.port=465
#spring.mail.properties.mail.smtp.socketFactory.port=465

3. Mailbox tool class (EmailUtils.java)

There are two methods provided here, just change the package name to use.


package com.blog.commons.mail;
import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.ObjectUtils;

import com.blog.commons.bean;

import lombok.extern.slf4j.Slf4j;

/**
 * @project commons-util
 * @description: 电子邮件工具类
 * @author 大脑补丁
 * @create 2020-03-17 20:32
 */
@Slf4j
public class EmailUtils {

    /**
     * 发送带有单个附件的邮件
     * 
     * @param mailSender
     *            邮件工具实例 (客户端通过 @Autowired JavaMailSender javaMailSender 注入即可使用)
     * 
     * @param fromEmail
     *            发件人邮箱地址(格式:[email protected]
     * @param toEmail
     *            收件人邮箱地址(格式:[email protected]
     * @param subject
     *            主题
     * @param content
     *            正文
     * @param attachment
     *            附件(若为null则不添加附件)
     * @return 0:失败,1:成功
     * 
     * @author 大脑补丁 on 2020-03-17 22:25
     */
    public static Integer sendMailAttachment(JavaMailSender mailSender, String fromEmail, String toEmail,
        String subject, String content, Attachment attachment) {
        // 附件名完整显示
        System.setProperty("mail.mime.splitlongparameters", "false");
        MimeMessage message = mailSender.createMimeMessage();
        // 1:成功;0:失败
        Integer result = 1;
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (!ObjectUtils.isEmpty(attachment) && !ObjectUtils.isEmpty(attachment.getFileName())
                && !ObjectUtils.isEmpty(attachment.getFilePath())) {
                try {
                    FileSystemResource file = new FileSystemResource(attachment.getFilePath());
                    // helper.addAttachment(attachment.getFileName(), file);
                    // 附件中文名编码,B:Base64编码格式
                    helper.addAttachment(MimeUtility.encodeWord(attachment.getFileName(), "UTF-8", "B"), file);
                } catch (Exception e) {
                    // 如果存在附件,但添加附件时出错,则标记邮件发送结果为失败
                    result = 0;
                    e.printStackTrace();
                }
            }
            if (result == 1) {
                // 若存在附件且附件添加成功时才发送;若不存在附件,则直接发送
                mailSender.send(message);
            }
            log.info("邮件发送成功,收件人地址:" + toEmail);
            return result;
        } catch (Exception e) {
            log.error("邮件发送出现异常,收件人地址:" + toEmail, e);
        }
        return result;
    }

    /**
     * 发送带有多个附件的邮件
     * 
     * @param mailSender
     *            邮件工具实例 (客户端通过 @Autowired JavaMailSender javaMailSender 注入即可使用)
     * 
     * @param fromEmail
     *            发件人邮箱地址(格式:[email protected]
     * @param toEmail
     *            收件人邮箱地址(格式:[email protected]
     * @param subject
     *            主题
     * @param content
     *            正文
     * @param List<Attachment>
     *            多个附件列表
     * @return 0:失败,1:成功
     * @author 大脑补丁 on 2020-03-17 22:16
     */
    public static Integer sendMailAttachments(JavaMailSender mailSender, String fromEmail, String toEmail,
        String subject, String content, List<Attachment> attachments) {
        System.setProperty("mail.mime.splitlongparameters", "false");
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (!ObjectUtils.isEmpty(attachments)) {
                attachments.forEach((attachment) -> {
                    try {
                        // 加载文件资源,作为附件
                        FileSystemResource file = new FileSystemResource(attachment.getFilePath());
                        // 添加附件
                        helper.addAttachment(MimeUtility.encodeWord(attachment.getFileName(), "UTF-8", "B"), file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            mailSender.send(message);
            log.info("邮件发送成功,收件人地址:" + toEmail);
            return 1;
        } catch (Exception e) {
            log.error("邮件发送出现异常,收件人地址:" + toEmail, e);
        }
        return 0;
    }
}

4. Mail object class (Attachment.java)

  • The above tool class uses an attachment object. The object has two properties, one is the attachment name and the other is the file path.
  • The attachment name is the filename in the email attachment, not the local filename. Note that the file path should pass the full path, such as: C:\temp\文档.txt, because the file needs to be read through the file stream, the path cannot only be written to the folder.
  • The following entity class uses lombok.jar. If you do not use this plugin, delete the three annotations on the class name below and add the Getter\Setter method by yourself.
package com.blog.commons.bean;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @project commons-util
 * @description: 邮件附件
 * @author 大脑补丁
 * @create 2020-03-17 22:37
 */
@Data
@Accessors(chain = true)
@RequiredArgsConstructor(staticName = "of")
public class Attachment {
    /** 文件名称 */
    private String fileName;
    /** 文件路径 */
    private String filePath;
}

5. How to use

  1. In the class that needs to send mail @Autowired, inject the mail object via JavaMailSender.
  2. In the class that needs to send emails, by @Value("${spring.mail.username}")injecting into the configuration file, your email address. (Why not write the mailbox? Because the mailbox account of each service module of the SpringCloud microservice is different, such as the mailbox with orders for orders, and the mailboxes for advertisements with advertisements. It is impossible to use only one mailbox account to send emails with all functions, otherwise it is very easy It is automatically blacklisted by the email client, and the files received by the user go directly to the trash)
@Value("${spring.mail.username}")
private String email;
  1. Create an attachment object.
Attachment attachment = new Attachment();
//邮件中的附件名,可以与路径中的不一样
attachment.setFileName("你的附件名.txt");
//硬盘中的文件名,必须写扩展名。
attachment.setFilePath("C:temo\文档.txt");
  1. Sending an email
    Returns 1 if it is sent successfully, and returns 0 if it fails.
Integer result = EmailUtils.sendMailAttachment(javaMailSender, email, "客户[email protected]","标题", "正文。",attachment );

An example of the use of the two tool methods

    private void demo() {

        // 步骤一:注入邮件工具实例。
        // @Autowired
        // private JavaMailSender javaMailSender;

        // 步骤二:注入公司邮箱,配置文件中,微服务模块对应的邮箱地址,每个服务邮箱地址可能不相同。
        // @Value("${spring.mail.username}")
        // private String email;

        // 步骤三:发送邮件。

        // 邮件工具1:发送单个附件邮件
        // Integer oneAttachment = EmailUtils.sendMailAttachment(javaMailSender, "业务模块1专用邮箱@163.cn", "客户[email protected]",
        // "我是标题", "您好!我是正文。", Attachment.of().setFileName("邮件附件名称.xls").setFilePath("C:\\Workspace\\本地文件名称.xlsx"));

        // 邮件工具2:发送多个附件邮件
        // 创建多个附件
        List<Attachment> attachments = new ArrayList<Attachment>();
        attachments.add(Attachment.of().setFileName("邮件附件名称1.xlsx").setFilePath("C:\\Workspace\\本地文件名称1.xlsx"));
        attachments.add(Attachment.of().setFileName("邮件附件名称2.xlsx").setFilePath("C:\\Workspace\\本地文件名称2.xlsx"));
        // 发送多个附件邮件
        // Integer multiAttachment = EmailUtils.sendMailAttachments(javaMailSender, "业务模块专用邮箱@cnecloud.cn",
        // "客户@qq.com","我是标题", "您好!我是正文。", attachments);
    }

6. Java regular expression to verify the legitimacy of emails

At the control layer, you can verify whether the email address entered by the user is legal:

Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
Matcher matcher = pattern.matcher(sendBillInput.getEmail());
    if (!matcher.matches()) {
        log.error("邮箱格式不合法");
    }

7. Problems encountered in sending emails

1. The Chinese name of the attachment is garbled

Solution:

Just add coding to the tool class.

MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
// 附件中文名编码,参数"B"含义:Base64编码格式
helper.addAttachment(MimeUtility.encodeWord(attachment.getFileName(), "UTF-8", "B"), file);

2. The name of the email attachment is incomplete or converted into other characters.

For example, the attachment name is defined as: 2021年苹果公司销售额记录单.xls, but the abnormal display of QQ mailbox is: 2021年苹果公____司销售额E7__.xls, and the abnormal display of Netease mailbox is: ATT0002.bin, what is going on?

Solution:

This problem is different from garbled characters. This is not because the attachment name is garbled, but because the attachment name is not displayed properly. We will add the following configuration to the mail tool to solve it:

 System.setProperty("mail.mime.splitlongparameters", "false");

8. Summary

The methods and common questions about sending emails in SpringCloud or Springboot are shared here. With these in hand, it is enough to use mail in Spring Cloud. Of course, you can use this tool class as a separate SpringCloud mail microservice.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324162711&siteId=291194637