我编写了一个从java发送简单邮件的代码(javamail / jaf)。在我运行该程序后,我从谷歌收到一封电子邮件,我的帐户被不安全的设备/应用程序访问。然后我不得不更改我的Gmail帐户的设置,以允许登录“不太安全的应用程序”选项。然后我收到了该程序的电子邮件。
我需要发送电子邮件而不更改我的帐户中的选项允许“不太安全的应用”选项。请帮忙。
我的代码是:
import java.util.Properties;
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 SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("*****@gmail.com","*******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("*****@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("*****@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear User," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
答案 0 :(得分:1)
为Gmail避免此问题的唯一方法是使用OAuth 2.0身份验证。您可以通过此链接阅读相关内容。 https://developers.google.com/gmail/xoauth2_protocol?hl=en