Send Email Using Java

Send Email Using Java

To send email using Java in your app or website, first you need to add the following two JAR files to your project. You can download it from here

  1. JavaMail API - javaee.github.io/javamail
  2. Java Activation Framework (JAF) - search.maven.org/remotecontent?filepath=com..

Now also allow your mail id to allow access to send email using low secure apps from here
myaccount.google.com/security

image.png

Procedure to send Email

Now let us look at how to Send Email from Gmail mail id using Java

Create a new class named SendEmail and add the following attributes to it -

  • Sender Email ID
  • Sender Email Password
  • Properties object to configure properties for mail
  • A session object
class SendEmail 
{
    private String emailId;
    private String emailPassword;

    // We need to configure the properties for the mail
    private Properties props;

    private Session session;

    SendEmail(String emailId,String emailPassword) 
    {
        this.emailId=emailId;
        this.emailPassword=emailPassword;
        props = new Properties();
        addProperties(); // Function defined further
    }
}

Now we need to add the following properties for configuration

  • mail.smtp.auth - for authentication (required in case of Gmail)
  • mail.smtp.starttls.enable - for TLS encryption
  • mail.smtp.host - for host (smtp.gmail.com for gmail server)
  • mail.smtp.port - for port (587 for gmail)
private void addProperties()
{
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
}

Now we need to login into the Gmail account through our code. Let's move further by creating a session with our email username and password:

private void login() 
{
    session = Session.getInstance(props,
        new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {  
                  return new PasswordAuthentication(emailId,emailPassword);  
              }  
        });
    System.out.println("Login to account successful");
}

Now create a utility function to prepare the message.

private Message prepareMessage (String recipientMailId,String subject,String messageText)
{
    try {
        login();
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(emailId));
        message.setRecipient(Message.RecipientType.TO, 
                         new InternetAddress(recipientMailId));

        message.setSubject(subject);
        message.setText(messageText);

        return message;
    }
    catch(Exception ex) {
        System.out.println(ex);
    }
    return null;    
}

If we need a CC or BCC as recipient simply use message.setRecipient(Message.RecipientType.CC, new InternetAddress(CCMailId)); message.setRecipient(Message.RecipientType.BCC, new InternetAddress(BCCMailId));

If we want to send an e-mail to multiple recipients then the following methods would be used to specify multiple email IDs
void addRecipients(Message.RecipientType type, Address[] addresses)

Now the send message function looks like this -

public void sendMessage (String recipientMailId, String subject, String messageText)
                                          throws Exception
{
    System.out.println("Preparing message to send");
    Message message = prepareMessage(recipientMailId,subject,messageText);
    System.out.println("Message prepared");

    Transport transport = session.getTransport();

    transport.connect();
    Transport.send(message);
    transport.close();

    System.out.println("Message sent successfully");
}

We create a Transport variable to connect and close the session and transport the message.

This is how email sending using Java looks like.

Complete code

The complete code for the above is here. Can directly copy this code and use.

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

class SendEmail 
{
    private String emailId;
    private String emailPassword;

    // We need to configure the properties for the mail
    private Properties props;
    private Session session;

    SendEmail(String emailId,String emailPassword) 
    {
        this.emailId=emailId;
        this.emailPassword=emailPassword;
        props = new Properties();
        addProperties();
    }

    private void addProperties()
    {
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
    }

    private void login() 
    {
        session = Session.getInstance(props,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {  
                   return new PasswordAuthentication(emailId,emailPassword);  
               }  
            });
        System.out.println("Login to account successful");
    }

    private Message prepareMessage(String recipientMailId,String subject,String messageText)
    {
        try {
            login();
            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress(emailId));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientMailId));

            message.setSubject(subject);
            message.setText(messageText);

            return message;
        }
        catch(Exception ex) {
            System.out.println(ex);
        }
        return null;    
    }

    public void sendMessage(String recipientMailId,String subject,String messageText) throws Exception
    {
        System.out.println("Preparing message to send");
        Message message = prepareMessage(recipientMailId,subject,messageText);
        System.out.println("Message prepared");

        Transport transport = session.getTransport();

        transport.connect();
        Transport.send(message);
        transport.close();

        System.out.println("Message sent successfully");
    }
}


public class Main
{
    public static void main(String args[]) throws Exception
    {
        SendEmail se = new SendEmail("xxxxxxxxxx@gmail.com","xxxxxxxxxxxx");
        se.sendMessage("xxxxxxxxxx@gmail.com","xxxxx-Subject-xxx","xxxxxx-Body-xxxxx");
    }
}

Thanks so much for reading till here. This is the end of the article. If you liked this please like this article and give me a follow.