Sending email in Java using Gmail, Yahoo, Hotmail and so on

In this tutorial, I’ve created simple maven web application to send email using gmail or any other mail. I’ve used JSF for frontend. Make sure you’ve installed glassfish server before beginning. You can download and install glassfish server from this.

When you’re done, you’ll get something like this :

 

First of all, create a simple maven web application EmailWithJSF. Then in pom.xml include the following dependency. The dependency is required for sending email in java.


<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>

Now create a jsf page named index.xhtml and insert the following code:

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Sending Email using Gmail, Hotmail, yahoo...</title>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGroup>
                <p>Sender From : <h:inputText value ="#{bean.user.from}"/></p>
                <p>Password : <h:inputSecret value ="#{bean.user.password}"/></p>
                <p>Send To : <h:inputText value ="#{bean.user.to}"/></p>
                <p>Subject : <h:inputText value ="#{bean.user.sub}"/></p>
                <p>Message : <h:inputText value ="#{bean.user.msg}"/></p>

                <h:commandButton value="submit" action="#{bean.send()}"/>
            </h:panelGroup>
        </h:form>
    </h:body>
</html>

After that create a landing page i.e success.xhtml.
success.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Message Sent</title>
    </h:head>
    <h:body>
        Message Sent Successfully.
    </h:body>
</html>

Inside WEB-INF, make sure your web.xml look like this
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Now include the following java classes, User.java and EmailBean.java

User.java


public class User {

    private String from;
    private String password;
    private String to;
    private String sub;
    private String msg;

    public User() {
    }

    public User(String from, String password, String to, String sub, String msg) {
        this.from = from;
        this.password = password;
        this.to = to;
        this.sub = sub;
        this.msg = msg;
    }

    //getter and setters

}

EmailBean.java


import java.util.Properties;
import javax.faces.bean.ManagedBean;
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;

@ManagedBean(name = "bean")
public class EmailBean {

    private String file;

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    User user = new User();

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String send() {
//Get properties object
        System.out.println("Send button click vayo");
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
//get Session
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user.getFrom(), user.getPassword());
            }
        });
//compose message
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user.getFrom()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getTo()));
            message.setSubject(user.getSub());
            message.setText(user.getMsg());
            Transport.send(message);
            System.out.println("message sent....");
            return "success.xhtml?faces-redirect=true";
        } catch (MessagingException ex) {
            ex.printStackTrace();
            return null;
        }
    }

}