2015-11-12 86 views
1

我在使用java郵件(1.4.6)在java中通過電子郵件發送附件時遇到了問題。看起來,當我附加任何類型的文檔併發送它時,收件人將以純文本格式在文本中獲取文件。而不是,你猜對了,發送整個文件就像你期望的那樣,並且身體不會受到干擾。在主體中以純文本形式發送的java電子郵件附件

代碼

try 
    { 

     // Create a message 
     MimeMessage message = new MimeMessage(session); 
     message.setFrom(new InternetAddress(username)); 
     message.setRecipients(Message.RecipientType.TO, 
       InternetAddress.parse(Compose.to)); 
     message.setSubject(Compose.subject); 
     //message.setText(Compose.body); 
     //If there are no CC's then skip it. This if seemed to decrease send time. 
     if(Compose.cc != null) 
     { 
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(Compose.cc)); 
      message.saveChanges(); 
     } 
     else 
      message.saveChanges(); 

     /* 
     * For adding the attached file to the email. This time the if 
     * statement is used to stop the email attachment process if there 
     * is none. Other wise due to the way I've set it up it'll try to 
     * send file path and file name as null, and we fail an otherwise valid email. 
     */ 

     if(Compose.filename != null) 
     { 
      String file = Compose.filepath; 
      String fileName = Compose.filename; 

      Multipart multipart = new MimeMultipart(); 
      BodyPart messageBodyPart = new MimeBodyPart(); 
      DataSource source = new FileDataSource(file); 
      messageBodyPart.setDataHandler(new DataHandler(source)); 
      messageBodyPart.setFileName(fileName); 
      multipart.addBodyPart(messageBodyPart); 

      BodyPart messageBodyPart2 = new MimeBodyPart(); 
      messageBodyPart2.setText(Compose.body); 
      multipart.addBodyPart(messageBodyPart2); 

      message.setContent(multipart); 
     } 
     else 
     { 
      message.setText(Compose.body); 
      message.saveChanges(); 
     } 

     //Send the message by javax.mail.Transport .    
     Transport tr = session.getTransport("smtp");   // Get Transport object from session   
     tr.connect(smtphost, username, password);    // We need to connect 
     tr.sendMessage(message, message.getAllRecipients()); // Send message 

     //Notify the user everything functioned fine. 
     JOptionPane.showMessageDialog(null, "Your mail has been sent."); 

    } 

在這個我記得是如何FileDataSource()是一個重載錄取口供的字符串或文件類型作爲參數思考,試圖既我得到了相同的結果,但我會嘗試多用現在是文件類型。

編輯:經過更多的測試後,我注意到有時文件不會出現在發送時身上的任何東西。

回答

1

對於每個零件,您必須爲set dispositionPart.INLINE爲正文,Part.ATTACHMENT爲附件。 attachFile方法將爲你做到這一點。避免JavaMail 1.4.6支持最新版本,或至少使用JavaMail 1.4.7,其中包含JavaMail 1.4.6已知問題的修復程序。

相關問題