MimeMessageHelper.addAttachment() method does not add attachment to the MimeMessage

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
) {}
}
</code>
<code>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 ) {} } </code>
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
    ) {}
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@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];
}
}
</code>
<code>@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]; } } </code>
@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];
    }
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public interface DecodeBase64FileIntoDataSourceUseCase {
DataSource execute(Command command);
record Command(
String fileName,
String base64File
) {}
}
</code>
<code>public interface DecodeBase64FileIntoDataSourceUseCase { DataSource execute(Command command); record Command( String fileName, String base64File ) {} } </code>
public interface DecodeBase64FileIntoDataSourceUseCase {

    DataSource execute(Command command);

    record Command(
            String fileName,
            String base64File
    ) {}
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@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;
};
}
}
</code>
<code>@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; }; } } </code>
@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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật