2014-05-23 57 views
0

我正在嘗試發送帶附件的電子郵件。整個事情工作正常,除了附件發送的部分發送沒有擴展名的附件。如何發送郵件的附件在發送時附有擴展名

例如,發送File.rar將收到file

這是怎麼了,我這樣做:

public class EmailSender { 

    public static void main(String[] args) { 
     String TO = "[email protected]"; 
     String host = "smtp.gmail.com"; 
     String port = "465"; 
     String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
     Properties mailConfig = new Properties(); 
     mailConfig.put("mail.smtp.host", host); 
     mailConfig.put("mail.smtp.socketFactory.port", port); 
     mailConfig.put("mail.smtp.socketFactory.class", SSL_FACTORY); 
     mailConfig.put("mail.smtp.auth", "true"); 
     mailConfig.put("mail.smtp.port", port); 

     Session session = Session.getDefaultInstance(mailConfig, 
      new Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication("Username", "Password"); 
       } 
      }); 

     try { 
      MimeMessage message = new MimeMessage(session); 
      message.setFrom(new InternetAddress("[email protected]")); 
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO)); 
      message.setSubject("Email with Attachment SUBJECT"); 

      BodyPart messageBodyTxt = new MimeBodyPart(); 
      messageBodyTxt.setText("Email with Attachment BODY"); 

      MimeBodyPart messageBodyAttachment = new MimeBodyPart(); 
      String filePath = "D:\\Unlocker1.9.2.rar"; 
      DataSource source = new FileDataSource(filePath); 
      messageBodyAttachment.setDataHandler(new DataHandler(source)); 
      messageBodyAttachment.setFileName("Unlocker1.9.2" + ".rar"); 

      Multipart multipart = new MimeMultipart(); 
      multipart.addBodyPart(messageBodyTxt); 
      multipart.addBodyPart(messageBodyAttachment); 
      message.setContent(multipart); 

      Transport.send(message); 
      System.out.println("Email sent successfully"); 

     } catch (MessagingException e) { 
      throw new RuntimeException(e); 
     } 

    } 
} 
+0

content-disposition。 – bmargulies

回答

0

使用從評論的意見,正確的方法是setDisposition,你會設置對於有問題的MimeBodyPart。因此,使用上面的代碼,可以這樣做:

messageBodyAttachment.setDisposition(javax.mail.Part.ATTACHMENT);