January 5, 2015

JavaMail example with Zoho/GMail using SMTPS

Here is a simple example of how to send emails securely using JavaMail via your Gmail or Zoho account.

The first example uses TLS, which should be your preferred encryption mechanism. The second example uses SSL.

The only difference between the two mechanisms is the port number, and the mail.smtp.startXXX.enable property.

For SSL use:

port 465
mail.smtp.startssl.enable

For TLS use:

port 987
mail.smtp.starttls.enable
 
Get the source on GitHub here

Example 1: Zoho/Gmail with TLS

package com.ritchie.email;

import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailService {

    private Logger logger = Logger.getLogger(SendEmailService.class.getName());

    public void sendEmail() {

        final String GMAIL_HOST = "smtp.gmail.com";
        final String ZOHO_HOST = "smtp.zoho.com";
        final String TLS_PORT = "897";

        final String SENDER_EMAIL = "username@zoho.com";
        final String SENDER_USERNAME = "username@zoho.com";
        final String SENDER_PASSWORD = "zoho-password";

        // protocol properties
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", ZOHO_HOST); // change to GMAIL_HOST for gmail                                                         // for gmail
        props.setProperty("mail.smtp.port", TLS_PORT);
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtps.auth", "true");
        // close connection upon quit being sent
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        try {
            // create the message
            final MimeMessage msg = new MimeMessage(session);

            // set recipients and content
            msg.setFrom(new InternetAddress(SENDER_EMAIL));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@gmail.com", false));
            msg.setSubject("Demo");
            msg.setText("Message Sent via JavaMail", "utf-8", "html");
            msg.setSentDate(new Date());

            // this means you do not need socketFactory properties
            Transport transport = session.getTransport("smtps");

            // send the mail
            transport.connect(ZOHO_HOST, SENDER_USERNAME, SENDER_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (MessagingException e) {
            logger.log(Level.SEVERE, "Failed to send message", e);

        }
    }
}

Example 2: Zoho/Gmail with SSL

package com.ritchie.email;

import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailService {

    private Logger logger = Logger.getLogger(SendEmailService.class.getName());

    public void sendEmail() {

        final String GMAIL_HOST = "smtp.gmail.com";
        final String ZOHO_HOST = "smtp.zoho.com";
        final String SSL_PORT = "465";

        final String SENDER_EMAIL = "username@zoho.com";
        final String SENDER_USERNAME = "username@zoho.com";
        final String SENDER_PASSWORD = "zoho-password";

        // protocol properties
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", ZOHO_HOST); // change to GMAIL_HOST for gmail                                                         // for gmail
        props.setProperty("mail.smtp.port", SSL_PORT);
        props.setProperty("mail.smtp.startssl.enable", "true");
        props.setProperty("mail.smtps.auth", "true");
        // close connection upon quit being sent
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        try {
            // create the message
            final MimeMessage msg = new MimeMessage(session);

            // set recipients and content
            msg.setFrom(new InternetAddress(SENDER_EMAIL));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@gmail.com", false));
            msg.setSubject("Demo");
            msg.setText("Message Sent via JavaMail", "utf-8", "html");
            msg.setSentDate(new Date());

            // this means you do not need socketFactory properties
            Transport transport = session.getTransport("smtps");

            // send the mail
            transport.connect(ZOHO_HOST, SENDER_USERNAME, SENDER_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (MessagingException e) {
            logger.log(Level.SEVERE, "Failed to send message", e);

        }
    }
} 


3 comments :

  1. Hello Chris,

    Thanks for the information on setting up Zoho Mail in JavaMail!

    The port number you have mentioned for smtp.zoho.com for TLS seems to be incorrect. The correct port number for smtp.zoho.com for TLS should be 587 instead of 987. Check out the help link provided below for more information about the same,

    https://www.zoho.com/mail/help/zoho-smtp.html#alink3

    ReplyDelete
  2. .Press the "Servers" button. If the password is recalled by Gmail, then sequential characters in asterisk would be visible in the password area.click here

    ReplyDelete