Creating and sending emails is very simple with Simple Java Mail; you don't need to know about the mailing RFC, MimeMessage or any other low
level javax.mail API. No anonymous inner classes needed and no large frameworks needed nor XML.
On top of that, Simple Java Mail will do some basic validation checks so that your email is always populated with enough data. It even verifies email addresses against RFC-2822 using the only complete rfc2822 validator in java in the world.
Simply create an Email, populate it with your data, create a Mailer and send the Email
instance. The mailer can be created with your own Session instance as well.
A Mailer instance is reusable.
Email email = new Email();
email.setFromAddress("Michel Baker", "m.baker@mbakery.com");
email.addRecipient("mom", "jean.baker@hotmail.com", RecipientType.TO);
email.addRecipient("dad", "StevenOakly1963@hotmail.com", RecipientType.TO);
email.setSubject("My Bakery is finally open!");
email.setText("Mom, Dad. We did the opening ceremony of our bakery!!!");
new Mailer("server", "25", "username", "password").sendMail(email);
The previous example becomes even more succinct by using the fluent API.
Email email = new EmailBuilder()
.from("Michel Baker", "m.baker@mbakery.com")
.to("mom", "jean.baker@hotmail.com")
.to("dad", "StevenOakly1963@hotmail.com")
.subject("My Bakery is finally open!")
.text("Mom, Dad. We did the opening ceremony of our bakery!!!")
.build();
new Mailer("server", "25", "username", "password").sendMail(email);
You can preconfigure a Mailer and use it many times.
Mailer inhouseMailer = new Mailer("server", "25", "username", "password");
inhouseMailer.sendMail(email);
inhouseMailer.sendMail(anotherEmail);
Or as preconfigured Spring bean:
<bean id="inhouseMailer" class="org.simplejavamail.mailer.Mailer">
<constructor-arg value="server" />
<constructor-arg value="25" />
<constructor-arg value="username" />
<constructor-arg value="password" />
</bean>
The default mode is to send emails synchronously, blocking execution until the email was processed completely and the STMP server send a succesful result.
You can also sent anyschronously in parallel or batches, or simply send in a fire-and-forget way. If an authenticated proxy is used, the proxy briding server is kept alive until the last email has been sent.
Depending on the SMTP server (and proxy server if used) this can greatly influence how fast emails are sent.
mailer.sendMail(email, true);
Refer to the configuration section on how to set the thread pool size default.
If you prefer to use your own preconfigured Session instance and still benefit from Simple Java Mail, you can!
Email email = new Email();
...
new Mailer(yourSession).sendMail(email);
Activating SSL or TLS is super easy. Just use the appropriate TransportStrategy enum.
Email email = new Email();
mailer.sendMail(email, TransportStrategy.SMTP_PLAIN); // default if omitted
mailer.sendMail(email, TransportStrategy.SMTP_SSL);
mailer.sendMail(email, TransportStrategy.SMTP_TLS);
Here's an example of SSL and TLS using gMail.
If you have two-factor login turned on, you need to generate an application specific password from your Google account.
new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);
You can add attachments very easily, but you'll have to provide the data yourself. Simple Java Mail accepts byte[]
and DataSource objects.
Email email = new Email();
email.addAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain"));
email.addAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain");
// ofcourse it can be anything: a pdf, doc, image, csv or anything else
email.addAttachment("invitation.pdf", new FileDataSource("invitation_v8.3.pdf"));
Embedding images is simple, but you have to add the placeholders in the HTML yourself.
Email email = new Email();
email.addEmbeddedImage("smiley", new FileDataSource("smiley.jpg"));
// this example is included in the demo package in MailTestApp.java
String base64String = "iVBORw0KGgoAAAANSUhEUgAAA ...snip";
email.addEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");
// the corresponding HTML should contain the placeholders
<p>Let's go!</p><img src='cid:thumbsup'><br/>
<p>Smile!</p><img src='cid:smiley'>
Sometimes you need extra headers in your email because your email server, recipient server or your email client needs it. Or perhaps you have a proxy or monitoring setup in between mail servers. Whatever the case, adding headers is easy.
Email email = new Email();
email.addHeader("X-Priority", 2);
email.addHeader("X-MC-GoogleAnalyticsCampaign", "halloween_sale");
email.addHeader("X-MEETUP-RECIP-ID", "71415272");
email.addHeader("X-my-custom-header", "foo");
In case you need to modify the internal Session object itself, because you need a tailored configuration that is supported by the underlying
javax.mail, that too is very easy.
Properties props = new Properties();
props.setProperty("mail.smtp.timeout", 30 * 1000);
props.setProperty("mail.smtp.connectiontimeout", 10 * 1000);
Mailer mailer = new Mailer();
mailer.applyProperties(props);
For emergencies, you can also get a hold of the internal Session instance itself. You should never need this however and if you do it means Simple Java Mail failed to simplify the configuration process for you. Please let us know how we can help alleviate this need.
Mailer mailer = new Mailer();
Session session = mailer.getSession();
// do your thing with session
Simple Java Mail also supports signing with DKIM domain keys. It uses java-utils-mail-dkim (dependency packaged along) to perform the DNS DKIM record check on the given domain.
Email signedEmail = new Email();
signedEmail.signWithDomainKey(
privateKey byte[] / File / InputStream,
"your_domain.org",
"your_selector");
new Mailer().sendMail(signedEmail);
Simple Java Mail can validate your email addresses. It's not just a simple regex check, but a complete and robust full validation against RFC-2822. It does this by including email-rfc2822-validator in the library.
EmailAddressValidator.isValid("your_address@domain.com",
EmailAddressCriteria.RFC_COMPLIANT);
// or, fine-tuned to be less strict:
EmailAddressValidator.isValid("your_address@domain.com",
of(ALLOW_QUOTED_IDENTIFIERS, ALLOW_PARENS_IN_LOCALPART));
If for some reason you need a MimeMessage, you can still benefit from the easy API Simple Java Mail offers. Behold.
Email email = new Email()
// populate email, the builder is great for this
// then
MimeMessage message = Mailer.produceMimeMessage(email);
// or
MimeMessage message = Mailer.produceMimeMessage(email, yourSession);
If you already have a MimeMessage, you can easily convert it into a ready-to-use Email instance, complete with embedded images and attachment intact.
MimeMessage mimeMessage = ...;
Email email = new Email(mimeMessage);
new Mailer().sendMail(email);
Simple Java Mail supports sending emails through a proxy. It is also the only java mailing framework in the world that supports sending emails through authenticated proxies.
The reason for this is that the underlying native Javax Mail framework supports anonymous SOCKS5 proxies, but not authenticated proxies.
To make this work with authentication, Simple Java Mail uses a trick: it sets up a temporary anonymous proxy server for Javax Mail to connect to and then relays the connection to the target proxy performing the authentication outside of Javax Mail.
This temporary server is referred to as the Proxy Bridging Server.
// anonymous proxy
new Mailer(serverConfig, new ProxyConfig("proxy.host.com", 1080));
// authenticated proxy
new Mailer(serverConfig, new ProxyConfig("proxy.host.com", 1080, "proxy username", "proxy password"));
Refer to the configuration section on how to set proxy server defaults and the port on which the proxy bridge runs.