我想创建一个函数,可以向任何指定的收件人(gmail)发送电子邮件。但遇到的问题是,当我提供使用两步验证的凭据时,我的身份验证失败。对于没有两步验证的帐户,它可以正常工作。那么我该怎么做才能在启用两步身份验证的情况下实现此功能呢?
以下是我用来发送电子邮件的代码:
public static boolean sendMail(String fromMail, String fromPassword, String toMail, String message) {
try {
final String user = fromMail, password = fromPassword;
Properties prop = new Properties();
prop.setProperty("mail.smtp.host", "smtp.gmail.com");
prop.setProperty("mail.smtp.port", "465");
prop.setProperty("mail.smtp.auth", "true");
prop.setProperty("mail.smtp.ssl.enable", "true");
// prop.put("mail.debug", "true");
// prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(user, password);
}
});
// Session sess=Session.getDefaultInstance(prop);
sess.setDebug(true);
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(fromMail));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
msg.setText(message);
msg.setContent(message, "text/html");
Transport.send(msg);
return true;
} catch (MessagingException msgEx) {
msgEx.printStackTrace();
return false;
}
}