我正在设法保存包含正文、主题等的简单消息。但是,我无法保存多部分消息。我在之前和之后登录appendMessages
,但注意到第二个日志不存在。有趣的是,我根本没有任何例外被解雇。我完全不知道这里出了什么问题。
这是我的Java代码:
Store store = null;
Folder folder = null;
String folderName = "sentbox";
try {
Session session = prepareSession(MailProtocols.IMAP, kid);
store = session.getStore("imap");
store.connect(myHost, user.getLogin(), user.getPassword());
folder = store.getFolder(folderName);
if (folder == null || !folder.exists()) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
MimeMessage mimeMessage = new MimeMessage(session);
Address[] to = null;
if(msg.getTo() != null) { // msg is an instance of custom message class, nothing special there
int msgSize = msg.getTo().size();
to = new InternetAddress[msgSize];
for (int i = 0; i < msgSize; i++) {
to[i] = new InternetAddress(msg.getTo().get(i));
}
}
mimeMessage.setRecipients(RecipientType.TO, to);
mimeMessage.setSentDate(new Date(System.currentTimeMillis()));
mimeMessage.setSubject(msg.getSubject());
if (msg.getFiles() != null) {
MimeMultipart mp = new MimeMultipart();
MimeBodyPart newPart = new MimeBodyPart();
newPart.setText(msg.getBody());
mp.addBodyPart(newPart);
for (MultipartFile multipartFile : msg.getFiles()) {
try {
newPart = new MimeBodyPart(); // create new part to each files
newPart.addHeader("My-File-Type", multipartFile.getContentType());
File tmpFile = File.createTempFile("newAttachment", ".tmp");
multipartFile.transferTo(tmpFile);
FileDataSource fds = new FileDataSource(tmpFile);
newPart.setDataHandler(new DataHandler(fds));
newPart.setFileName(multipartFile.getOriginalFilename());
newPart.setDisposition(Part.ATTACHMENT);
mp.addBodyPart(newPart);
tmpFile.deleteOnExit();
} catch (IOException e) {
logger.debug("Can not create temp file ===========>");
e.printStackTrace();
}
}
mimeMessage.setContent(mp);
mimeMessage.saveChanges();
} else {
mimeMessage.setText(msg.getBody());
}
folder.appendMessages(new Message[] {mimeMessage});
Message[] allMessages = folder.getMessages();
UIDFolder uidFolder = (UIDFolder) folder;
long savedMsgId = uidFolder.getUID(allMessages[allMessages.length - 1]);
logger.info("savedMsgId",savedMsgId + "") //cannot get this output at all
} catch (Exception e) {
logger.error(e);
} finally {
closeMailStore(store, folder); // just simple method which closes the store
}
我正在使用 Apache James 3.0.4。欢迎任何方法