How to Send Email Using Java: Setup and Configuration

Learn how to send email from your Java application using the JavaMail API and Java Activation Framework (JAF). Discover how to download, install, and configure the necessary JAR files, such as mail.jar and activation.jar, to enable email functionality in your Java projects.



Java - Sending Email

To send an email using your Java application, you first need to have the JavaMail API and the Java Activation Framework (JAF) installed on your machine. You can download the latest version of JavaMail (Version 1.6) and JAF (Version 1.2) from their official websites.

After downloading and unzipping these files, locate the JAR files in the top-level directories. You need to add mail.jar and activation.jar to your CLASSPATH.

Send a Simple Email

The following example demonstrates how to send a simple email from your machine. Ensure that your localhost is connected to the Internet and is capable of sending emails.


// File Name: SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail {

public static void main(String[] args) {
    // Recipient's email ID
    String to = "recipient@example.com"; // Update recipient email

    // Sender's email ID
    String from = "sender@example.com"; // Update sender email

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field
        message.setFrom(new InternetAddress(from));

        // Set To: header field
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject("This is the Subject Line!");

        // Set the actual message
        message.setText("This is the actual message.");

        // Send the message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}
}

Output


$ java SendEmail
Sent message successfully....

Send an Email to Multiple Recipients

To send an email to multiple recipients, you can use the following method:


void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException

Here, type can be set to Message.RecipientType.TO, CC (Carbon Copy), or BCC (Blind Carbon Copy).

Send an HTML Email

The following example demonstrates how to send an HTML email:


// File Name: SendHTMLEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendHTMLEmail {

public static void main(String[] args) {
    // Recipient's email ID
    String to = "recipient@example.com"; // Update recipient email

    // Sender's email ID
    String from = "sender@example.com"; // Update sender email

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field
        message.setFrom(new InternetAddress(from));

        // Set To: header field
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject("This is the Subject Line!");

        // Send the actual HTML message
        message.setContent("

This is the actual message

", "text/html"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } }

Output


$ java SendHTMLEmail
Sent message successfully....

Send an Email with Attachment

To send an email with an attachment, use the following example:


// File Name: SendFileEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendFileEmail {

public static void main(String[] args) {
    // Recipient's email ID
    String to = "recipient@example.com"; // Update recipient email

    // Sender's email ID
    String from = "sender@example.com"; // Update sender email

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field
        message.setFrom(new InternetAddress(from));

        // Set To: header field
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject("This is the Subject Line!");

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText("This is the message body");
        
        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is the attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "file.txt"; // Update to your attachment file path
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}
}

Output


$ java SendFileEmail
Sent message successfully....

User Authentication

If you need to provide user ID and password for email server authentication, set the following properties:


props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

The rest of the email sending mechanism remains as explained above.