0
我要發送帶附件的電子郵件。郵件的正文是正確的,但附件是空的。附件的大小正在顯示。那麼,怎麼了?用Java-Mail發送附件無法正常工作
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText(
"Prozess vom " + new SimpleDateFormat("dd.MM.yyyy").format(new Date()) + " erfolgreich beendet");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Part two is attachment
BodyPart attachement = new MimeBodyPart();
File fi = new File("C:" + File.separator + "Logdatei_Auto" + File.separator + "logdatei.txt");
String filename = fi.getAbsolutePath();
String name = fi.getName();
javax.activation.DataSource source = new FileDataSource(filename);
attachement.setDataHandler(new DataHandler(source));
attachement.setFileName(name);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachement);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
UPDATE
終於將其與下面的代碼工作:
File filename = new File("logdatei.pdf");
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
// Create a default MimeMessage object.
// Create a default MimeMessage object.
try {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("*******"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("*******"));
message.setSubject("Test");
message.setSentDate(new Date());
//
// Set the email message text.
//
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText("Blah...");
//
// Set the email attachment file
//
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(filename) {
@Override
public String getContentType() {
return "application/octet-stream";
}
};
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(filename.getName());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
感謝@所有
THX,但問題仍然存在 – user3515460
@ user3515460嘗試通過'file'到'FileDataSource'代替fileName'的'。 – eatSleepCode
@ user3515460是否將'File'傳遞給'FileDataSource'而不是'fileName'工作? – eatSleepCode