1. 程式人生 > >SpringBoot中快速實現郵箱傳送

SpringBoot中快速實現郵箱傳送

前言

在許多企業級專案中,需要用到郵件傳送的功能,如:

  1. 註冊使用者時需要郵箱傳送驗證
  2. 使用者生日時傳送郵件通知祝賀
  3. 傳送郵件給使用者等

    建立工程匯入依賴
<!-- 郵箱傳送依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 小火龍程式碼簡化 -->
<dependency>
    <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    <version>1.18.8</version>
</dependency>

本工程依賴於SpringBoot,是基於SpringBoot再次對郵箱傳送進行了一次封裝。

建立Application.properties
# JavaMailSender 郵件傳送的配置
spring.mail.host=smtp.qq.com
[email protected]
#授權碼
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8
封裝郵箱傳送工具類

建立郵箱資訊實體類,如下:

/**
 * 郵件資訊實體
 *
 * @author:伍梓濤
 * @version:1.0.0
 * @Modified By:SimpleWu
 * @CopyRright (c)2019-:YUM架構平臺
 */
@Data
public class MailEntity {
    private String to; //收件人
    private String subject;//標題
    private String text;//正文
    private boolean isHtml = false;//是否html郵件
    private List<String> files;//附件地址
    private Date sentDate;//傳送時間

}

建立郵箱資訊實體類工具,快捷建立郵件資訊

/**
 * 郵箱傳送資訊統一處理封裝
 *
 * @author:伍梓濤
 * @version:1.0.0
 * @Modified By:SimpleWu
 * @CopyRright (c)2019-:YUM架構平臺
 */
@Slf4j
public class MailEntityHelper {


    public static MimeMessageHelper craeteMessageHelper(MimeMessage mimeMessage, MailEntity mailBean) throws MessagingException {

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        // mimeMessageHelper.setFrom(emailSender);//發件人
        mimeMessageHelper.setTo(mailBean.getTo());//收件人
        mimeMessageHelper.setSubject(mailBean.getSubject());//標題
        mimeMessageHelper.setText(mailBean.getText(), mailBean.isHtml());//是否html
        mimeMessageHelper.setSentDate(mailBean.getSentDate() == null ? new Date() : mailBean.getSentDate());// 客戶端郵箱傳送時間
        if (mailBean.getFiles() != null && mailBean.getFiles().size() > 0) {
            //附件新增
            mailBean.getFiles().forEach(filename -> {
                String ext = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
                File diskfile = new File(filename);
                try {
                    mimeMessageHelper.addAttachment(diskfile.getName(), diskfile);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    log.error("設定附件失敗:{}", mailBean);
                }
            });
        }
        return mimeMessageHelper;
    }

}

建立郵箱傳送工具類,進行郵箱傳送:


/**
 * 郵箱傳送工具類
 *
 * @author:伍梓濤
 * @version:1.0.0
 * @Modified By:SimpleWu
 * @CopyRright (c)2019-:YUM架構平臺
 */
@Component
@Slf4j
public class MailHelper {


    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String emailSender;

    private static MailHelper mailHelper;

    public MailHelper() {
        mailHelper = this;
    }

    /**
     * 構建靜態獲取例項
     *
     * @return
     */
    public static MailHelper buidler() {
        if (mailHelper == null) {
            return null;
        }
        return mailHelper;
    }

    /*public void sendSimpleMail(EmailContextPojo mailBean) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //郵件傳送人
            simpleMailMessage.setFrom(emailSender);
            //郵件接收人
            simpleMailMessage.setTo(mailBean.getTo());
            //郵件主題
            simpleMailMessage.setSubject(mailBean.getSubject());
            //郵件內容
            simpleMailMessage.setText(mailBean.getText());
            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("郵件傳送失敗", e.getMessage());
        }
    }*/


    public void sendMail(MailEntity mailBean) {
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = MailEntityHelper.craeteMessageHelper(mimeMailMessage, mailBean);
            mimeMessageHelper.setFrom(emailSender);//發件人
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            log.error("郵件傳送失敗", e.getMessage());
        }
    }


    public void sendMail(MailEntity... mailBeans) {
        //批量傳送集合
        List<MimeMessage> mimeMessages = new ArrayList<>(mailBeans.length);
        try {
            if (mailBeans != null || mailBeans.length > 0) {
                for (int i = 0; i < mailBeans.length; i++) {
                    MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
                    MimeMessageHelper messageHelper = MailEntityHelper.craeteMessageHelper(mimeMailMessage, mailBeans[i]);
                    messageHelper.setFrom(emailSender);//發件人
                    mimeMessages.add(mimeMailMessage);
                }
            }

            MimeMessage[] resultMessage = new MimeMessage[mimeMessages.size()];
            mimeMessages.toArray(resultMessage);
            javaMailSender.send((resultMessage));
        } catch (Exception e) {
            log.error("郵件傳送失敗", e.getMessage());
        }
    }


}

在之前通過郵箱傳送資訊統一處理的工具類,對郵件資訊實體進行封裝後,這裡就只需要傳入物件引數即可。由於在這裡使用的是SpringBoot已經封裝好的,由於我們要把它當成工具類使用,每次需要注入並不方便。
所在在類中加了個靜態物件,在Spring 容器例項化的時候給他初始化直接賦值給javaMailSender並且通過buidler()可以靜態獲取到例項物件,但是這樣如果被重新建立物件後就會產生問題,所以最好在工具類中使用Spring 容器去獲取 javaMailSender即可 。

傳送郵件

1.傳送普通郵件

 MailEntity emailContextPojo = new MailEntity();
 emailContextPojo.setSubject("Ycloud 郵箱標題");
 emailContextPojo.setText("Ycloud 郵箱正文");
 emailContextPojo.setTo(" 接收郵箱號 ");
 MailHelper.buidler().sendMail(emailContextPojo);

2.傳送Html郵件

 emailContextPojo.setHtml(true);

只需要將資訊實體類設定成true即可。
3.傳送附件

emailContextPojo.setFiles(Arrays.asList("D:\\Yum系統架構平臺\\004.高系統部署\\004.PXC\\部署手冊.docx"));

只需要增加附件路徑即可。
注: 請勿直接在專案中使用郵箱傳送
可參考JOB實現定時傳送郵件:https://www.cnblogs.com/SimpleWu/p/11341453.html
本文程式碼案例:https://github.com/450255266/open-doubi/tree/master/SpringBoot/email