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: http://www.oracle.com/technetwork/java/javamail/index-138643.html

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 = "user@gmail.com";
 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 = oldschoolemailhost.com";

public static void send(String recipient, String subject, String text) throws AddressException, MessagingException {
 Properties properties = System.getProperties();
 properties.setProperty("mail.smtp.host", 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));
 msg.setRecipients(Message.RecipientType.TO,
 InternetAddress.parse(recipient, false));
 msg.setSubject(subject);
 msg.setText(text);
 Transport.send(msg);
}
}

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

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

@Override
 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 = "bobama@me.com";
String subject = "topic";
String text = "smile =)";

Mail.send(recipient, subject, text);

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