TLS issue when sending to gmail through JavaMail

Viewed 28351

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", "blahblah@gmail.com");
    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("blahblah2@gmail.com"));

    transport.connect();
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
4 Answers
package enviando_email.enviando_email;
import static org.junit.Assert.assertTrue;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Test;

/**
 * Unit test for simple App.
 */

public class AppTest 
{

    @org.junit.Test
    public void testEmail() {
        
          final String username = "yourusername";
          final String password = "yourpass";
        
        try {
            
            Properties properties = new Properties(); 
            properties.put("mail.smtp.auth", "true"); /*autorizacao*/
            properties.put("mail.smtp.starttls.enable", "true"); /* autenticacação*/
            properties.put("mail.smtp.host", "smtp-mail.outlook.com"); /* servidor do gmail */
            properties.put("mail.smtp.port", "587"); /* porta de saida do servidor */
            properties.put("mail.smtp.socketFactory.port", "587"); /* especifica a porta a ser conectada pelo socket */
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); /* classe do socket de conexão SMTP */
            
            //cria sessão - recebe objeto autorizado para se manter na sessão 
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            
            Address[] toUser = InternetAddress.parse("recipient1@hotmail.com,recipient2@gmail.com");
            
            Message message = new MimeMessage(session); //pega sessão válida 
            message.setFrom(new InternetAddress(username)); //pega o usuario que iniciou a sessão e envia mensagem por ele
            message.setRecipients(Message.RecipientType.TO, toUser); //para quem enviar email 
            message.setSubject("Chegou assunto do e-mail"); //Assunto do e-mail
            message.setText("Olá esse e-mail está sendo enviado pelo java mail");
            
            Transport.send(message);
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
Related