I try to make mailSender that is capable of sending emails with attachments using libraries jakarta.mail and org.springframework.mail.
I use public void addAttachment(String attachmentFilename, DataSource dataSource)
from MimeMessageHelper
object to add attachment to the MimeMessage
. Unfortunately, it does not work - there is no any exception thrown, but MimeMessage
does not contain any attachment after this operation and sent email hasn't got any attachment assigned to it too. At least, I haven't found any attachment's data inside MimeMessage
using debugger + I get email without attachment to my mailbox.
It may be important - I went deeper into addAttachment
method while debugging and I found out that inside the method there is new instance of DataHandler
with ByteArrayDataSource
(my attachment) created. This handler is then added to MimeBodyPart
which is then added to the root MimeMultipart
inside MimeMessageHelper
. I am not sure, but I think that this MimeMultipart
should be present inside MimeMessage
passed to messageHelper constructor in my useCase. Unfortunately I can see in my instance of MimeMessage
after addAttachment
operation that there is an instance of DataHandler
with null dataSource field
instead of this new created one. It looks that addAttachment
operation is simply ignored. But maybe i misunderstood something?
There is the code of the useCases used in the process:
public interface SendEmailUseCase {
EmailSendingResult execute(Command command);
record Command(
String sendToAddress,
String replyToAddress,
String ccAddress,
String bccAddress,
String fromAddress,
String subject,
String contentText,
List<EmailAttachment> attachments
) {}
}
@CustomLog
@Service
@RequiredArgsConstructor
public class SendEmailUseCaseHandler implements SendEmailUseCase {
private final JavaMailSender emailSender;
private final DecodeBase64FileIntoDataSourceUseCase decodeBase64FileIntoDataSourceUseCase;
@Override
public EmailSendingResult execute(Command command) {
try {
if (!MailConfig.IS_SENDING_ACTIVE)
return EmailSendingResult.emailNotSentWithoutError();
final MimeMessage messageToSent = prepareEmail(command);
log.info("Sending Email...");
emailSender.send(messageToSent);
log.info("Email with subject: " + messageToSent.getSubject() + " has been sent to: " +
Arrays.toString(messageToSent.getRecipients(Message.RecipientType.TO)));
return EmailSendingResult.emailSent();
} catch (CommonServicesException | MessagingException ex) {
log.info("Email with subject: " + command.subject() + " has not been sent");
log.catching(Level.ERROR, ex);
return EmailSendingResult.emailNotSentWithError(ex);
}
}
private MimeMessage prepareEmail(Command command) {
try {
log.info("Preparing email to send...");
final String mailFrom = command.fromAddress().isBlank() ? MailConfig.MAIL_FROM : command.fromAddress();
final MimeMessage message = emailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(splitAddresses(command.sendToAddress()));
message.setReplyTo(splitAddresses(command.replyToAddress()));
helper.setCc(splitAddresses(command.ccAddress()));
helper.setBcc(splitAddresses(command.bccAddress()));
helper.setFrom(mailFrom);
helper.setSubject(MimeUtility.encodeText(command.subject(), "utf-8", "B"));
message.setText(command.contentText(), "windows-1250","html");
if (command.attachments() == null)
return message;
for (EmailAttachment att : command.attachments()) {
final DataSource processedAtt = decodeBase64FileIntoDataSourceUseCase.execute(
new DecodeBase64FileIntoDataSourceUseCase.Command(att.fileName(), att.fileBase64())
);
helper.addAttachment(att.fileName(), processedAtt);
}
return message;
} catch (MessagingException | UnsupportedEncodingException ex) {
throw new CommonServicesException("Preparation of email message before sending failed", ex);
}
}
private InternetAddress[] splitAddresses(String addresses) throws AddressException {
return (addresses != null)
? InternetAddress.parse(addresses)
: new InternetAddress[0];
}
}
public interface DecodeBase64FileIntoDataSourceUseCase {
DataSource execute(Command command);
record Command(
String fileName,
String base64File
) {}
}
@Service
public class DecodeBase64FileIntoDataSourceUseCaseHandler implements DecodeBase64FileIntoDataSourceUseCase {
@Override
public DataSource execute(Command command) {
final byte[] fileSourceBytes = Base64.getDecoder().decode(command.base64File());
final ContentType type = getPartType(command.fileName());
return new ByteArrayDataSource(fileSourceBytes, type.getValue());
}
private ContentType getPartType(String fileName) {
final String fileExtension = FilenameUtils.getExtension(fileName);
return switch (fileExtension) {
case "pdf" -> ContentType.PDF;
default -> ContentType.TEXT_PLAIN;
};
}
}
I appreciate any help, because i have really no clue what could be wrong here.
Thanks in advance.
The problem was incorrect method used to set text using provided charset:
message.setText(command.contentText(), "windows-1250","html");
I solved it by replacing this line with:
helper.setText(command.contentText(), true);
and changing MimeMessageHelper
constructor like this:
final MimeMessageHelper helper = new MimeMessageHelper(message, true, "windows-1250");
there is the final code of the prepareEmail
method:
private MimeMessage prepareEmail(Command command) {
try {
log.info("Preparing email to send...");
final String mailFrom = command.fromAddress().isBlank() ? MailConfig.MAIL_FROM : command.fromAddress();
final MimeMessage message = emailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message, true, "windows-1250");
helper.setTo(splitAddresses(command.sendToAddress()));
message.setReplyTo(splitAddresses(command.replyToAddress()));
helper.setCc(splitAddresses(command.ccAddress()));
helper.setBcc(splitAddresses(command.bccAddress()));
helper.setFrom(mailFrom);
helper.setSubject(MimeUtility.encodeText(command.subject(), "utf-8", "B"));
helper.setText(command.contentText(), true);
if (command.attachments() == null)
return message;
for (EmailAttachment att : command.attachments()) {
final DataSource processedAtt = decodeBase64FileIntoDataSourceUseCase.execute(
new DecodeBase64FileIntoDataSourceUseCase.Command(att.fileName(), att.fileBase64())
);
helper.addAttachment(att.fileName(), processedAtt);
}
return message;
} catch (MessagingException | UnsupportedEncodingException ex) {
throw new CommonServicesException("Preparation of email message before sending failed", ex);
}
}