我正在尝试修改现有的 MimeMessage 正文部分。我想过滤某些链接。你们中有人知道为什么即使正文部分内容接缝要更改,消息仍使用旧内容发送吗?是否有一些缓存正在进行?知道如何解决这个问题吗?
这是我的代码:
public void resend(InputStream data) throws Exception {
Session mailSession = createMailSession();
//mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession, data);
Object content = message.getContent();
if (content.getClass().isAssignableFrom(MimeMultipart.class)) {
MimeMultipart mimeMultipart = (MimeMultipart) content;
for (int i = 0; i < mimeMultipart.getCount(); i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.getContentType().startsWith("text/plain")) {
String cnt = updateContent((String) bodyPart.getContent());
System.out.println("ContentType = " + bodyPart.getContentType());
System.out.println("Content = " + cnt);
bodyPart.setContent(cnt, bodyPart.getContentType());
} else if (bodyPart.getContentType().startsWith("text/html")) {
String cnt = updateContent((String) bodyPart.getContent());
System.out.println("ContentType = " + bodyPart.getContentType());
System.out.println("Content = " + cnt);
bodyPart.setContent(cnt, bodyPart.getContentType());
}
}
} else {
String cnt = updateContent((String) message.getContent());
System.out.println("ContentType = " + message.getContentType());
System.out.println("Content = " + cnt);
message.setContent(cnt, message.getContentType());
}
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
private String updateContent(String cnt) {
return cnt.replace("www.xyz.pl", "www.new-xyz.pl");
}
输入流“数据”包含原始消息。
有什么想法吗?
提前致谢....
最佳答案
您需要在 MimeMessage 上调用 saveChanges()(据我所知应该足够了),另请参阅:api-doc MimeMessage#saveChanges() :
Updates the appropriate header fields of this message to be consistent with the message's contents. If this message is contained in a Folder, any changes made to this message are committed to the containing folder.
If any part of a message's headers or contents are changed, saveChanges must be called to ensure that those changes are permanent. Otherwise, any such modifications may or may not be saved, depending on the folder implementation.
关于java - 如何修改现有的 Java 邮件 MimeMessage 正文部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7674775/