此发送邮件功能适用于所有类型的文件,如.html,.txt作为附件。但是当我尝试将.zip文件夹作为附件发送时,它会终止。
public void sendmail(){
System.out.println("started function");
String from = "amritharajeevan.77@gmail.com";
// Sender's email ID needs to be mentioned
String to = "amritha2.rajeevan@aricent.com";
final String username = "amritharajeevan.77";//change accordingly
final String password = "vivekrajeevan";//change accordingly
// Assuming you are sending email through gmail.com
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Server Error");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Server"+" " +servererror+ " " +" is unreachable. Please check the logs.");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "/Users/aricent/Desktop/amritha/seetest/May6.zip";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("sent start function");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
所以我不知道该怎么办?请告诉我我的代码应该改变哪些部分。我试过.txt和.html文件。它工作正常。
答案 0 :(得分:0)
查看Apache Commons Email项目,该项目将清理大量此类代码并简化附件。
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(zipFile);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Zip File");
attachment.setName("myfiles.zip");
MultiPartEmail email = new MultiPartEmail();
email.attach(attachment);