Send Mail via Java

I recently needed to send an email via Java. This was the first time i tried to do this, so I’ll post the code here. Maybe someone can use this one day.

First of all, you need to get JavaMail library here:

Then you can create a class called “Mail” or “MailService”. Then paste the following code:

import java.util.Properties;
 import javax.mail.Authenticator;
 import javax.mail.Message;
 import javax.mail.MessagingException;
 import javax.mail.PasswordAuthentication;
 import javax.mail.Session;
 import javax.mail.Transport;
 import javax.mail.internet.AddressException;
 import javax.mail.internet.InternetAddress;
 import javax.mail.internet.MimeMessage;

public class Mail {
 private static final String EMAIL = "";
 private static final String PASSWORD = "supersecretpassword";
 private static final String USERNAME = "totallysillyusername";
 private static final int SMTP_PORT = 25;
 private static final String SMTP_HOST =";

public static void send(String recipient, String subject, String text) throws AddressException, MessagingException {
 Properties properties = System.getProperties();
 properties.setProperty("", SMTP_HOST);
 properties.setProperty("mail.smtp.port", String.valueOf(SMTP_PORT));
 properties.setProperty("mail.smtp.auth", "true");
 Session session = Session.getDefaultInstance(properties, new MailAuthenticator(USERNAME, PASSWORD));
 MimeMessage msg = new MimeMessage(session);
 msg.setFrom(new InternetAddress(EMAIL));
 InternetAddress.parse(recipient, false));

class MailAuthenticator extends Authenticator {
 private final String user;
 private final String password;

public MailAuthenticator(String user, String password) {
 this.user = user;
 this.password = password;

 public PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication(user, password);

Something special about this code is the MailAuthenticator. You normally don’t write an extra class for this, but it makes the code more readable I think.

Then you can call this class everywhere like that:

String recipient = "";
String subject = "topic";
String text = "smile =)";

Mail.send(recipient, subject, text);

And thats it, it’s really easier then I expected. Try it out =).

Yannick Signer