【问题标题】:Sending an email with an attachment using javamail API使用 javamail API 发送带有附件的电子邮件
【发布时间】:2013-06-13 22:33:02
【问题描述】:

我正在尝试发送带有 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();
    } 
 }

我该如何纠正这个问题?

【问题讨论】:

    标签: java email datasource jakarta-mail transport


    【解决方案1】:

    电子邮件由标题和正文部分组成。

    标题部分将包含 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

    【讨论】:

      【解决方案2】:

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

      因此,您必须通过转到帐户设置、密码部分来更改安全级别并禁用验证码安全设置或降低您的安全级别取决于旧的或最新的 gmail 应用程序。

      如果您想通过 gmail 访问本地目录来发送附件,那么您需要使用 File 对象设置为 DataSource 构造函数类,如下面的程序所示。这将避免“访问被拒绝”异常。

      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);
              }
          }
      }
      

      【讨论】:

        【解决方案3】:
        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);
                }
            }
        }
        

        【讨论】:

          【解决方案4】:

          你可以试试这样的:

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

          查看更多详情:Send email via SMTP with attachment, plain/text, and text/hml

          【讨论】:

            【解决方案5】:

            请参阅debugging tips 的 JavaMail 常见问题解答。特别是,协议跟踪将告诉您更多关于每种情况下发生的情况。在那里,您还可以找到使用 GMail 的提示。

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

            【讨论】:

              猜你喜欢
              • 2019-05-28
              • 2015-10-27
              • 2017-01-07
              • 1970-01-01
              • 2016-08-23
              • 1970-01-01
              • 2018-12-18
              • 2016-09-22
              相关资源
              最近更新 更多