我在android上试用了一个电子邮件应用程序。我首先使用用户名和密码 然后在下一个活动中,我会收到收件人地址主题和消息并发送电子邮件。 我收到错误 JavaX身份验证失败。这是我的邮件身份验证和发送代码。发送按钮的单击功能调用此类
public class MailHandler {
final String username;
final String password;
public MailHandler(String username,String password){
this.username=username;
this.password=password;
}
public void sendMail(String Sub,String msg,String sender,String cc,String to) {
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.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(Sub);
message.setText(msg);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
答案 0 :(得分:2)
一个简单的解决方案是使用最终的String
参数,例如
public void sendMail(final String username ,final String password );
。
答案 1 :(得分:1)
您的代码有效。我复制它编译并使用我的gmail凭据运行它。您确定使用正确的gmail凭据发送邮件吗?
MailHandler m = new MailHandler("myAccount@gmail.com", "myPassword");
m.sendMail("Test", "Testing", "myOtherAccount@gmail.com", "myWork@myCompany.com", "myOtherWork@myCompany.com");
//运行后,我查看了工作电子邮件,看到了消息。
如果我使用无效密码,我会得到以下statcktrace。这就是你所看到的
535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 jl8sm4152932obb.18
at MailHandler.sendMail(MailHandler.java:50)
at MailHandler.main(MailHandler.java:56)
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 jl8sm4151848obb.18
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at MailHandler.sendMail(MailHandler.java:45)
... 1 more