25、springboot發送郵件

雖然現在短信驗證已經最流行也是最常用的驗證方式;但是郵件驗證還是必不可少,依然是網站的必備功能之一。什麼註冊驗證,忘記密碼或者是給用戶發送營銷信息都是可以使用郵件發送功能的。最早期使用JavaMail的相關api來進行發送郵件的功能開發,後來spring整合了JavaMail的相關api推出了JavaMailSender更加簡化了郵件發送的代碼編寫,現在springboot對此進行了封裝就有了現在的spring-boot-starter-mail。

1、新建項目sc-mail,對應的pom.xml文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-cloud</groupId>
    <artifactId>sc-mail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>sc-mail</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

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

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

    </dependencies>
</project>

2、新建配置文件application.yml

spring:
    application:
        name: sc-mail
    mail:
        host: smtp.qq.com #郵箱服務器地址
        port: 465
        username: [email protected] #用戶名
        password: vfcqhwsnnwugbhcx #密碼 (改成自己的密碼)
        default-encoding: UTF-8
        properties:
            mail:
                smtp:
                    ssl:
                        enable:
                            true

3、新建郵件發送服務類

package sc.mail.service.impl;

import java.io.File;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import sc.mail.service.MailService;

@Service
public class MailServiceImpl implements MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 文本
     * @param from
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendSimpleMail(String from, String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("simple mail had send。");
        } catch (Exception e) {
            logger.error("send mail error", e);
        }
    }

    /**
     * @param from
     * @param to
     * @param subject
     * @param content
     */
    public void sendTemplateMail(String from, String to, String subject, String content) {
            MimeMessage message = mailSender.createMimeMessage();
            try {
                    //true表示需要創建一個multipart message
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    helper.setFrom(from);
                    helper.setTo(to);
                    helper.setSubject(subject);
                    helper.setText(content, true);
                    mailSender.send(message);
                    logger.info("send template success");
            } catch (Exception e) {
                    logger.error("send template eror", e);
            }
    }

    /**
     * 附件
     * 
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String from, String to, String subject, String content, String filePath){
            MimeMessage message = mailSender.createMimeMessage();
            try {
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    helper.setFrom(from);
                    helper.setTo(to);
                    helper.setSubject(subject);
                    helper.setText(content, true);
                    FileSystemResource file = new FileSystemResource(new File(filePath));
                    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                    helper.addAttachment(fileName, file);
                    mailSender.send(message);
                    logger.info("send mail with attach success。");
            } catch (Exception e) {
                    logger.error("send mail with attach success", e);
            }
    }

    /**
     * 發送內嵌圖片
     * 
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param imgPath
     * @param imgId
     */
    public void sendInlineResourceMail(String from, String to, String subject, String content,
            String imgPath, String imgId){
            MimeMessage message = mailSender.createMimeMessage();
            try {
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    helper.setFrom(from);
                    helper.setTo(to);
                    helper.setSubject(subject);
                    helper.setText(content, true);
                    FileSystemResource res = new FileSystemResource(new File(imgPath));
                    helper.addInline(imgId, res);
                    mailSender.send(message);
                    logger.info("send inner resources success。");
            } catch (Exception e) {
                    logger.error("send inner resources fail", e);
            }
    }

}

4、新建測試類

package sc.mail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import sc.mail.service.MailService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailSendTest {

    @Autowired
    private MailService mailService;

    @Test
    public void sendSimpleMailTest() {
        mailService.sendSimpleMail("[email protected]", "[email protected]", 
                "sendSimpleMailTest", "sendSimpleMailTest from [email protected]");
    }

    @Test
    public void sendTemplateMailTest() {
        String html = "<html><body>"
                + " <div> "
                + "    sendTemplateMailTest from [email protected] </br>"
                + "    <b>這是模板郵件</b>"
                + "</div>"
                + "</body></html>";
        mailService.sendTemplateMail("[email protected]", "[email protected]", 
                "sendTemplateMailTest", html);
    }

    @Test
    public void sendAttachmentsMailTest() {
        String filePath = "D:\\springcloudws\\sc-mail\\src\\main\\java\\sc\\mail\\service\\impl\\MailServiceImpl.java";
        mailService.sendAttachmentsMail("[email protected]", "[email protected]", 
                "sendAttachmentsMailTest", "sendAttachmentsMailTest from [email protected]", filePath);
    }

    @Test
    public void sendInlineResourceMailTest() {
        String imgId = "img1";

        String content = "<html><body>"
                + "sendInlineResourceMailTest:<img src=\'cid:" + imgId + "\' >"
                        + "</body></html>";

        String imgPath = "D:\\springcloudws\\sc-mail\\src\\main\\resources\\20181015223228.jpg";

        mailService.sendInlineResourceMail("[email protected]", "[email protected]", 
                "sendAttachmentsMailTest", content, imgPath, imgId);
    }

}

5、運行測試類驗證是否發送郵件成功br/>登錄[email protected]郵箱
25、springboot發送郵件
簡單郵件
25、springboot發送郵件
模板郵件
25、springboot發送郵件
附件郵件
25、springboot發送郵件
內嵌圖片郵件
25、springboot發送郵件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章