JavaMail API – Java program to send email – Gmail SMTP server example

We know that if we have to send a mail to somebody from Java code, we need to have access on some mail server credentials. If we do not have access to those credentials, Google provides public access to Gmail SMTP server through our Gmail account.

1. Gmail SMTP Server Details

Google has provided free access to one of its SMTP server and we can use it Java code to send emails.

  1. Gmail SMTP server – smtp.gmail.com
  2. Port – 465 (SSL required)
  3. Port – 587 (TLS required)
  4. Use Authentication – Yes

2. Java program to send email though Gmail server

Given below is program which can be used to send emails using Gmail SMTP server.

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 JavaEmail
{
    Session mailSession;

    public static void main(String args[]) throws AddressException, MessagingException
    {
        JavaEmail javaEmail = new JavaEmail();
        javaEmail.setMailServerProperties();
        javaEmail.draftEmailMessage();
        javaEmail.sendEmail();
    }

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

    private MimeMessage draftEmailMessage() throws AddressException, MessagingException
    {
        String[] toEmails = { "admin@gmail.com" };
        String emailSubject = "Test email subject";
        String emailBody = "This is an email sent by <b>//howtodoinjava.com</b>.";
        MimeMessage emailMessage = new MimeMessage(mailSession);
        /**
         * Set the mail recipients
         * */
        for (int i = 0; i < toEmails.length; i++)
        {
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
        }
        emailMessage.setSubject(emailSubject);
        /**
         * If sending HTML mail
         * */
        emailMessage.setContent(emailBody, "text/html");
        /**
         * If sending only text mail
         * */
        //emailMessage.setText(emailBody);// for a text email
        return emailMessage;
    }

    private void sendEmail() throws AddressException, MessagingException
    {
        /**
         * Sender's credentials
         * */
        String fromUser = "user-email@gmail.com";
        String fromUserEmailPassword = "*******";

        String emailHost = "smtp.gmail.com";
        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromUser, fromUserEmailPassword);
        /**
         * Draft the message
         * */
        MimeMessage emailMessage = draftEmailMessage();
        /**
         * Send the mail
         * */
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        System.out.println("Email sent successfully.");
    }
}

Happy Learning !!

If you get “Connection timed out” error, then make sure you are not behind any proxy which is preventing your to access gmail server. Most corporate proxies will prevent you. Try pinging the URL : ‘smtp.gmail.com’.

In this example, we saw Java program to send email using gmail smtp server to multiple recipients. Drop me your questions in comments.

Happy Learning !!

References:

GMail SMTP detail

Leave a Reply

46 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial