【发布时间】:2015-09-05 15:03:39
【问题描述】:
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
private Session session;
private final String username;
private final String password;
public MailSender(String username, String password) {
this.username = username;
this.password = password;
init(username, password);
}
public final void init(String username, String password) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MailSender.this.username, MailSender.this.password);
}
});
}
public boolean send(String recipient, String subject, String body) {
boolean status = false;
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
status = true;
} catch (MessagingException ex) {
Logger.getLogger(MailSender.class.getName()).log(Level.SEVERE, null, ex);
}
return status;
}
public static void main(String[] args) {
MailSender mailer = new MailSender("ganeshdatapoint@gmail.com", "******");
//Userprojects u=new Userprojects();
boolean status = mailer.send("ganeshdatapoint@gmail.com", "Testing Subject", "Testing message");
System.out.println(status);
}
}
例外:
我已使用正确的登录电子邮件 ID 和密码通过 JavamailAPI 编译和执行此程序,下面给出了我的可运行批处理文件命令
身份验证失败异常:534.5.7.14 https://account.google.com/continousSignIn
【问题讨论】:
-
“给出下面指定的例外”,然后没有指定。这是我们必须自己发现的那些巧妙的面试问题之一吗?最后一期
.是微型图形图像实际上将异常作为微文本保存吗?还是您只是忘记包含它? -
认证失败异常:534.5.7.14 account.google.com/continousSignIn
-
很明显您没有使用了正确的登录 ID 和密码。
-
也许 Gmail 对您尝试登录过于频繁但失败感到不满?你启用less secure apps了吗?
-
您有 Google 两步验证吗?如果是这样,您必须为您的应用程序生成一个新密码,您的普通密码将不起作用。 security.google.com/settings/security/apppasswords
标签: java email jakarta-mail