Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Send Simple Text Email With Java

Using Apache Commons Email SimpleEmail class, users can send simple text email. This article explains how to send a simple text email in Java. 

 

You create a maven based java project and add the following dependency in the project pom.xml file. 

<dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-email</artifactId>
     <version>1.4</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-parent</artifactId>
    <version>38</version>  
</dependency>

Write the following code in the "SendSimpleTextEmail" class .

package com.example.email;
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 SendSimpleTextEmail {
    public static void main(String[] args)
    {
       //Initialize a new email instance
        Email email=new SimpleEmail();
        //Set email host
        email.setHostName("smtp.googlemail.com");
        //Set email authentication username and password
        email.setAuthenticator(new DefaultAuthenticator("Selenium Master User Name","Selenium Master User Password"));
        //Set email host SSL to true
        email.setSSL(true);
        try {
            //Set From email address
            email.setFrom("
 This email address is being protected from spambots. You need JavaScript enabled to view it.
 ");
        } catch (EmailException e) {
            e.printStackTrace();
        }
        //Set email Subject line
        email.setSubject("Java Test Email");
        try {
            //Set Email Message
            email.setMsg("This is a test from Java Email");
        } catch (EmailException e) {
            e.printStackTrace();
        }
        try {
            //Set Email To Address
            email.addTo("
 This email address is being protected from spambots. You need JavaScript enabled to view it.
 ");
        } catch (EmailException e) {
            e.printStackTrace();
        }
        try {
            //Send Email
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

    }
}

Run the above code and check the email. As shown on the email confirmation message below, email is sent to the address successfully. 

from:	
 This email address is being protected from spambots. You need JavaScript enabled to view it.
 
to:	
 This email address is being protected from spambots. You need JavaScript enabled to view it.
 
date:	Sun, Jun 28, 2015 at 3:32 PM
subject:	Java Test Email
mailed-by:	seleniummaster.com