![](/img/trans.png)
[英]Send email with javax.mail using an existing InputStream as attachment content
[英]Java - Change the name of email attachment using javax.mail library
這是我目前的代碼。 它正確發送帶有附件的電子郵件,但發送的附件的文件名是我計算機上文件的完整路徑。 我希望它顯示為文件名(即“name_of_file.zip”而不是“/Users/MyUser/Desktop/name_of_file.zip”)。 有沒有辦法做到這一點?
public void sendMailWithAttachments () {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }});
String msgBody = "Body of email";
String fileAttachment = "/Users/MyUser/Desktop/name_of_file.zip";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("me@email.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("person@email.com"));
msg.setSubject("Email Subject!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(msgBody);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException e) {
System.out.println(e);
} catch (MessagingException e) {
System.out.println(e);
}
}
更改: messageBodyPart.setFileName(fileAttachment);
to: messageBodyPart.setFileName(new File(fileAttachment).getName());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.