When I send attachments, I don't see the body message (message.setText(this.getEmailBody());) in the email. Without attachments, the email appears with the body message. Emails are sent to a gmail account. Any clue why is this 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");
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
You need to separate into 2 parts to do this:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With