When using Javamail to send mail the Message-ID gets set when the message is actually sent. If you want to provide your own Message-ID then you need to subclass MimeMessage. You can then use that subclass to create your message.
public class CustomMimeMessage extends MimeMessage {
public CustomMimeMessage(Session session) {
super(session);
}
@Override
protected void updateMessageID() throws MessagingException {
setHeader("Message-ID", "objects-message-id");
}
}
written by objects
\\ tags: javamail, Message-ID, MimeMessage
When specifying an email address using JavaMail you can not only specify actual email address of the person, but also their name if required. The InternetAddress class is used to represent an email address which includes support for specifying both the email address and the personal name.
There are two ways this can be done, firstly the RFC822 address syntax can be used to specify both in one string.
message.setFrom(new InternetAddress("Joe Smith <joe@acme.com>"));
Or alternatively a constructor is available to specify the two separately
message.setFrom(new InternetAddress("joe@acme.com", "Joe Smith"));
written by objects
\\ tags: javamail, mail, sender
Multipart emails can be used to send html content with JavaMail. If you want to use images in the html content you can either specify the url of the image on an external server, or you can embed the image in the email itself.
To embed an image in your mail you need to assign it a cid, which you can then reference in your html img tag. Here is an example that demonstrates embedding an image and use of cid.
Properties sessionProperties = System.getProperties();
sessionProperties.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(sessionProperties, null);
// Create message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
to, false));
message.setSubject(subject);
// Add html content
// Specify the cid of the image to include in the email
String html = "<html><body><b>Test</b> email <img src='cid:my-image-id'></body></html>";
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");
mp.addBodyPart(htmlPart);
// add image in another part
MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath);
imagePart.setDataHandler(new DataHandler(fds));
// assign a cid to the image
imagePart.setHeader("Content-ID", "my-image-id");
mp.addBodyPart(imagePart);
message.setContent(mp);
// Send the message
Transport.send(message);
written by objects
\\ tags: html, image, javamail, multipart