Body message does not appear when sending attachments

When I send attachments, I do not see the body message (message.setText (this.getEmailBody ());) in the email. Without attachments, an email message appears with a body message. Emails are sent to your gmail account. Any clues why this is happening?

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"); 
+6
source share
2 answers

You need to use the following:

  // 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 
+9
source

To do this, you need to divide into 2 parts:

  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); 
+1
source

All Articles