Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[mail] Fix sending HTML/Multipart mails #13108

Merged
merged 1 commit into from
Jul 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down