I am working on Java Spring, Maven and I am trying to send a mail on gmail, using a gmail id. I am getting this error:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 11sm885884pfp.38 - gsmtp
even through I have set the parameter
mail.smtp.starttls.enable
to true.
This is my function:
public String sendMail(String to, String subject, String textMessage) throws IOException {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = from@gmail.com;
InternetAddress toAddress = null;
try {
toAddress = new InternetAddress(to);
} catch (AddressException e) {
System.out.print("\nError in Address of Sender or reciever\n");
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(textMessage);
SMTPTransport t = (SMTPTransport) mailSession.getTransport("smtp");
t.setStartTLS(true);
t.connect("smtp.gmail.com", "from@gmail.com", "from.password!");
t.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
t.close();
} catch (MessagingException e) {
System.out.print("\nError in message Genration\n");
e.printStackTrace();
}
return "success";
}
All the answers on SO tell us to set mail.smtp.starttls.enable to true. Doing that even does not work.
I have also included the javax.mail dependency in my pom as:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
When you're using spring, it's better to incorporate their abstractions instead of javax.mail
low level API. In fact, you can use JavaMailSender
and its implementation, JavaMailSenderImpl
, to achieve the same result. See this for an example.