Send email using Javamail API


                               Before explaining the Java program to send email, I will explain the classes and methods used here from Java Mail API, that will provide some background knowledge about the stuff here. This code is configured to send email from Gmail to any email service provider by using Java programming language. If you wish to send email from any other email service provider, then you need to change host (d_host) and port number (d_port) corresponding to the service provider. This requires Mail.jar to be downloaded which can be done here
Email Providers

Authenticator

This class obtains authentication for network connection. Authentication can be done by means of providing username, password. When authentication is required, the system will invoke a method on the subclass getPasswordAuthentication() and this will query about the authentication to number of inherited methods and returns the result.  

MIME Message

                This class represents MIME style email message.  This class provides methods to set various stuffs for sending emails. Some basic methods required for sending emails are ‘setSubject’, ‘setFrom’, ‘addRecipient’, ‘setText’ these are self-explanatory by name.  Even bigger emails with HTML content can be sent through ‘setContent’ method. Emails can also be sent to multiple people through ‘addRecipients’ method. There are lot more interesting methods inside MIME Message.

Transport.send

                Transport is an abstract class that that models a message transport.  Send is a static method that sends the message to specified address along with data stored in MIME Message. If any invalid email is found it returns SendFailedException

JavaMail.java  - Download

package javamail;

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

public class JavaMail {    
    String d_email = "fromAddress@gmail.com",
            d_password = "password", //your email password
            d_host = "smtp.gmail.com",
            d_port = "465",
            m_to = "ToAddress", // Target email address
            m_subject = "Testing",
            m_text = "Hey, this is a test email.";
    
    public JavaMail() {
        Properties props = new Properties();
        props.put("mail.smtp.user", d_email);
        props.put("mail.smtp.host", d_host);
        props.put("mail.smtp.port", d_port);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        //props.put("mail.smtp.debug", "true");
        props.put("mail.smtp.socketFactory.port", d_port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);     
            MimeMessage msg = new MimeMessage(session);
            msg.setText(m_text);
            msg.setSubject(m_subject);
            msg.setFrom(new InternetAddress(d_email));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
            Transport.send(msg);
        } catch (Exception mex) {
            mex.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
        JavaMail blah = new JavaMail();
    }
  
    private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(d_email, d_password);
        }
    }
}



 Finally we have come to the end of this post. Hope this will help you to incorporate this Program in various applications.

Possible Exceptions:

1) Unknown SMTP host: smtp.gmail.com - This error might occur if you do not have a valid internet connection.
2) Could not connect to SMTP host: smtp.gmail.com  - If you face this error, first disable your firewall and try running the code, still if you face this issue, then check your Antivirus settings.

Clear explanation is provided in the comments below. Please read...

Have a look at this tutorial for reading emails using Java mail api




Reactions:

7 comments :

  1. javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1389)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:41
    2)
    at javax.mail.Service.connect(Service.java:310)
    at javax.mail.Service.connect(Service.java:169)
    at javax.mail.Service.connect(Service.java:118)
    at javax.mail.Transport.send0(Transport.java:188)
    at javax.mail.Transport.send(Transport.java:118)
    at JavaMail.(JavaMail.java:35)
    at JavaMail.main(JavaMail.java:44)
    Caused by: java.net.UnknownHostException: smtp.gmail.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java
    :550)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketI
    mpl.java:141)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
    ... 8 more

    ReplyDelete
  2. Kindly check your internet connection. This error will occur if you do not have a valid internet connection.

    ReplyDelete
  3. Hi

    I am using the exact same code that you have provided in Eclipse Juno 4.2. I am getting the following error:


    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.SocketException: Connection reset
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:367)
    at javax.mail.Service.connect(Service.java:226)
    at javax.mail.Service.connect(Service.java:175)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at kdkmail.gui.views.JavaMail.(JavaMail.java:34)
    at kdkmail.gui.views.JavaMail.main(JavaMail.java:41)
    Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 8 more


    Would you be able to advise on what the problem might be?
    Thank you in advance.

    ReplyDelete
    Replies
    1. I tried replicating this issue in my PC but negative, follow the below steps and kindly respond with the results.
      1)Try pinging the host- smtp.gmail.com from command prompt.
      2)Disable your firewall and try running the code.

      Delete
    2. Hi

      I resolved the problem.
      The ping to the host always worked for me. Disabling windows firewall did not change anything.
      However, when I went into my antivirus(Avast) settings, I found that it was redirecting port 25 for SMTP. I removed all restrictions in Avast that were to do with email and the codee runs successfully.

      Delete
    3. Great!! Thanks for sharing..

      Delete
  4. I want to create a form on my website through which user can send email to two OUTLOOK email-ids.
    The form is just like user enters his/her email-id, name, subject, message and send mail to outlook ids.
    The users id an be gmail, yahoo etc. What shld be the port number, host etc.

    ReplyDelete