无法使用Java代码
问题描述:
package abc;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
public static void main(String[] args) {
// TODO Auto-generated method stub
String to="[email protected]";
String from="[email protected]";
final String username="from";
final String password="password";
Properties properties=new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", "587");
Session session=Session.getInstance(properties,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
}
);
try{
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Mail");
message.setText("Hey I wrote a java code to send mail. Thanks ");
Transport.send(message);
System.out.println("Sent Mail :)");
}
catch(MessagingException e){
e.printStackTrace();
}
}
}
从Gmail发送邮件,我得到了以下errror whene我试图运行上面的代码::无法使用Java代码
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvHc
534-5.7.14 gCjfbim5WYCDTQee6sZlZ2d31nncueOizOcz9NieexN5nSlGr0c49lSZ43qc4RQPQvpWLH
534-5.7.14 qCUQUecjIR7qxdYJ5R_WgLxkzD9u4Ds3EEG7ceSMyTZg0dpSGJb-zl5C82YDTdLOYTX5Pl
534-5.7.14 tmEfWrmktFCdAxUjtDiPNruDLqhPSIZ9dd187tQjBtOw2X8zx7MUcysN9BRawwDmbXT6mJ
534-5.7.14 cLn_sJS5UBuqommn0uJK7W1tPZzU> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 qy7sm48619995pab.34 - gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at abc.SendMail.main(SendMail.java:36)
Gmail没有让这个代码。我甚至收到了一封来自gmail的关于可疑登录信息的邮件,并回顾了我运行此代码的地方。解决办法是什么 ?
答
它是AuthenticationFailedException,你应该使用真正的用户名和密码组合,以使程序工作,并应该访问您的程序登录到下面详细解释的gmail。
而且你也应该检查这一点,以便访问你的程序发送邮件,整个答案在堆栈跟踪中给出的链接;
https://support.google.com/mail/answer/78754
你必须做的是(如上面的链接解释);
- 授予您的用户访问权限;
https://accounts.google.com/DisplayUnlockCaptcha
- 给访问安全性较低的登录;
https://www.google.com/settings/security/lesssecureapps
此后,如果再次尝试运行与有效参数你的代码,测试邮件将被发送。
我正在尝试使用我的真实密码和编号,但编辑了代码在此处发帖。感谢您的解决方案! :) – PP93