private class SendEmailTask extends AsyncTask<String, Void, Boolean> {
private String host;
private String port;
private String username;
private String password;
private String subject;
private String body;
public SendEmailTask(String host, String port, String username, String password, String subject, String body) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.subject = subject;
this.body = body;
}
@Override
protected Boolean doInBackground(String... params) {
String toAddress = params[0];
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
return true;
} catch (MessagingException e) {
Log.e("Email", "Error sending email: " + e.getMessage());
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
Log.i("Email", "Email sent successfully.");
} else {
Log.e("Email", "Error sending email.");
}
}
}
调用方法:
SendEmailTask task = new SendEmailTask("smtp.163.com", "465", "your_email@163.com", "your_password(服务授权码)", "title", "body");
task.execute(email); //email对应的是收件人的邮箱