Java Mail Example – Gmail

This example uses Java Mail and can be used as Utility class for sending email using Java Mail, using your GMAIL account. One can configure their smtp servers accordingly then.

package com.dirtyyourhands;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
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 EmailUsingJava {

  Session mailSession;

  public static void main(String args[]) throws AddressException, MessagingException {

    EmailUsingJava emailUsingJava = new EmailUsingJava();

  private void configureEmailProperties() {
    Properties emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", "587");
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");
    mailSession = Session.getDefaultInstance(emailProperties, null);

  private void sendEmail() throws AddressException, MessagingException {
    String fromUser = "";
    String fromUserEmailPassword = "<Your GMAIL Password Goes Here>";
    String emailHost = "";
    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromUser, fromUserEmailPassword);

    MimeMessage mimeMessage = prepareEmail();
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    System.out.println("Email sent successfully.");

  private MimeMessage prepareEmail() throws AddressException, MessagingException {
    String[] toEmails = { "", "" };
    String emailSubject = "Email using GMAIL";
    String emailBody = "Sending email using GMAIL from example.";

    MimeMessage emailMessage = new MimeMessage(mailSession);

    // configuring TO addresses
    for (int i = 0; i < toEmails.length; i++) {
      emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));

    // we are sending HTML email, if you want to send text email using
    // setText(emailBody);
    emailMessage.setContent(emailBody, "text/html");

    return emailMessage;