About
Jakarta Mail (previously known as JavaMail) is the basic / low level component of all email client implementation in Java.
It does not integrate a email server.
Articles Related
Highest Library component
The following library are based on JavaMail and cache the details implementation away
Client:
SMTP server:
Architecture
To send an email with Java mail:
- you create a Session object. It's a context object that is also responsible for the user authentication, message store control access and the transport protocol
- you create then an email message in this context that is composed of a content that may have multipart.
- and send it
The whole architecture and more details are available in the Specification documentation
Example
Simple
from the doc
Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom("[email protected]");
msg.setRecipients(Message.RecipientType.TO, "[email protected]");
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport.send(msg, "[email protected]", "my-password");
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
Multipart alternative (ie HTML otherwise text)
How to create a MIME multipart/alternative message.
final MimeMessage msg = new MimeMessage(session);
// create and fill the text message part
MimeBodyPart multiPartText = new MimeBodyPart();
multiPartText.setText(textBody, "utf-8","plain");
// create and fill the html message part
MimeBodyPart multiPartHtml = new MimeBodyPart();
multiPartHtml.setText(htmlBody, "utf-8","html");
// create the Multipart and its parts to it
Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(multiPartText);
mp.addBodyPart(multiPartHtml);
// add the Multipart to the message
msg.setContent(mp);