springboot發送郵件

源碼:https://gitee.com/smfx1314/sendMail

Spring Boot中發送郵件步驟

Spring Boot中發送郵件具體的使用步驟如下

  • 1、添加Starter模塊依賴
  • 2、添加Spring Boot配置(QQ/網易系/Gmail)
  • 3、調用JavaMailSender接口發送郵件

開始編碼

創建springboot項目,添加依賴
項目結構


1、添加依賴
在 Maven pom.xml 配置文件中加入 spring-boot-starter-mail 依賴。

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

2、添加配置參數
然後在 application.yml 文件中加入以下配置。

application.yml 配置
網易系(126/163/yeah)郵箱配置

## QQ郵箱配置
spring:
  mail:
    host: smtp.qq.com #發送郵件服務器
    username: [email protected] #發送郵件的郵箱地址
    password:  ivhkrc*****kbdcf #客戶端授權碼,不是郵箱密碼,這個在qq郵箱設置裏面自動生成的
    properties.mail.smtp.port: 465 #端口號465或587
    from: [email protected] # 發送郵件的地址,和上面username一致
  可以任意
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

網易系(126/163/yeah)郵箱配置

##網易系(126/163/yeah)郵箱配置
spring:
  mail:
    host: smtp.126.com #發送郵件服務器
    username: [email protected] #發送郵件的郵箱地址
    password: xxxxxxx #客戶端授權碼,不是郵箱密碼,網易的是自己設置的
    properties.mail.smtp.port: 994 #465或者994
    from: [email protected] # 發送郵件的地址,和上面username一致
   可以任意
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

注意:

  • 126郵箱SMTP服務器地址:smtp.126.com,端口號:465或者994
  • 163郵箱SMTP服務器地址:smtp.163.com,端口號:465或者994
  • yeah郵箱SMTP服務器地址:smtp.yeah.net,端口號:465或者994

封裝郵件接口,方便調用發送郵件
IMailService 接口

package com.jiangfeixiang.sendemail;

/**
 * @Author: 姜飛祥
 * @Description: 封裝一個發郵件的接口,後邊直接調用即可
 * @Date: Create in 2019/1/28/0028 21:57
 * @param: $params$
 * @return: $returns$
 */
public interface IMailService {

    /**
     * 發送文本郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 發送HTML郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     */
    public void sendHtmlMail(String to, String subject, String content);



    /**
     * 發送帶附件的郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     * @param filePath 附件
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath);
}

IMailServiceImpl 實現類

package com.jiangfeixiang.sendemail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Service;

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

/**
 * @Author: 姜飛祥
 * @Description:
 * @Date: Create in 2019/1/28/0028 22:00
 * @param: $params$
 * @return: $returns$
 */
@Service
public class IMailServiceImpl implements IMailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Spring Boot 提供了一個發送郵件的簡單抽象,使用的是下面這個接口,這裏直接注入即可使用
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 配置文件中我的qq郵箱
     */
    @Value("${spring.mail.from}")
    private String from;

    /**
     * 簡單文本郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //創建SimpleMailMessage對象
        SimpleMailMessage message = new SimpleMailMessage();
        //郵件發送人
        message.setFrom(from);
        //郵件接收人
        message.setTo(to);
        //郵件主題
        message.setSubject(subject);
        //郵件內容
        message.setText(content);
        //發送郵件
        mailSender.send(message);
    }

    /**
     * html郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //獲取MimeMessage對象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //郵件發送人
            messageHelper.setFrom(from);
            //郵件接收人
            messageHelper.setTo(subject);
            //郵件主題
            message.setSubject(subject);
            //郵件內容,html格式
            messageHelper.setText(content, true);
            //發送
            mailSender.send(message);
            //日誌信息
            logger.info("郵件已經發送。");
        } catch (MessagingException e) {
            logger.error("發送郵件時發生異常!", e);
        }
    }

    /**
     * 帶附件的郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     * @param filePath 附件
     */
    @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 = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            //日誌信息
            logger.info("郵件已經發送。");
        } catch (MessagingException e) {
            logger.error("發送郵件時發生異常!", e);
        }


    }
}

測試

package com.jiangfeixiang.sendemail;

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;

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

    /**
     * 注入發送郵件的接口
     */
    @Autowired
    private IMailService mailService;

    /**
     * 測試發送文本郵件
     */
    @Test
    public void sendmail() {
        mailService.sendSimpleMail("[email protected]","主題:你好普通郵件","內容:第一封郵件");
    }

    @Test
    public void sendmailHtml(){
        mailService.sendHtmlMail("[email protected]","主題:你好html郵件","<h1>內容:第一封html郵件</h1>");
    }
}


到此已經結束,下一篇,我將分享常見的網站註冊,郵箱點擊鏈接驗證激活如何實現。

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