尝试发送带有文件附件的电子邮件时出现错误:
javax.mail.internet.ParseException: Expected '/', got files
at javax.mail.internet.ContentType.<init>(ContentType.java:102)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1331)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1354)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075)
at javax.mail.Transport.send(Transport.java:123)
下面的代码:
@Override
public void execute(String filePath) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(GMAIL_ACCOUNT, GMAIL_PASSWORD);
}
});
//We create a new mail message
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("esombugma@gmail.com"));
//We constitute the list of recipients
List<InternetAddress> recipList = new ArrayList<>();
for(String address : this.getRecipients()) {
recipList.add(new InternetAddress(address));
}
InternetAddress[] iaTab = new InternetAddress[recipList.size()];
iaTab = recipList.toArray(iaTab);
msg.setRecipients(Message.RecipientType.TO, iaTab);
msg.setSubject(this.getSubject());
msg.setSentDate(new Date());
//Create multi-part
Multipart multipart = new MimeMultipart();
//Create a message part
MimeBodyPart msgBodyPart = new MimeBodyPart();
msgBodyPart.setContent(this.getMessage(), this.getSubject());
multipart.addBodyPart(msgBodyPart);
//Adds attachment
if((new File(filePath)).exists()) {
MimeBodyPart attachment = new MimeBodyPart();
try {
attachment.attachFile(new File(filePath));
} catch (IOException ex) {
Logger.getLogger(EmailSender.class.getName()).log(Level.SEVERE, null, ex);
}
attachment.setFileName((new File(filePath)).getName());
multipart.addBodyPart(attachment);
}
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException ex) {
Logger.getLogger(EmailSender.class.getName()).log(Level.SEVERE, null, ex);
}
}
生成文件的代码在这里:
public String getMissingReportName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhh");
return "C://Report//Report_" + sdf.format(new Date()) + ".xls";
}
那么一个示例报告文件应该是:Report_20130512
例如。
有人可以向我解释这个错误的根源是什么。谢谢你。