Apache commons mail maven

Apache Commons Mail is a library that provides a simple and easy-to-use API for sending emails in Java. Here's how to use it with Maven:

Step 1: Add the Apache Commons Mail dependency to your Maven project

In your pom.xml file, add the following dependency:

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-email</artifactId>
        <version>1.5</version>
    </dependency>
</dependencies>

Step 2: Create a Java class that uses Apache Commons Mail

Create a new Java class that will use Apache Commons Mail to send an email. For example:

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 SendEmail {
    public static void main(String[] args) {
        Email email = new SimpleEmail();
        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("[email protected]", "your-password"));
        email.setFrom("[email protected]");
        email.setSubject("Test Email");
        email.setMsg("This is a test email sent using Apache Commons Mail.");
        try {
            email.send();
            System.out.println("Email sent successfully!");
        } catch (EmailException e) {
            System.out.println("Error sending email: " + e.getMessage());
        }
    }
}

Step 3: Run the Java class

Compile and run the Java class using Maven:

mvn compile exec:java -Dexec.mainClass="SendEmail"

This will send an email using Apache Commons Mail.

Tips and Variations