Images sent as an attachment in e-mail with Thymeleaf

Asked

Viewed 398 times

0

Hello, I’m sending a dynamic email template using Thymeleaf. The email is displayed correctly with the images, however, the images are also being attached in the body of the email, which should not occur.

HTML:

<!-- I need put the image backgroud via css!-->
<body th:style="'background-image: url('+ |cid:${background}| +')'">
    <!--my image-->
    <img src="../../../static/images/email/topo_email.png" th:src="|cid:${logo}|"/>
</body>

Java:

//the main code of the method is here:

String emailFormatado = contatoEmail.getDescricao().replace(System.lineSeparator(), "<br>");
contatoEmail.setDescricao(emailFormatado);

Context context = new Context(new Locale("pt", "BR"));
context.setVariable("contatoEmail", contatoEmail);
context.setVariable("logo", "logo");
context.setVariable("background", "background");

try {
    String corpoEmail = thymeleaf.process("admin/mail/EmailResposta", context);
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    helper.setFrom(contatoEmail.getUsuario().getEmail());
    helper.setTo(email);
    helper.setSubject(String.format("Mensagem de respota"));
    helper.setText(corpoEmail, true);

    helper.addInline("background", new ClassPathResource("static/images/email/background_email.png"));
    helper.addInline("logo", new ClassPathResource("static/images/email/topo_email.png"));

    mailSender.send(mimeMessage);
} catch (MessagingException e) {
    logger.error("Erro enviando e-mail", e);

I made some variations in the code, but without success. Any help is welcome.

2 answers

1

Two years later and you still helped me.

I supplemented it as follows:

FileSystemResource file = new FileSystemResource(new File("C:\\telefone.png").getCanonicalPath());
helper.addInline("telefoneid", file, "image/png");

If you want the image to be attached uncommented

//helper.addAttachment("telefone.png", file);

mimeMessage.setContent(mail.getContent(), "text/html;charset=utf-8");

mailSender.send(mail);

0


Solution:

In java code, it was missing to inform the image type in the same variable:

helper.addInline("logo", new ClassPathResource("static/images/email/topo_email.png"), "image/png");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.