I have this class that is sending emails ok from the same server using localhost, but when sending emails from another IP, and setting the host like this:
@Service
@Slf4j
@Transactional(readOnly = true)
public class MailMessageService extends SimpleMailMessage {
static Properties prop = new Properties();
public MailMessageService() {
super();
}
public void sendMessage(String subject, String body, String mailTo, String pathToFile) throws MessagingException, IOException {
log.info("Sending email to: *{}* ", mailTo);
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("info", "oT2ct2UUii87");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("info@taradell.com.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));
message.setSubject(subject);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(body, "text/html; charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
log.info("pathToFile: *{}* ", pathToFile);
if (pathToFile != null) {
MimeBodyPart attachment = new MimeBodyPart();
attachment.attachFile(pathToFile);
multipart.addBodyPart(attachment);
}
log.info("Setting content");
message.setContent(multipart);
log.info("Sending message {} ", message);
Transport.send(message);
}
public void sendMessage(String subject, String body, String mailTo) throws MessagingException, IOException {
sendMessage(subject, body, mailTo, null);
}
@PostConstruct
public void initProperties() {
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "172.105.90.58");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "172.105.90.58");
}
}
I have this errors:
jakarta.mail.MessagingException: Could not convert socket to TLS
at org.eclipse.angus.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2173)
at org.eclipse.angus.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:741)
at jakarta.mail.Service.connect(Service.java:367)
at jakarta.mail.Service.connect(Service.java:225)
at jakarta.mail.Service.connect(Service.java:174)
at jakarta.mail.Transport.send0(Transport.java:232)
at jakarta.mail.Transport.send(Transport.java:102)
Looking at your error "Could not convert socket to TLS", you're having a TLS negotiation issue with your SMTP server. Here's how to fix it:
Try a different port with proper TLS settings:
prop.put("mail.smtp.port", "587"); // for STARTTLS
Or just copy/paste this:
@PostConstruct
public void initProperties() {
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "live.smtp.mailtrap.io");
prop.put("mail.smtp.port", "587");
}
// In your Authenticator:
return new PasswordAuthentication("username", "password");
Disclaimer: I've crafted the answer based on this tutorial.