【发布时间】:2016-01-23 18:21:14
【问题描述】:
我已经编写了一个从 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);
}
}
}
【问题讨论】:
标签: java email smtp gmail jakarta-mail