From 6f81b0d873627b336ea221e22aef0e16af5deabb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hans-J=C3=B6rg=20Merk?= Date: Sun, 10 Jul 2022 15:21:56 +0200 Subject: [PATCH] [mail] Fix sending HTML/Multipart mails (#13108) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Hans-Jörg Merk Signed-off-by: Andras Uhrin --- .../binding/mail/internal/SMTPHandler.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java index dbf271e5ad43f..f95dc033a13dc 100644 --- a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java +++ b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java @@ -12,11 +12,16 @@ */ package org.openhab.binding.mail.internal; +import java.lang.reflect.Field; import java.util.Collection; import java.util.List; +import javax.activation.DataHandler; +import javax.activation.DataSource; import javax.activation.PatchedMailcapCommandMap; import javax.mail.MessagingException; +import javax.mail.Part; +import javax.mail.internet.MimeMultipart; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; @@ -39,6 +44,7 @@ * * @author Jan N. Klug - Initial contribution * @author Hans-Jörg Merk - Fixed UnsupportedDataTypeException - Originally by Jan N. Klug + * - Fix sending HTML/Multipart mail - Originally by Jan N. Klug */ @NonNullByDefault public class SMTPHandler extends BaseThingHandler { @@ -100,7 +106,25 @@ public boolean sendMail(Email mail) { } mail.buildMimeMessage(); - mail.getMimeMessage().getDataHandler().setCommandMap(commandMap); + + // fix command map not available + DataHandler dataHandler = mail.getMimeMessage().getDataHandler(); + dataHandler.setCommandMap(commandMap); + try { + DataSource dataSource = dataHandler.getDataSource(); + Field dataField = dataSource.getClass().getDeclaredField("data"); + dataField.setAccessible(true); + Object data = dataField.get(dataSource); + if (data instanceof MimeMultipart) { + MimeMultipart mimeMultipart = (MimeMultipart) data; + for (int i = 0; i < mimeMultipart.getCount(); i++) { + Part mimePart = mimeMultipart.getBodyPart(i); + mimePart.getDataHandler().setCommandMap(commandMap); + } + } + } catch (NoSuchFieldException | IllegalAccessException ignored) { + } + mail.sendMimeMessage(); } catch (MessagingException | EmailException e) { Throwable cause = e.getCause();