嗨,我是 JavaMail 的新手。
我想上传一个文件作为附件。它只存储文件名。
文件成功地附加了文件名,而不是该文件的内容。
如何解决它。提前致谢...
我尝试了以下代码:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddr));
if (subject == null) {
message.setSubject("");
} else {
message.setSubject(subject);
}
if (attachedFile == null || attachedFile.equalsIgnoreCase("")) {
if (content == null) {
message.setText("");
} else {
message.setText(content);
}
} else {
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
if (content == null) {
messageBodyPart.setText("");
} else {
messageBodyPart.setText(content);
}
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
// messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(
attachedFile.getBytes("UTF-8"),
"application/octet-stream");
messageBodyPart = new MimeBodyPart();
// DataSource source = new FileDataSource(attchedFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachedFile);
// messageBodyPart.setHeader("Content-ID", "image/*");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
Transport.send(message);