我正在尝试使用 Java 发送电子邮件:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "abcd@example.com";
// Sender's email ID needs to be mentioned
String from = "web@example.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
我收到错误消息:
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
此代码可以发送电子邮件吗?
原文由 Mohit Bansal 发布,翻译遵循 CC BY-SA 4.0 许可协议
以下代码适用于 Google SMTP 服务器。您需要提供您的 Google 用户名和密码。
2015 年 12 月 11 日更新
用户名+密码不再是推荐的解决方案。这是因为
Google 发布了 Gmail API - https://developers.google.com/gmail/api/?hl=en 。我们应该使用 oAuth2 方法,而不是用户名 + 密码。
这是使用 Gmail API 的代码片段。
GoogleMail.java
要通过 oAuth2 构建授权的 Gmail 服务,这里是代码片段。
实用程序.java
为了提供一种用户友好的 oAuth2 身份验证方式,我使用了 JavaFX 来显示以下输入对话框
显示用户友好的 oAuth2 对话框的关键可以在 MyAuthorizationCodeInstalledApp.java 和 SimpleSwingBrowser.java 中找到