For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail