2013-01-27 6 views
6

Quando invio gli allegati, non visualizzo il messaggio del corpo (message.setText (this.getEmailBody());) nell'email. Senza allegati, l'e-mail appare con il messaggio del corpo. Le email vengono inviate a un account Gmail. Qualche indizio perché sta succedendo questo?Il messaggio corpo non viene visualizzato quando si inviano allegati

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

risposta

9

è necessario utilizzare il seguente:

  // 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

questo non funziona. – nidis

+0

L'intero metodo. Per me funziona. Controlla se mi sono perso qualcosa nello snippet. Ecco l'intero [metodo] (http://ideone.com/7ByeQs). – Srinivas

+2

hai ragione. Ha funzionato anche per me. Penso che il problema fosse in queste due righe: MimeBodyPart messageBodyPart = new MimeBodyPart(); \t \t \t messageBodyPart.attachFile (this.attachmentsDir.concat (file.trim())); Quindi ho dovuto farlo a modo tuo. Grazie per il tuo aiuto;) – nidis

1

è necessario separare in 2 parti per fare questo:

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