sending automatic javamail from a website using java mail API

Question


Below is my code for sending an automatic mail on registration from my website:

import java.util.Properties;

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;

public class ConfirmationMail {

    public static void main(String[] args) {

        int id=0;
        String passWord=null;
        sendMail(id, passWord);
    }

        public static void sendMail(int id, String passWord) {
        // TODO Auto-generated method stub

        final String username = "[email protected]";
        final String password = "xxx";
        final String host= "smtp.gmail.com";
        final int port=587;
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");


        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Message sent successfully");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

And when i run this on my eclipse its throwing exception the stack trace is as below:

     java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;  
  nested exception is:  
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?  
    at com.affiliate.DTO.ConfirmationMail.sendMail(ConfirmationMail.java:64)  
    at com.affiliate.servlet.AffiliateApproveServlet.doGet(AffiliateApproveServlet.java:39)  
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)  
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)  
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)  
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)  
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)  
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)  
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)  
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)  
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)  
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)  
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)  
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)  
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)  
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)  
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)  
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)  
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)  
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)  
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)  
    at java.lang.Thread.run(Thread.java:724)  
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;  
  nested exception is:  
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?  
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1986)  
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)  
    at javax.mail.Service.connect(Service.java:345)  
    at com.affiliate.DTO.ConfirmationMail.sendMail(ConfirmationMail.java:55)  
    ... 22 more  
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?  
    at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:671)  
    at sun.security.ssl.InputRecord.read(InputRecord.java:504)  
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)  
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)  
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)  
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)  
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:532)  
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:337)  
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)  
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)  
    ... 25 more  

And the jar files i have in my eclipse build path are javax.mail.jar , activation.jar, commons-email-1.0.jar Please help me resolve this... Thanks in advance...



Answer


Use javamail 1.5.1

TLS connections work with this version. https://javamail.java.net/docs/SSLNOTES.txt

Replace

props.put("mail.smtp.ssl.enable", "true");

with because gmail use TLS.

props.put("mail.smtp.starttls.enable", "true");

Replace 4 lines below

Transport transport = session.getTransport("smtps");
transport.connect (host, port,username,password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();  

with just this 1 line.

Transport.send(message);