I am trying to configure an email sender in java. I have a google account that I have configured the SMTP server and I created an app password for the account.
I then added the following configuration into my application.yml :
mail:
host: smtp.gmail.com
port: 587
username: MY_EMAIL
password: MY_PASSWORD
properties:
mail:
smtp:
trust: "*"
auth: true
starttls:
enabled: true
required: true
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
This is my email sender class:
@Service
@RequiredArgsConstructor
public class EmailService {
@Value("${spring.mail.username}")
private String mailOrigin;
private final JavaMailSender mailSender;
private final SpringTemplateEngine templateEngine;
@Async
public void sendEmail(String to, String userName, EmailTemplateName emailTemplate, String confirmationUrl, String activationCode, String subject) throws MessagingException{
String templateName;
if(emailTemplate == null){
templateName = "confirm-email";
}else{
templateName = emailTemplate.getName();
}
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED, StandardCharsets.UTF_8.name());
Map<String,Object> properties = new HashMap<>();
properties.put("username", userName);
properties.put("confirmationUrl", confirmationUrl);
properties.put("activation_code", activationCode);
Context context = new Context();
context.setVariables(properties);
helper.setFrom(mailOrigin);
helper.setTo(to);
helper.setSubject(subject);
String template = templateEngine.process(templateName, context);
helper.setText(template, true);
mailSender.send(mimeMessage);
}
}
However, I still get the following exception when trying to send emails:
org.springframework.mail.MailSendException: Failed messages:
org.eclipse.angus.mail.smtp.SMTPSendFailedException: 530-5.7.0 Must issue a STARTTLS
command first. For more information, go to
530-5.7.0 https://support.google.com/a/answer/3221692 and review RFC 3207
530 5.7.0 specifications. 5b1f17b1804b1-432da24498csm101062995e9.1 - gsmtp
What am I doing wrong here? From my understanding the JavaMailSender should already configure the session based on my inputs on the application.yml right?
Was able to solve the issue. Actually was just an indentation issue on my application.yml
.
The starttls
should be inside the smtp
like this:
mail:
smtp:
trust: "*"
auth: true
starttls:
enabled: true
required: true
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000