How to Send Email in Java

Sarwan Soomro Feb 16, 2024
  1. Steps You Need To Take Before Executing Your JavaMail
  2. Send Email From Gmail in Java
  3. Send Email From Microsoft Email using JavaMail API
  4. Send Email With Apache Commons Library in Java
How to Send Email in Java

This article will share the latest techniques to send emails using JavaMail and Apache Commons API(s). In total, there are three programs in this demonstration.

You can use the first program for sending emails from Gmail. The second program will uncover how to use Microsoft to send emails in Java, while the last one is a simple demonstration of how you also use Apache Commons to send emails using Java.

Steps You Need To Take Before Executing Your JavaMail

  1. Download and configure: JavaMail jar file and Activation jar file
  2. Turn off 2-Step Verification and Less Secure App
  3. Configure build path: click on your Java project, configure the build path and the libraries section, and add external jar files under the classpath.

Once you have successfully done these steps, your first program will not throw any exception.

Send Email From Gmail in Java

Before executing our program, let’s explain how the code works.

  • Properties: These depict a permanent set of properties with keys as strings that we use to set values in each key.
  • MimeMessage: It contains three significant variables, subject, receipt, message text. These variables help take user input to extend the MimeMessage.
  • Session: The JavaMail API contains the session properties. We can also override the session, but that is not the goal of this task.
  • Transport: This generic class in this API represents a message transport functionality to send emails.
Note
We highly recommend you open these files from your libraries to read more about them.

Code:

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

// Main Class
public class FirstProgram {
  public static void main(String[] args) {
    // Turn off Two Factor Authentication
    // Turn off less secure app
    final String sender = "Write Yor Email Address"; // The sender email
    final String urpass = "The Password of your email here"; // keep it secure
    Properties set = new Properties();
    // Set values to the property
    set.put("mail.smtp.starttls.enable", "true");
    set.put("mail.smtp.auth", "true");
    set.put("mail.smtp.host", "smtp.gmail.com");
    set.put("mail.smtp.port", "587");
    Session session = Session.getInstance(set, new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(sender, urpass);
      }
    });

    try {
      // email extends Java's Message Class, check out javax.mail.Message class to read more
      Message email = new MimeMessage(session);
      email.setFrom(new InternetAddress("senderEmail")); // sender email address here
      email.setRecipients(Message.RecipientType.TO,
          InternetAddress.parse("receiverEmail")); // Receiver email address here
      email.setSubject("I am learning how to send emails using java"); // Email Subject and message
      email.setText("Hi, have a nice day! ");
      Transport.send(email);
      System.out.println("Your email has successfully been sent!");
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
}

Output:

Your email has successfully been sent!

You can also check out the output in the following GIF:

Send Email From Gmail Using Java

Send Email From Microsoft Email using JavaMail API

Although the core functionality of the code block is the same as the first program that we already discussed, some functions might differ:

  • import java.util.Date;: It enables generating a date object and instantiating it to match the time of creation, measured to the closest millisecond.
  • import javax.mail.Authenticator;: It provides an object that learns how to get connection authentication. Typically, this is done by enabling the user for information.
  • import javax.mail.PasswordAuthentication;: It is a safe container that we utilize to collect a user name and a password. Note: We can also override it based on our preferences.
  • import javax.mail.internet.InternetAddress;: It denotes a class that stores an internet email address using the RFC822 syntax structure.

Some of the classes in the javax.mail API were worth discussing to understand the following code structure.

Code:

import java.util.Date;
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.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailUsingJavaOutlook {
  // Define contstant strings and set properties of the email
  final String SERVIDOR_SMTP = "smtp.office365.com";
  final int PORTA_SERVIDOR_SMTP = 587;
  final String CONTA_PADRAO = "sender email here";
  final String SENHA_CONTA_PADRAO = "sender password";
  final String sender = "Write your email again";
  final String recvr = "Whom do you want to send?";
  final String emailsubject = "Subject of the email";
  // Note: you can use the date function just like these strings
  final String msg = "Hi! I am sending this email from a java program.";

  public void Email() {
    // Set the session of email
    final Session newsession = Session.getInstance(this.Eprop(), new Authenticator() {
      @Override
      // password authenication
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
      }
    });
    // MimeMessage to take user input
    try {
      final Message newmes = new MimeMessage(newsession);
      newmes.setRecipient(Message.RecipientType.TO, new InternetAddress(recvr));
      newmes.setFrom(new InternetAddress(sender));
      newmes.setSubject(emailsubject); // Takes email subject
      newmes.setText(msg); // The main message of email
      newmes.setSentDate(new Date()); // You can set the date of the email here
      Transport.send(newmes); // Transfort the email
      System.out.println("Email sent!");
    } catch (final MessagingException ex) { // exception to catch the errors
      System.out.println("try hard!"); // failed
    }
  }
  // The permenant set of prperties containg string keys, the following configuration enables the
  // SMPTs to function
  public Properties Eprop() {
    final Properties config = new Properties();
    config.put("mail.smtp.auth", "true");
    config.put("mail.smtp.starttls.enable", "true");
    config.put("mail.smtp.host", SERVIDOR_SMTP);
    config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
    return config;
  }
  public static void main(final String[] args) {
    new SendEmailUsingJavaOutlook().Email();
  }
}

Output:

Email sent!

You can also view the output in the image below:

Send Outlook Email with a Java Program

Send Email With Apache Commons Library in Java

You can download Commons Email from here and add the commons-email-1.5.jar file to the build path of your IDE. Open these library files and read the code to learn more.

This final code block uses all the Apache classes, but we can always customize them based on our requirements.

Code:

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class SendMailWithApacheCommonsJava {
  @SuppressWarnings("deprecation")
  public static void main(String[] args) throws EmailException {
    Email sendemail = new SimpleEmail();
    sendemail.setSmtpPort(587);
    sendemail.setAuthenticator(
        new DefaultAuthenticator("uremail", "urpassword")); // password and email
    sendemail.setDebug(false);
    sendemail.setHostName("smtp.gmail.com");
    sendemail.setFrom("uremail");
    sendemail.setSubject("The subject of your email");
    sendemail.setMsg("Your email Message");
    Your Email Address sendemail.addTo("receivermail"); // Receiver Email Address
    sendemail.setTLS(true);
    sendemail.send(); // sending email
    System.out.println("You have sent the email using Apache Commons Mailing API");
  }
}

Output:

You have sent the email using Apache Commons Mailing API

You can also see the output in the GIF provided below:

Java Email with Apache Commons Mailing API

Sarwan Soomro avatar Sarwan Soomro avatar

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

LinkedIn

Related Article - Java Email