2013-01-27 33 views
6

Khi tôi gửi tệp đính kèm, tôi không thấy thông báo nội dung (message.setText (this.getEmailBody());) trong email. Không có tệp đính kèm, email sẽ xuất hiện cùng với thông báo nội dung. Email được gửi đến một tài khoản gmail. Bất kỳ đầu mối tại sao điều này xảy ra?Thông báo nội dung không xuất hiện khi gửi tệp đính kèm

 MimeMessage message = new MimeMessage(session_m);  
     message.setFrom(new InternetAddress(this.getEmailSender())); 
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.getEmailRecipient())); 
     message.setSubject(this.getEmailSubject()); 
     message.setText(this.getEmailBody()); //This won't be displayed if set attachments 

     Multipart multipart = new MimeMultipart(); 

     for(String file: getAttachmentNameList()){ 
      MimeBodyPart messageBodyPart = new MimeBodyPart(); 
      messageBodyPart.attachFile(this.attachmentsDir.concat(file.trim())); 
      multipart.addBodyPart(messageBodyPart); 

      message.setContent(multipart); 
     } 


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

Trả lời

9

Bạn cần phải sử dụng như sau:

  // Create the message part 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     // Fill the message 
     messageBodyPart.setText(body); 
     messageBodyPart.setContent(body, "text/html"); 

     Multipart multipart = new MimeMultipart(); 
     multipart.addBodyPart(messageBodyPart); 
     //Add the bodypart for the attachment(s) 
     // Send the complete message parts 
     message.setContent(multipart); //message is of type - MimeMessage 
+0

này không hoạt động. – nidis

+0

Toàn bộ phương pháp. Nó làm việc cho tôi. Kiểm tra xem tôi có bỏ sót gì đó trong đoạn trích không. Đây là toàn bộ [phương pháp] (http://ideone.com/7ByeQs). – Srinivas

+2

bạn nói đúng. Nó cũng làm việc cho tôi. Tôi nghĩ rằng vấn đề nằm trong hai dòng đó: MimeBodyPart messageBodyPart = new MimeBodyPart(); \t \t \t messageBodyPart.attachFile (this.attachmentsDir.concat (file.trim())); Vì vậy, tôi phải làm theo cách của bạn. Cảm ơn sự giúp đỡ của bạn;) – nidis

1

Bạn cần phải tách biệt thành 2 phần để làm điều này:

 Multipart multipart = new MimeMultipart(); 

     // content part 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     messageBodyPart.setText(content); 
     messageBodyPart.setContent(content, "text/html"); 
     multipart.addBodyPart(messageBodyPart); 

     BodyPart attachmentPart = new MimeBodyPart(); 
     DataSource source = new FileDataSource(file); 
     attachmentPart.setDataHandler(new DataHandler(source)); 
     attachmentPart.setFileName(file.getName()); 
     multipart.addBodyPart(attachmentPart); 
Các vấn đề liên quan