Я делаю java приложение, которое отправляет электронные письма.
По какой-то причине я продолжал получать javax.mail.AuthenticationFailedException
, хотя у меня были правильные имя пользователя и пароль.
Я видел, как в некоторых сообщениях говорится, что отсутствие аутентификации по паролю может также вызвать это исключение, но я думаю, что у меня есть и эта часть. Теперь я застрял и не могу понять, где что-то не так go.
вот мой код:
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import javax.swing.*;
public class sendEmail {
private static String subject = "Test", content = "This is a test";
public sendEmail() {
}
public static void send() throws MessagingException{
Properties properties = new Properties();
properties.put("mail.smtp.auth","true");// set the authentication to true
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.host","smtp.gmail.com");
properties.put("mail.smtp.port","587");
String username = "clashroyale70532@gmail.com";
String password = "********";
Session ses = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPassWordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
ses.setDebug(true);
Message message = prepareMessage(ses,username);
Transport.send(message);
}
private static Message prepareMessage(Session session, String account) {
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(account));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(account));
msg.setSubject(subject);
msg.setText(content);
return msg;
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException m) {
throw new RuntimeException(m);
}
return null;
}
public static void main(String[] args) {
try {
sendEmail.send();
}
catch (MessagingException m) {
m.printStackTrace();
}
}
}
Вот вывод отладочной информации JavaMail:
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning
javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: protocolConnect returning false, host=smtp.gmail.com, user=*******(name not shown, it's my real name), password=<null>
Пользователь, которого он показывает, не связан с учетной записью электронной почты, которую я использовал в своем коде. Я не уверен, как он получил мое настоящее имя.