MimeMessageHelper.addAttachment()无法给MimeMessage添加附件求助
问题排查与解决方案
核心问题:直接调用MimeMessage.setText()覆盖了多部件邮件结构
你在prepareEmail方法中创建了支持多部件的MimeMessageHelper(第二个参数传true),但之后直接调用message.setText(command.contentText(), "windows-1250","html"),这会直接替换邮件的内容结构为单一文本部件,覆盖掉MimeMessageHelper正在构建的包含附件的多部件(MimeMultipart)结构,导致之前添加的附件被完全忽略。
修复方案
将直接操作MimeMessage的setText方法,改为使用MimeMessageHelper提供的setText方法:
// 替换原有的 message.setText(...) 代码 helper.setText(command.contentText(), "windows-1250", true);
MimeMessageHelper.setText()的参数对应关系:
- 第一个参数:邮件内容文本
- 第二个参数:字符编码
- 第三个参数:是否为HTML格式(
true表示内容是HTML类型)
其他验证点
- 确认
command.attachments()不为空且包含有效的附件数据 - 验证
DecodeBase64FileIntoDataSourceUseCase返回的ByteArrayDataSource是否正常:可以打印processedAtt.getContentType()和processedAtt.getInputStream().available(),确认文件解码后内容有效 - 确保
MimeMessageHelper实例在添加附件过程中没有被重新创建或覆盖
修复后的关键代码片段
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")); // 使用helper设置文本内容,避免覆盖多部件结构 helper.setText(command.contentText(), "windows-1250", 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); } }
内容的提问来源于stack exchange,提问作者K0cur
相关产品推荐
相关产品推荐

