1
package com.bcs;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailTLS {

    public static void main(String[] args) {
        String host = "smtp.gmail.com";
        int port = 587;
        String username = "foo@gmail.com";
        String password = "bar";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(props);

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

            Transport transport = session.getTransport("smtp");
            transport.connect(host, port, username, password);
            Transport.send(message);

            System.out.println("Done");

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

I have given all the necessary inputs . But still it fails with

Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
    at com.bcs.SendMailTLS.main(SendMailTLS.java:43)
Caused by: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
    at javax.mail.Service.connect(Service.java:329)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.bcs.SendMailTLS.main(SendMailTLS.java:38)

I am new to java mail.Any help would be greatly appreciated.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
saravana
  • 11
  • 1
  • 1
  • 2
  • Does this help? http://stackoverflow.com/questions/1990454/using-javamail-to-connect-to-gmail-smtp-server-ignores-specified-port-and-tries-t – Jared Farrish Sep 25 '11 at 18:00

1 Answers1

3

This might help: http://www.behrang.org/en/blog/2010/03/30/sending-email-from-grails-using-gmail/

I think you should set these properties:

'mail.smtp.auth': 'true',
'mail.smtp.socketFactory.port': '465',
'mail.smtp.socketFactory.class': 'javax.net.ssl.SSLSocketFactory',
'mail.smtp.socketFactory.fallback': 'false'

And the port is 465.

Behrang
  • 46,888
  • 25
  • 118
  • 160
  • 1
    This requires connecting via the `smtps` Transport, not via `smtp`. And the OP has the correct port for `smtp`/`STARTTLS`. http://mail.google.com/support/bin/answer.py?answer=13287 – dkarp Mar 13 '11 at 20:27