使用 Spring Boot 發(fā)送郵件

發(fā)送郵件是網(wǎng)站的必備功能之一,用戶注冊(cè)驗(yàn)證、忘記密碼或者發(fā)送營銷信息。Spring Boot使用 spring-boot-starter-mail,讓郵件發(fā)送的業(yè)務(wù)更加簡潔和完善。

郵件相關(guān)協(xié)議內(nèi)容如下:
  • SMTP 協(xié)議:發(fā)送郵件協(xié)議;
  • POP3 協(xié)議:獲取郵件協(xié)議;
  • IMAP:接收信息的高級(jí)協(xié)議;
  • MIME:郵件拓展內(nèi)容格式:信息格式,附件格式。

本人以qq郵箱為例。第一步肯定是要讓qq郵箱 開通POP3 /SMTP 服務(wù),因?yàn)槲覀冺?xiàng)目中有用到,否則就會(huì)因沒有授權(quán)而拋錯(cuò)。

授權(quán)頁面01[圖片上傳中...(TIM截圖20171206112905.png-255fe0-1512531023545-0)]

授權(quán)頁面02

這其中會(huì)產(chǎn)生一個(gè)授權(quán)碼,要記下來,下面要用。
好,接下來可以寫代碼了。

1.添加依賴
<dependencies>
    <dependency> 
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency> 
</dependencies>
2.配置application.yml文件
spring:
  application:
    name: mail
  mail:
    host: smtp.qq.com
    username: 123456@qq.com
    password: you-password  #開啟 POP3 之后設(shè)置的客戶端授權(quán)密碼
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true #這地方必須加,不然會(huì)授權(quán)失敗,提示350錯(cuò)誤
          starttls:
            enable: true
            required: true
3.新建服務(wù)類

MailService .java


/**
 * 發(fā)送郵件
 */
public interface MailService {

    public void sendSimpleMail(String to, String subject, String content);

    public void sendHtmlMail(String to, String subject, String content);

    public void sendAttachmentsMail(String to, String subject, String content, String filePath);

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
}

MailServiceImpl.java


import com.sqlb.service.MailService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

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


    @Override
    public void sendSimpleMail(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);
            log.info("簡單郵件已經(jīng)發(fā)送。");
        } catch (Exception e) {
            log.error("發(fā)送簡單郵件時(shí)發(fā)生異常!", e);
        }
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要?jiǎng)?chuàng)建一個(gè)multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            log.info("html郵件發(fā)送成功");
        } catch (MessagingException e) {
            log.error("發(fā)送html郵件時(shí)發(fā)生異常!", e);
        }
    }

    @Override
    public void sendAttachmentsMail(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 = file.getFilename();
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            log.info("帶附件的郵件已經(jīng)發(fā)送。");
        } catch (MessagingException e) {
            log.error("發(fā)送帶附件的郵件時(shí)發(fā)生異常!", e);
        }
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        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(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            log.info("嵌入靜態(tài)資源的郵件已經(jīng)發(fā)送。");
        } catch (MessagingException e) {
            log.error("發(fā)送嵌入靜態(tài)資源的郵件時(shí)發(fā)生異常!", e);
        }
    }
}
4.接下來就是測試了

import com.sqlb.service.MailService;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import static org.junit.Assert.*;


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

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleMail() throws Exception {
        mailService.sendSimpleMail("receiver-email","這是一封簡單郵件","大家好,這是我的第一封郵件!");
    }

    @Test
    public void sendHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 這是一封html郵件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail("123456@126.com","這是一封HTML郵件",content);
    }

    @Test
    public void sendAttachmentsMail() throws Exception {
        String filePath="e:\\temp\\fastdfs-client-java-5.0.0.jar";
        mailService.sendAttachmentsMail("ityouknow@126.com", "主題:帶附件的郵件", "有附件,請(qǐng)查收!", filePath);
    }

    @Test
    public void sendInlineResourceMail() throws Exception {

        String rscId = "neo006";
        String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "e:\\temp\\weixin.jpg";

        mailService.sendInlineResourceMail("123456@126.com", "主題:這是有圖片的郵件", content, imgPath, rscId);

    }


    @Test
    public void sendTemplateMail() {
        //創(chuàng)建郵件正文
        Context context = new Context();
        context.setVariable("id", "006");
        String emailContent = templateEngine.process("emailTemplate", context);

        mailService.sendHtmlMail("123456@126.com","主題:這是模板郵件",emailContent);
    }
}

ok 效果如下,大功告成!


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容