使用javamail API发送带附件的电子邮件

我正在尝试使用Java发送带有附件的电子邮件。

当我发送没有附件的电子邮件时,我收到了电子邮件,但是当我添加附件时,我没有收到任何内容,我也没有收到任何错误消息。

这是我正在使用的代码:

public void send () throws AddressException, MessagingException{ //system properties Properties props = new Properties(); props.put("mail.smtp.localhost", "localhost"); props.put("mail.smtp.host",Configurations.getInstance().email_serverIp); /* * create some properties and get the default Session */ session = Session.getDefaultInstance(props, null); //session Session session = Session.getInstance(props, null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("zouhaier.mhamdi@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zouhaier.mhamdi@gmail.com")); message.setSubject("Testing Subject"); message.setText("PFA"); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); generateCsvFile("/tmp/test.csv"); messageBodyPart = new MimeBodyPart(); String file = "/tmp/test.csv"; String fileName = "test.csv"; DataSource source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); System.out.println("Sending"); Transport.send(message); System.out.println("Done"); } private static void generateCsvFile(String sFileName) { try { FileWriter writer = new FileWriter(sFileName); writer.append("DisplayName"); writer.append(','); writer.append("Age"); writer.append(','); writer.append("YOUR NAME"); writer.append(','); writer.append('\n'); writer.append("Zou"); writer.append(','); writer.append("26"); writer.append(','); writer.append("zouhaier"); //generate whatever data you want writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } } 

我怎么能纠正这个?

  1. 禁用您的反病毒

因为你有这样的警告

警告消息形成防病毒

试试这个代码……它可以帮助你….

 public class SendMail { public SendMail() throws MessagingException { String host = "smtp.gmail.com"; String Password = "............"; String from = "XXXXXXXXXX@gmail.com"; String toAddress = "YYYYYYYYYYYYY@gmail.com"; String filename = "C:/SendAttachment.java"; // Get system properties Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtps.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, toAddress); message.setSubject("JavaMail Attachment"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Here's the file"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); try { Transport tr = session.getTransport("smtps"); tr.connect(host, from, Password); tr.sendMessage(message, message.getAllRecipients()); System.out.println("Mail Sent Successfully"); tr.close(); } catch (SendFailedException sfe) { System.out.println(sfe); } } public static void main(String args[]){ try { SendMail sm = new SendMail(); } catch (MessagingException ex) { Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex); } } } 

有关调试提示,请参阅JavaMail FAQ。 特别是,协议跟踪将告诉您更多关于每种情况下发生了什么的信息。 当你在那里时,你会发现使用GMail的提示。

如果唯一的区别只是添加附件,那么它似乎不太可能是身份validation问题。 您可能会收到一个您没有注意到的exception,因为您的send方法被声明为抛出MessagingException。

您可以尝试以下方法:

 File f = new File(file); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(f); multipart.addBodyPart(attachmentPart); 

有关详细信息,请参阅: 通过SMTP发送带附件,纯文本/文本和文本/ hml的电子邮件

您可以使用用户名和密码访问Gmail。 但gmail帐户将拒绝访问。

因此,您必须通过转到帐户设置,密码部分并取消validation代码安全设置或降低安全级别来更改安全级别,具体取决于旧的或最新的Gmail应用程序。

如果要通过访问本地目录通过gmail发送附件,则需要按照以下程序中的指示将File对象设置为DataSource构造函数类。 这将避免“拒绝访问”exception。

 import java.io.File; import java.io.IOException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class EmailApp { public static void main(String[] args)throws IOException { final String username = "mygmail@gmail.com"; final String password = "mypassword"; 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); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("dharmendrasundar@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("dharmendrasundar@gmail.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); message.setSubject("Testing Subject"); message.setText("PFA"); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart = new MimeBodyPart(); String attachmentPath = "C:/TLS/logs/26-Mar-2015"; String attachmentName = "LogResults.txt"; File att = new File(new File(attachmentPath), attachmentName); messageBodyPart.attachFile(att); DataSource source = new FileDataSource(att); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachmentName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); System.out.println("Sending"); Transport.send(message); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } } 

电子邮件消息由标题和正文段组成。

标题部分将包含from,to和subject。

身体包含附件。 要支持在正文中携带附件,请键入Multipart

Multipart对象包含多个部分,其中每个部分都表示为一种BodyPart其子类MimeBodyPart可以将文件作为其内容。

要在邮件正文中添加附件, MimeBodyPart类提供了一些方便的方法。

 // JavaMail 1.3 MimeBodyPart attachPart = new MimeBodyPart(); String attachFile = "D:/test.pdf"; DataSource source = new FileDataSource(attachFile); attachPart.setDataHandler(new DataHandler(source)); attachPart.setFileName(new File(attachFile).getName()); multipart.addBodyPart(attachPart); // JavaMail 1.4 MimeBodyPart attachPart = new MimeBodyPart(); String attachFile = "D:/test.pdf"; attachPart.attachFile(attachFile); multipart.addBodyPart(attachPart); 

有关更多信息,请参阅此链接。

https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm