Java умеет отправлять письма через
SMTP без сторонних сервисов с помощью библиотеки javax.mail.Подключаем зависимость (
Maven):<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
Указываем настройки SMTP-сервера:
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Создаём сессию с логином и паролем:
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("you@example.com", "password");
}
});Готовим письмо:
Message msg = new MimeMessage(session);
msg.setFrom("you@example.com");
msg.setRecipients(Message.RecipientType.TO, "target@example.com");
msg.setSubject("Тестовое письмо");
msg.setText("Привет! Это письмо отправлено из Java.");
Отправляем:
Transport.send(msg);
🔥 Работает с Gmail, Яндексом, корпоративной почтой и любым
SMTP.👉 Java Ready | #совет