Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TLS issue when sending to gmail through JavaMail

Turns out that JavaMail is a bit more frustrating than I thought it would be. I've looked at several examples online on how to send a simple SMTP email through Gmail's servers (but not through SSL). After trying several different examples of code, I keep concluding to the same example exception when I call transport.connect(). I keep getting this stack trace:

Exception in thread "main" com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. l10sm302158wfk.21
     at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
     at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)
     at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)
     at SendEmail.main(SendEmail.java:47)

Can someone please tell me what I should add or do to fix this?

Here is my code:

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.host", "smtp.gmail.com");
    props.put("mail.user", "[email protected]");
    props.put("mail.password", "blah");
    props.put("mail.port", "587");

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("This is a test");
    message.setContent("This is a test", "text/plain");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

    transport.connect();
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
like image 238
Brian Avatar asked Jun 28 '11 20:06

Brian


1 Answers

You need to enable STARTTLS. Add one more property to your configuration:

props.put("mail.smtp.starttls.enable", "true");
like image 126
Rob Harrop Avatar answered Oct 06 '22 00:10

Rob Harrop