Springboot 自動傳送郵件

萬笑佛發表於2023-11-23

   完成Springboot配置發件郵箱,自動給其他郵箱傳送郵件功能

一、建立springboot基礎專案,引入依賴

<!-- Spring Boot 郵件依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring Boot 模板依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、配置檔案新增必要的配置:

#qq郵箱為例
spring.mail.host=smtp.qq.com

spring.mail.port=465

spring.mail.username=89666XXX@qq.com

spring.mail.password=XXXXXX  #不是郵件密碼而是授權碼(郵箱設定裡獲取)

spring.mail.protocol=smtp

spring.mail.test-connection=true

spring.mail.default-encoding=UTF-8

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.properties.mail.smtp.ssl.enable=true

spring.mail.properties.mail.display.sendmail=spring-boot-demo

 

   三、工程結構

 

四、MailService介面
package com.example.mail.demo;

import javax.mail.MessagingException;

public interface MailService {
    /**
     * 傳送文字郵件
     *
     * @param to      收件人地址
     * @param subject 郵件主題
     * @param content 郵件內容
     * @param cc      抄送地址
     */
    void sendSimpleMail(String to, String subject, String content, String... cc);

    /**
     * 傳送HTML郵件
     *
     * @param to      收件人地址
     * @param subject 郵件主題
     * @param content 郵件內容
     * @param cc      抄送地址
     * @throws MessagingException 郵件傳送異常
     */
    void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException;

    /**
     * 傳送帶附件的郵件
     *
     * @param to       收件人地址
     * @param subject  郵件主題
     * @param content  郵件內容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 郵件傳送異常
     */
    void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;

   
}
五、MailServiceImpl實現
package com.example.mail.demo;
 
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;

@Service
public class MailServiceImpl implements MailService {

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

    /**
     * 傳送文字郵件
     *
     * @param to      收件人地址
     * @param subject 郵件主題
     * @param content 郵件內容
     * @param cc      抄送地址
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        if (cc != null) {
            message.setCc(cc);
        }
        mailSender.send(message);
    }

    /**
     * 傳送HTML郵件
     *
     * @param to      收件人地址
     * @param subject 郵件主題
     * @param content 郵件內容
     * @param cc      抄送地址
     * @throws MessagingException 郵件傳送異常
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        mailSender.send(message);
    }

    /**
     * 傳送帶附件的郵件
     *
     * @param to       收件人地址
     * @param subject  郵件主題
     * @param content  郵件內容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 郵件傳送異常
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        FileSystemResource file = new FileSystemResource(new File(filePath));

        String fileName = new File(filePath).getName();
        System.out.println("fileName:"+fileName);
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }


}
六、EmailController控制類
package com.example.mail.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import java.io.File;
import java.net.URL;

@Controller
public class EmailController {

    @Autowired
    private MailService mailService;

    /**
     * 測試傳送簡單郵件
     */
    @GetMapping("/testSendSimpleMail")
    @ResponseBody
    public String sendSimpleMail() {
        mailService.sendSimpleMail("2431886055@qq.com", "這是一封簡單郵件", "這是一封普通的SpringBoot測試郵件");
        return "ok";
    }

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 傳送html郵件
     * @return
     * @throws MessagingException
     */
    @GetMapping("/sendHtmlMail")
    @ResponseBody
    public String sendHtmlMail() throws MessagingException {
        Context context = new Context();
        context.setVariable("project", "Spring Boot email");
        context.setVariable("author", "萬笑佛");
        context.setVariable("url", "https://www.cnblogs.com/yclh/");
        String emailTemplate = templateEngine.process("welcome", context);
        mailService.sendHtmlMail("2431886055@qq.com", "這是一封模板HTML郵件", emailTemplate);
        return "ok";
    }


    /**
     * 傳送帶附件的郵件
     * @throws MessagingException
     */
    @GetMapping("/sendAttachmentsMail")
    @ResponseBody
    public String sendAttachmentsMail() throws MessagingException {
        URL url = null;
        try {
            // 建立一個檔案物件
            File file = new File("D:\\IDEANew\\45Mail\\src\\main\\resources\\static\\index.html");
            // 將檔案物件轉換為URI
            url = file.toURI().toURL();
            // 輸出URL
            System.out.println("檔案的URL: " + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(url.getPath());
        mailService.sendAttachmentsMail("2431886055@qq.com", "這是一封帶附件的郵件", "郵件中有附件,請注意查收!", url.getPath());
        return "ok";
    }



}
七、postman測試
(1)第一個簡單郵件

 

效果

(2)第二個帶模板的郵件

效果

 

(3)第三個帶附件的郵件

 

效果

 

 

 

相關文章