【发布时间】:2014-08-31 04:16:23
【问题描述】:
我正在尝试从应用程序发送电子邮件,我使用以下代码:
private static final String username = "sth@gmail.com";
private static final String password = "pass";
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sth@gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
private class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SendQuestion.this, "Please wait", "Sending mail", true, false);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
@Override
protected Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
Eclipse 抛出 javax.mail.AuthenticationFailedException。当我第一次尝试发送邮件时,我的 gmail 帐户收到了来自 Google 的关于安全性的邮件,并且他们阻止了该邮件。然后我在 /lesssecureapps 激活我想允许不太安全的应用程序。但这并没有解决它。是我的代码有问题还是 gmail 问题?
PS:我已经添加了所有必要的 .jar 并包含了对清单的 Internet 访问权限
【问题讨论】: