Springboot Thymeleaf 發郵件 將html內容展示在郵件內容中


 

需要的依賴主要如下:

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

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

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

  

代碼如下:

主要文件有interface Mailserver 和 MailServerImpl

 

 

代碼:

package com.example.demo.email;

public interface MailService {

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

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

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

}

 

package com.example.demo.email;

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.Component;
import org.springframework.stereotype.Service;

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

@Component
//@Service
public class MailServiceImpl implements MailService {

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

    @Autowired
    private JavaMailSender javaMailSender;

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

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

    @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 {
            javaMailSender.send(message);
            logger.info("發送簡單郵件成功!");
        } catch (Exception e) {
            logger.error("發送簡單郵件時發生異常!", e);
        }

    }

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

        try {
            //true表示需要創建一個multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);//郵件接收者
            helper.setCc(cc);
            helper.setBcc(bcc);
            helper.setSubject(subject);//郵件主題
            helper.setText(content, true);//郵件內容

            FileSystemResource avatar = new FileSystemResource("image/Jasmine.png");
            helper.addInline("avatar",avatar);

            javaMailSender.send(message);
            logger.info("發送HTML郵件成功!");
        } catch (MessagingException e) {
            logger.error("發送HTML郵件時發生異常!", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = javaMailSender.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);

            javaMailSender.send(message);
            logger.info("發送帶附件的郵件成功!");
        } catch (MessagingException e) {
            logger.error("發送帶附件的郵件時發生異常!", e);
        }
    }

}

 

如何調用

Context context = new Context();
            context.setVariable("bugnum", "bugnum#"+bugNotifyBean.getId());
            context.setVariable("pro_img", "avatar");
            context.setVariable("bugdes", bugNotifyBean.getDescription());
            context.setVariable("bugstatus", bugNotifyBean.getBugStatus());
            context.setVariable("crname", bugNotifyBean.getCrname());
            context.setVariable("crnum", bugNotifyBean.getCrnum());
            context.setVariable("oname", bugNotifyBean.getOname());
            context.setVariable("pname", bugNotifyBean.getPname());
            context.setVariable("rca", bugNotifyBean.getRca());
            context.setVariable("tasknum", bugNotifyBean.getTasknum());
            context.setVariable("solution", bugNotifyBean.getSolution());


            String emailContent = templateEngine.process("emailTemplate", context);
            mailService.sendHtmlMail(developerEmail, testerEmail,"您好,有一個Bug要關注,謝謝!!", emailContent);

  

 

1. 買坑之旅

org.springframework.mail.MailSendException: Failed messages: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: image\Jasmine.png
; message exception details (1) are:

 

 2. html中帶有圖片,即

<html><body><img src="cid:avatar"/></body></html>
    @Override
    public void sendHtmlMailwithImage(String to, String cc, String subject, String content) {

        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //true表示需要創建一個multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);//郵件接收者
            helper.setCc(cc);
            helper.setSubject(subject);//郵件主題
            helper.setText(content, true);//郵件內容

            String imagePath="src/main/resources/proba.jpg";
            FileSystemResource fileSystemResource = new FileSystemResource(imagePath);

            //FileSystemResource avatar = new FileSystemResource("image/Jasmine.png");
            System.out.println(fileSystemResource);
            helper.addInline("avatar",fileSystemResource);
            javaMailSender.send(message);
            System.out.println("發送HTML郵件成功!");
        } catch (MessagingException e) {
            System.out.println("發送HTML郵件時發生異常!"+ e);
        }

    }

  更新於20190701 讀取圖片,加載到郵件內容中

利用springboot-mail除了發送上面三種郵件格式

簡單郵件內容

html郵件內容

帶有附件的郵件內容,還可以讀取pic,組裝到對應的html中

String imagePath="src/main/resources/proba.jpg";
            FileSystemResource fileSystemResource = new FileSystemResource(imagePath);

            //FileSystemResource avatar = new FileSystemResource("image/Jasmine.png");
            System.out.println(fileSystemResource);
            helper.addInline("avatar",fileSystemResource);

  獲取pic的路徑,如果是在程序中執行,可以給出相對路徑

如果部署到服務上去,我給出server的詳細路徑也可

html中獲取用格式:

<html><body><img src="cid:avatar"/></body></html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM