如何使用 ThymeLeaf 发送带有内嵌图像的电子邮件 [英] How to send email with inline image using ThymeLeaf

查看:52
本文介绍了如何使用 ThymeLeaf 发送带有内嵌图像的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ThymeLeaf 和 Spring 发送带有内嵌图像的电子邮件,但到目前为止没有成功.电子邮件已发送,但内嵌图片不会显示在电子邮件中.

该项目不是基于网络的(不是网站),而是一个桌面独立的,不是移动的

这是我获取图像文件的方式:

URL url = getClass().getResource("/LawFirmAdvisoryGroup.jpg");File file = new File(url.getPath());MultipartFile multipartFile = new MockMultipartFile(file.getName(),file.getName(), "image/jpeg", IOUtils.toByteArray(input));

<小时>

我的服务类:

@Autowired私有 JavaMailSender mailSender;@自动连线私有模板引擎模板引擎;公共无效sendMailWithInline(最终字符串收件人姓名,最终字符串收件人电子邮件,最终MultipartFile图像,最终字节[] imageBytes)抛出消息异常{最终上下文 ctx = new Context();ctx.setVariable("imageResourceName", image.getName());//这样我们就可以从 HTML 中引用它final MimeMessage mimeMessage = this.mailSender.createMimeMessage();最后的 MimeMessageHelper 消息= new MimeMessageHelper(mimeMessage, true, "UTF-8");message.setSubject("内嵌图片");message.setFrom("XXXX@yahoo.com");message.setTo(recipientEmail);//添加内嵌图像,从 HTML 代码引用为cid:${imageResourceName}"最终 InputStreamSource imageSource = new ByteArrayResource(imageBytes);message.addInline(image.getName(), imageSource, image.getContentType());最终字符串 htmlContent = this.templateEngine.process("left_sidebar.html", ctx);message.setText(htmlContent, true);this.mailSender.send(mimeMessage);}

<小时>

HTML:

<html xmlns:th="http://www.thymeleaf.org"><头><title th:remove="all">带有内嵌图片的电子邮件</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><身体><p><img src="LawFirmAdvisoryGroup.jpg" th:src="'cid:' + ${imageResourceName}"/></p></html>

解决方案

这很完美:

只需添加指向托管在远离桌面的外部服务器上的图像的链接即可.使用内联 CSS,而不是 CSS 类.

本网站将帮助您将 CSS 类转换为内联 CSS,Premailer.Dialect.

避免任何花哨的 CSS,只使用最基本的.如果您希望 HTML 邮件轻松流动,即使在移动设备和其他较小的屏幕上,也应尽可能避免浮动(如 float: left;).

在您的项目库中包含 NekoHTML,并更改您的 Spring spring.xml 到:

<bean id="emailTemplateResolver" class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver"><property name="prefix" value="resources/WEB_INF/HTMLMailTemplates/XXXX/html/"/><!-- <property name="templateMode" value="HTML5"/>--><property name="templateMode" value="LEGACYHTML5"/><property name="characterEncoding" value="UTF-8"/><property name="order" value="1"/></bean>

示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><头><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>带有内嵌图片的电子邮件</title><风格>身体 {背景图片:url('https://dl.dropbox.com/s/XXXX/pageBackGround.gif');背景重复:重复;保证金:0;大纲:0;}.pageContentWrapper {填充:10px;宽度:100%;背景图片:url('https://dl.dropbox.com/s/XXXX/smallerInlineImage.gif');背景重复:重复;}.smallerInlineImage {宽度:22px;高度:22px;填充:0 4px 6px 0;向左飘浮;}</风格><身体><div class="pageContentWrapper"><div class="smallerInlineImage"><img src="https://dl.dropboxusercontent.com/s/3ydel6zp53pb65b/smallerInlineImage.png" height="22" width="22">

服务类:

@Service公共类 ThymeEmailService {@自动连线私有 JavaMailSender mailSender;@自动连线私有模板引擎模板引擎;public void sendMailWithInline() 抛出 MessagingException {最终上下文 ctx = new Context();final MimeMessage mimeMessage = this.mailSender.createMimeMessage();final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");message.setSubject("示例电子邮件主题");message.setFrom("senderEmail@yahoo.com");message.setTo("recipientEmail@yahoo.com");最终字符串 htmlContent = this.templateEngine.process("emailTemplate.html", ctx);message.setText(htmlContent, true);String[] 附件 = {"C:\\Users\\MyPc\\Dropbox\\CV\\myPDFAttachment.pdf"};for(字符串附件:附件){FileSystemResource file = new FileSystemResource(attachment);message.addAttachment(file.getFilename(), file);}this.mailSender.send(mimeMessage);}}

I'm trying to send an email with an inline image using ThymeLeaf and Spring, but so far no success. The email sends, but the inline image won't show in the email.

The project is not web-based (not a website), but is a desktop stand-alone, not mobile

This is how I get the image file:

URL url = getClass().getResource("/LawFirmAdvisoryGroup.jpg");
File file = new File(url.getPath());

MultipartFile multipartFile = new MockMultipartFile(file.getName(),
    file.getName(), "image/jpeg", IOUtils.toByteArray(input));


My service class:

@Autowired
private JavaMailSender mailSender;

@Autowired
private TemplateEngine templateEngine;

public void sendMailWithInline(final String recipientName, final String recipientEmail, final MultipartFile image, final byte[] imageBytes)
throws MessagingException {

    final Context ctx = new Context();
        ctx.setVariable("imageResourceName", image.getName()); // so that we can reference it from HTML

        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message
        = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        message.setSubject("Inline Image");
        message.setFrom("XXXX@yahoo.com");
        message.setTo(recipientEmail);

        // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
        final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
        message.addInline(image.getName(), imageSource, image.getContentType());


        final String htmlContent = this.templateEngine.process("left_sidebar.html", ctx);
        message.setText(htmlContent, true);
        this.mailSender.send(mimeMessage);

    }


The HTML:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title th:remove="all">Email with inline image</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p>
      <img src="LawFirmAdvisoryGroup.jpg" th:src="'cid:' + ${imageResourceName}" />
    </p>
  </body>
</html>

解决方案

This works perfectly:

Just add a link to the image hosted on an external server away from your desktop. Use inline CSS, instead of CSS classes.

This website will help you convert CSS classes to inline CSS, Premailer.Dialect.

Avoid any fancy CSS, just use the most basic. Floating (like float: left;) should be avoided as much as possible if you'd like your HTML mail to flow easily, even in mobile devises and other smaller screens.

Include NekoHTML in your project libraries, and change your Spring spring.xml to:

<!-- THYMELEAF: Template Resolver for email templates -->
<bean id="emailTemplateResolver" class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
    <property name="prefix" value="resources/WEB_INF/HTMLMailTemplates/XXXX/html/" />
    <!-- <property name="templateMode" value="HTML5" /> -->
    <property name="templateMode" value="LEGACYHTML5" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="order" value="1" />
</bean>

Sample this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Email With Inline Images</title>

    <style>
        body {
            background-image: url('https://dl.dropbox.com/s/XXXX/pageBackGround.gif');
            background-repeat: repeat;
            margin:0;
            outline:0;
        }
        .pageContentWrapper {
            padding:10px;
            width: 100%;
            background-image: url('https://dl.dropbox.com/s/XXXX/smallerInlineImage.gif');
            background-repeat: repeat;
        }
        .smallerInlineImage {
            width: 22px;
            height: 22px;
            padding: 0 4px 6px 0;
            float: left;
        }
    </style>

</head>

<body>
    <div class="pageContentWrapper">
        <div class="smallerInlineImage">
            <img src="https://dl.dropboxusercontent.com/s/3ydel6zp53pb65b/smallerInlineImage.png" height="22" width="22">
        </div>
    </div>
</body>

Service Class:

@Service
public class ThymeEmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    public void sendMailWithInline() throws MessagingException {

        final Context ctx = new Context();

        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        message.setSubject("Sample Email Subject");
        message.setFrom("senderEmail@yahoo.com");
        message.setTo("recipientEmail@yahoo.com");

        final String htmlContent = this.templateEngine.process("emailTemplate.html", ctx);
        message.setText(htmlContent, true);

        String[] attachments = {"C:\\Users\\MyPc\\Dropbox\\CV\\myPDFAttachment.pdf"};

        for (String attachment : attachments) {
            FileSystemResource file = new FileSystemResource(attachment);
            message.addAttachment(file.getFilename(), file);
        }

        this.mailSender.send(mimeMessage);
    }
}

这篇关于如何使用 ThymeLeaf 发送带有内嵌图像的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Java开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆