You are currently viewing How to Send Emails with JavaMail API

How to Send Emails with JavaMail API

The code provided is an example of how to send emails using the JavaMail API. It demonstrates how to configure the email properties, set the sender, subject, and content of the email, and send it to one or multiple recipients.

import java.util.Properties;
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 Main {

    public static void main(final String[] args) {

        try {

            EmailConfig emailConfig = new EmailConfig(
                    "smtp.gmail.com", // SMTP host
                    "587", // SMTP port
                    "edwardnyirendajr@gmail.com", // Username
                    "password" // Password
            );

            Mail mail = new Mail(emailConfig, "edwardnyirendajr@gmail.com");

            mail.setSubject("Sending Emails with JavaMail API") // Email subject
                .setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") // Email content
                .send("edward@coderscratchpad.com"); // Email recipients

            // Sending to multiple recipients
            // .send("email1@coderscratchpad.com", "email2@coderscratchpad.com");

            System.out.println("Email sent successfully.");

        } catch (MessagingException e) {
            System.out.println("Failed to send email. Error: " + e.getMessage());
        }

    }

}


record EmailConfig(String host, String port, String username, String password) { }

class Mail {

    private Message message;

    public Mail(EmailConfig emailConfig) {
        this.config(emailConfig);
    }

    public Mail(EmailConfig emailConfig, String senderEmail) throws MessagingException {
        this(emailConfig);
        this.message.setFrom(new InternetAddress(senderEmail));
    }

    private void config(EmailConfig emailConfig) {

        // Set the SMTP properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", emailConfig.host());
        properties.put("mail.smtp.port", emailConfig.port());
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(emailConfig.username(), emailConfig.password());
            }

        });

        this.message = new MimeMessage(session);

    }

    public Mail setSenderEmail(String senderEmail) throws MessagingException {
        this.message.setFrom(new InternetAddress(senderEmail));
        return this;
    }

    public Mail setSubject(String subject) throws MessagingException {
        this.message.setSubject(subject);
        return this;
    }

    public Mail setText(String text) throws MessagingException {
        this.message.setText(text);
        return this;
    }

    public void send(String... recipients) throws MessagingException {
        this.message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(String.join(",", recipients)));
        Transport.send(this.message);
    }

    public Message getMessage() {
        return this.message;
    }

}

To run the code, you need to include the JavaMail API library and JavaBeans Activation Framework in your project’s dependencies. These libraries provide the necessary classes and functionality for sending emails using the JavaMail API.

You can download the JavaMail API library here and JavaBeans Activation Framework here or use a dependency management tool like Maven or Gradle to include it in your project.

Here is an example of how to include the JavaMail API and JavaBeans Activation Framework dependencies using Maven:

<dependencies>

  <!-- JavaMail API -->
  <dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
  </dependency>
	
  <!-- JavaBeans Activation Framework -->
  <dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
  </dependency>
	
</dependencies>

If your version of Java does not support records, you would need to replace the EmailConfig record with a class that provides the equivalent functionality. Here’s an example of how you can define a class equivalent to the EmailConfig record:

public class EmailConfig {

    private final String host;
    private final String port;
    private final String username;
    private final String password;

    public EmailConfig(String host, String port, String username, String password) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public String getHost() {
        return host;
    }

    public String getPort() {
        return port;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
    
}

The Mail class is responsible for creating and sending the email. It takes an EmailConfig object in the constructor to configure the email settings.

That was all I had to share with you guys. If you found this code informative and would love to see more, don’t forget to subscribe to our newsletter! 😊

Leave a Reply