tags:

views:

44

answers:

2

Hi All,

try 
{
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true"); 
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.user", "username");
props.setProperty("mail.password", "password");

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

 MimeMessage msg = new MimeMessage(session);

 InternetAddress addressFrom = new InternetAddress(from);
 msg.setFrom(addressFrom);

 msg.addRecipient(Message.RecipientType.TO,new InternetAddress(" Recipient mail id "));

 msg.setSubject(subject);
 Transport transport = session.getTransport();
 transport.connect();
 transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.TO));
 transport.close();

} catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

I am using the above code to send email to a gmail account. I have set the smtp host value (smtp.gmail.com)and port (465) in the properties. But the email is not sent and my app got stuck for long time. After that i am getting an error like given below

"javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1"

Can anyone tell what is the reason and how to resolve this issue?

+1  A: 

Setting

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

enables tls which is on port 587 not 465

props.put("mail.smtp.port", "587");

See Google Doc

And check whether you really need these lines

props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.fallback", "false");
stacker
another reference http://forums.sun.com/thread.jspa?threadID=5316613
stacker
Hey thank u so much, it worked....
SWDeveloper
A: 

Hi,

It is working for me if I try from my gmail account. Now I tried to send email from my yahoomail by changing the smtp host as "smtp.mail.yahoo.com". But I am getting "SMTPSendFailedException". Can I know what changes I need to do to make it working ? similarly for hotmail and rediffmail too...

thanks, Senthil.M

Senthil
If you have a question, ask a **question**, don't hijack someone else's question with something claiming to be an **answer**.
David Dorward