使用Simple Java Mail应该很简单:
Email email = new Email();
email.setFromAddress("lollypop", "lol.pop@somemail.com");
email.addRecipient("C.Cane", "candycane@candyshop.org", RecipientType.TO);
email.setText("We should meet up!");
email.setTextHTML("<b>We should meet up!</b>");
email.setSubject("hey");
new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);
如果您启用了双因素登录,则需要从您的 Google 帐户生成应用程序专用密码。
如果你还想自己做,这个库背后的代码很简单。它根据传递的TransportStrategy(plain、ssl 或 tls)在 Session 上设置特定属性,并使用 Authenticator 执行身份验证:
"mail.transport.protocol" : "smtp"
"mail.smtp.starttls.enable" : "true"
"mail.smtp.host" : host
"mail.smtp.port" : port
"mail.smtp.username" : username
"mail.smtp.auth" : "true"
和
return Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});