【发布时间】:2018-02-02 17:00:00
【问题描述】:
我正在努力使用 Javamail,我正在尝试发送带有 zip 文件的电子邮件。 当我尝试发送没有附件的邮件时,它工作正常,但是当我添加 zip 时,邮件不再发送。我没有错误...
我的代码:
LOGGER.info("########################### Send Email with attachement to " + destination + " Start ######################");
//Config smtp mail
Properties props = new Properties();
props.put("mail.smtp.host", getSmtpHost());
props.put("mail.smtp.socketFactory.port", getSmtpsocketFactoryPort());
props.put("mail.smtp.socketFactory.class", getSmtpsocketFactoryClass());
props.put("mail.smtp.auth", getSmtpAuth());
props.put("mail.smtp.port", getSmtpPort());
//instance Session
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUsername(), getPassword());
}
});
try {
//construction objet mail
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getFromAddress()));
//Send Email to Addresse
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination));
message.setSubject(objet);
message.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(contenu);
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
String fileName = attachementPath + attachementName;
File file = new File (fileName);
attachmentBodyPart.attachFile(file);
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
//send Email
Transport.send(message);
LOGGER.info("########################### Send email with attachement to " + destination + " End ########################### ");
} catch (MessagingException e) {
LOGGER.error("Error when send email to " + destination);
throw new RuntimeException(e);
}
我尝试了很多东西,我可能很累找到错误xD
感谢您的帮助!!
更新:感谢 jmehrens,我找到了问题所在。我的邮件服务器不允许 .zip
【问题讨论】:
-
"当我添加 zip 时,邮件不再发送。"看起来很可疑,你可能在某个地方有一些例外。顺便说一句,
new StringBuilder(attachementPath + attachementName).toString()有什么意义??? -
也许stackoverflow.com/q/17097806/180100 可以提供帮助
-
您的邮件服务器是否有不允许以
.zip结尾的文件的策略?您应该能够仅使用邮件客户端或重命名扩展来测试它。 -
@jmehrens 谢谢!我只是尝试使用 .txt 并且它有效!这是我第一次使用 Javamail,所以我假设我犯了一个错误......
-
@RC。我做了一个 StringBuilder 因为我累了,我认为 String = String + String 不起作用......
标签: java email jakarta-mail attachment