JavaMail API - пример отправки электронной почты через Gmail SMTP
В этой статье мы покажем вам, как отправить электронное письмо через SMTP-сервер Gmail.
Для отправки электронной почты на Java нам понадобитсяJavaMail
pom.xml
com.sun.mail javax.mail 1.6.2
1. Gmail SMTP через TLS
SMTP = smtp.gmail.com Port = 587
SendEmailTLS.java
package com.example; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class SendEmailTLS { public static void main(String[] args) { final String username = "[email protected]"; final String password = "password"; Properties prop = new Properties(); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.port", "587"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); //TLS Session session = Session.getInstance(prop, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients( Message.RecipientType.TO, InternetAddress.parse("[email protected], [email protected]") ); message.setSubject("Testing Gmail TLS"); message.setText("Dear Mail Crawler," + "\n\n Please do not spam my email!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } }
2. Gmail через SSL
2.1 The logic is the same, just pass in different properties values.
SMTP = smtp.gmail.com Port = 465
SendEmailSSL.java
package com.example; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class SendEmailSSL { public static void main(String[] args) { final String username = "[email protected]"; final String password = "password"; Properties prop = new Properties(); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.port", "465"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.socketFactory.port", "465"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session session = Session.getInstance(prop, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients( Message.RecipientType.TO, InternetAddress.parse("[email protected], [email protected]") ); message.setSubject("Testing Gmail SSL"); message.setText("Dear Mail Crawler," + "\n\n Please do not spam my email!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } }
3. Требуется пароль для конкретного приложения
3.1 If 2-Step verification is ON. Мы получим следующее сообщение об ошибке:
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at 534 5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor - gsmtp at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965) at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780) at javax.mail.Service.connect(Service.java:388) at javax.mail.Service.connect(Service.java:246) at javax.mail.Service.connect(Service.java:195) at javax.mail.Transport.send0(Transport.java:254) at javax.mail.Transport.send(Transport.java:124) at com.example.calculator.SendEmail.main(SendEmail.java:41)
3.2 To fix it, follow this guide to create an App Password
Никакой разницы в коде, просто вместо него ставится только что сгенерированный пароль приложения.
SendEmail.java
package com.example; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class SendEmail { public static void main(String[] args) { final String username = "[email protected]"; final String password = "puts your app password here"; // update here // same code... } }
java.net.UnknownHostException: smtp.gmail.com
Убедитесь, что брандмауэр или прокси-сервер не заблокировал этотsmtp.gmail.com