1

Я хочу сделать утилиту для отправки электронных писем. Нашел библиотеку JavaMail. Скачал её и нашел простенькую программу на ней. Я воспользовался eclipse для написания кода, он ошибок в синтаксисе не нашел. Вот код:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {
    final String senderEmailID = "myemailt@gmail.com";
    final String senderPassword = "admin";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "465";
    String receiverEmailID = null;
    static String emailSubject = "Test Mail";
    static String emailBody = ":)";

    public SendEmail(
            String receiverEmailID,
            String emailSubject,
            String emailBody
    ) {
        this.receiverEmailID = receiverEmailID;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;
        Properties props = new Properties();
        props.put("mail.smtp.user", senderEmailID);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        SecurityManager security = System.getSecurityManager();
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmailID));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmailID));
            Transport.send(msg);
            System.out.println("Message send Successfully:)");
        } catch (Exception mex) {
            mex.printStackTrace();
        }
    }

    public class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderEmailID, senderPassword);
        }
    }

    public static void main(String[] args) {
        SendEmail mailSender = new
                SendEmail("my2email@gmail.com", emailSubject, emailBody);
    }
}

При компиляции вылетает ошибка:

Error: Unable to initialize main class SendEmail
Caused by: java.lang.NoClassDefFoundError: javax/mail/Authenticator

Помогите решить проблему.

1 ответ 1

1

Решение находится в очень неожиданном месте, а именно: при работе с google mail необходимо вот здесь включить опцию "Небезопасные приложения заблокированы" по ссылке: https://myaccount.google.com/lesssecureapps?pli=1

1
  • 1
    Уже включены небезопасные приложения, ошибка была в установленной библиотеке, не было пару пакетов, но спасибо за ответ)
    – merive
    1 мая 2020 в 18:51

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.