1

我正在android上尝试一个电子邮件应用程序。我首先输入用户名和密码,
然后在下一个活动中我接受收件人地址主题和味精并发送电子邮件。我收到错误JavaX 身份验证失败。这是我的邮件身份验证和发送代码。发送按钮的 OnClick 函数调用此类

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);
    }
}
}
4

2 回答 2

2

一个简单的解决方案是使用最终String参数,例如 public void sendMail(final String username ,final String password );.

于 2012-10-31T15:41:36.633 回答
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
于 2012-08-16T14:44:19.770 回答