Must issue a STARTTLS command first. Sending email with Java and Google Apps

I am trying to use Bill the Lizard's code to send an email using Google Apps. I am getting this error:

Exception in thread "main" javax.mail.SendFailedException: Sending failed;
  nested exception is: 
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. f3sm9277120nfh.74

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at SendMailUsingAuthentication.postMail(SendMailUsingAuthentication.java:81)
    at SendMailUsingAuthentication.main(SendMailUsingAuthentication.java:44)

Bill's code contains the next line, which seems related to the error:

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

However, it does not help.

These are my import statements:

import java.util.Properties; 
import javax.mail.Authenticator;
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;

Does anyone know about this error?


Solution 1:

I found the problem. Previously i was using j2ee.jar to import javax.mail.

I removed j2ee.jar from the classpath and downloaded JavaMail 1.4.1 and put into my classpath two jars, smtp.jar and mailapi.jar. I use now smtps instead smtp

Transport transport = session.getTransport("smtps");            

Now Bill the Lizard's code works.

Solution 2:

Set the following tags. It will work.

props.put("mail.smtp.user","username"); 
props.put("mail.smtp.host", "smtp.gmail.com"); 
props.put("mail.smtp.port", "25"); 
props.put("mail.debug", "true"); 
props.put("mail.smtp.auth", "true"); 
props.put("mail.smtp.starttls.enable","true"); 
props.put("mail.smtp.EnableSSL.enable","true");

props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");   
props.setProperty("mail.smtp.socketFactory.fallback", "false");   
props.setProperty("mail.smtp.port", "465");   
props.setProperty("mail.smtp.socketFactory.port", "465");