0

I've looked over the previous links on SO concerning the matter but they don't solve my problem.

So here is my code:

public class SendMail {

    private String from;
    private String to;
    private String host;
    private String subject;
    private String message;
    private String pass;

    private static final Logger LOGGER = Logger.getLogger(SendMail.class.getName());

    public SendMail(String from, String pass, String to, String host, String subject, String message) {
        super();
        this.from = from;
        this.to = to;
        this.host = host;
        this.subject = subject;
        this.message = message;
        this.pass = pass;
    }

    public void sendMail(){
        Properties properties = System.getProperties();
        final String USERNAME = from;
        final String PASSWORD = pass;

        properties.put("mail.smtp.user", USERNAME);
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "25");
        properties.put("mail.debug", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.EnableSSL.enable", "true");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.fallbac k", "false");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.socketFactory.port", "465");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthenticated(){
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });


        //properties.setProperty("mail.imap.ssl.enable", "true");
        //properties.put("mail.debug", "true");
        //Session session = Session.getInstance(properties);

        try {
            //Store store = session.getStore("imap");
            //store.connect(host, USERNAME, PASSWORD);

            MimeMessage mime = new MimeMessage(session);
            mime.setFrom(new InternetAddress(USERNAME));
            mime.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mime.setSubject(subject);
            mime.setText(message);
            Transport.send(mime);
            LOGGER.log(Level.INFO, "Mail sent successfully");
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            LOGGER.log(Level.SEVERE, "Unable to send mail\n");
        }   
    }

}

And here are the logs:

DEBUG: JavaMail version 1.4.4
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
Dec 30, 2015 4:51:31 PM utility.mailclient.SendMail sendMail
SEVERE: Unable to send mail

Also, the commented part in the above code is taken from this link:

http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail

which is supposed to be correct. But I'm getting the same result. Here are the logs using this code (and commenting out all the properties.put and properties.setProperty lines above)

DEBUG: JavaMail version 1.4.4
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: mail.imap.statuscachetimeout: 1000
DEBUG: mail.imap.appendbuffersize: -1
DEBUG: mail.imap.minidletime: 10
DEBUG: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from 182.75.40.98 j10mb367075283iee
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH
A0 OK Thats all she wrote! j10mb367075283iee
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: PLAIN-CLIENTTOKEN
DEBUG IMAP: AUTH: OAUTHBEARER
DEBUG IMAP: AUTH: XOAUTH
DEBUG: protocolConnect login, host=imap.gmail.com, user=mailid04@gmail.com, password=<non-null>
A1 AUTHENTICATE PLAIN
+ 
AGF0dWxzcGFtMDRAZ21haWwuY29tAGF0dWxzcGFt
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS
A1 OK mailid@gmail.com authenticated (Success)
A2 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS
A2 OK Success
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "localhost", port 25, isSSL false
Dec 30, 2015 5:11:24 PM utility.mailclient.SendMail sendMail
SEVERE: Unable to send mail

PS: I've turned on the check of gmail which allows less secure apps to access it.

vish4071
  • 5,135
  • 4
  • 35
  • 65
  • Try to add `properties.put("java.net.preferIPv4Stack", "true");` – Helping Hands Dec 30 '15 at 11:49
  • Exactly same case... – vish4071 Dec 30 '15 at 11:52
  • Seems you message part is missing something , please check code here which is working to send mail in java , [Send Mail in JAVA](http://stackoverflow.com/questions/34511161/how-to-send-out-an-email-notification-in-selenium-webdriver-using-java/34511377#34511377) – Helping Hands Dec 30 '15 at 11:56
  • Is there a reason you are trying to connect to host "localhost", port 25? Do you definitely have a mail daemon running on localhost? Gmail authentication seems to be working, as shown by "mailid@gmail.com authenticated (Success)" – Dave Dec 30 '15 at 12:16
  • So should I just remove that line? – vish4071 Dec 30 '15 at 12:35
  • Can you print (e.printStackTrace () ) and share full exception? Google has very good error texts in place for gmail smtp. – Jan Dec 30 '15 at 13:20
  • @Jan Google's error texts will show up in the debug log, not the exception. – user207421 Dec 31 '15 at 02:11
  • You can check your AV mail shield. Usually AV blocks the outgoing mails for security purposes. Read this one http://stackoverflow.com/questions/17098281/my-java-program-stopped-sending-emails-using-my-gmail-account. May be, but post your stacktrace as mentioned by Jan. – Tech Enthusiast Dec 31 '15 at 07:15
  • Thanks for the discussion everyone. I've got my mail client working and I've post the code in the answer. I'd like you to verify one thing from there...what is the security level of that code if you can please. (like, is the password travelling through web as plaintext? ,etc) – vish4071 Dec 31 '15 at 07:17

2 Answers2

2

This may not be a complete answer, but there's so many things wrong I couldn't fit it all in a comment...

  1. Get rid of the socket factory properties, you don't need them.
  2. There is no "mail.smtp.EnableSSL.enable" property. Perhaps you intended "mail.smtp.ssl.enable".
  3. You're using a very old version of JavaMail, upgrade if you can.
  4. Change your Gmail password immediately, it's exposed (but encoded) in the log output above.
  5. There's no need to connect to the Store before sending the message using Transport.
  6. Gmail examples are in the JavaMail FAQ.
  7. You're setting "mail.smtp.port" twice, to different values. You don't need to set it at all if you set "mail.smtp.ssl.enable" to "true".

If you make all those changes and it still doesn't work, update your post with the latest code and debug output.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
  • Thanks for the answer but I was still getting similar error. After some searching and trials, I got a code that works and I've post it as answer. I'd like you to verify one thing from there...what is the security level of that code if you can please. (like, is the password travelling through web as plaintext? ,etc) – vish4071 Dec 31 '15 at 07:14
  • That's essentially the same code as in the JavaMail FAQ, did you try it? Because you've enabled STARTTLS, the connection will be switched to SSL/TLS before the password is sent, so the password won't be sent in the clear. You can set the "require" property instead of the "enable" property if you want it to fail if the server doesn't support STARTTLS. Note also that there's no "password" property so there's no point in setting it. And you don't need to set the "user" or "host" properties either since you're passing them in explicitly in the connect call. Again, see the code in the FAQ. – Bill Shannon Dec 31 '15 at 07:33
  • 1
    And read the FAQ item referenced by #1 in my answer to understand why you don't want to use Session.getDefaultInstance. – Bill Shannon Dec 31 '15 at 07:34
0

After many trials with different properties setting up, I got my code to be able to send mail. Here is the code:

public void sendMail(){
    Properties properties = System.getProperties();
    final String USERNAME = from;
    final String PASSWORD = pass;

    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.user", from);
    properties.put("mail.smtp.password", pass);
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    //properties.put("mail.debug", "true");

    Session session = Session.getDefaultInstance(properties);
    try {

        MimeMessage mime = new MimeMessage(session);
        mime.setFrom(new InternetAddress(USERNAME));

        mime.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        mime.setSubject(subject);
        mime.setText(message);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(mime, mime.getAllRecipients());
        transport.close();
        LOGGER.log(Level.INFO, "Mail sent successfully");
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        LOGGER.log(Level.ERROR, "Unable to send mail\n");
    }   
}

Noticeable changes here are:

  • Different properties that are set up.
  • The way last transport.send is changed to transport.sendMessage.

And this works.

vish4071
  • 5,135
  • 4
  • 35
  • 65