Java怎么接入Gmail SMTP发送邮件
时间: 2025-05-11 16:19:55 浏览: 14
### Java Gmail SMTP Email Sending Configuration Example
To send emails through Gmail's SMTP service using a Java program, one must configure an appropriate `Properties` object and utilize the JavaMail API. Below is a comprehensive guide with code examples.
#### Configuring Properties Object
The following properties need to be set when configuring the connection to Gmail’s SMTP server:
- **mail.smtp.host**: Specifies the host of the SMTP server.
- **mail.smtp.port**: Defines the port number used by the SMTP server (typically 587 for TLS).
- **mail.smtp.auth**: Indicates that authentication is required.
- **mail.smtp.starttls.enable**: Enables STARTTLS encryption for secure communication between client and server.
Here is how these settings look in practice:
```java
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); // Specify Gmail as the SMTP server[^3].
props.put("mail.smtp.port", "587"); // Use port 587 for TLS/STARTTLS[^4].
props.put("mail.smtp.auth", "true"); // Enable authentication.
props.put("mail.smtp.starttls.enable", "true");// Enable STARTTLS.
```
#### Authenticating with Gmail Credentials
Authentication requires providing valid credentials such as username (email address) and password or app-specific passwords if two-factor authentication is enabled on the account.
Below demonstrates creating a session with authenticator details:
```java
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) throws MessagingException {
final String username = "[email protected]";
final String password = "your-password";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props,
new Authenticator() { // Provide authentication mechanism.
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = prepareMessage(session); // Prepare email content.
Transport.send(message); // Send the prepared message.
System.out.println("Sent message successfully.");
}
private static Message prepareMessage(Session session) throws MessagingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]")); // Set sender address.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); // Add recipient(s).
message.setSubject("Test Subject"); // Define subject line.
message.setText("This is a test email body."); // Write text content.
return message;
}
}
```
#### Handling Errors Effectively
When dealing with potential issues during email transmission, consider implementing proper exception handling mechanisms within your application logic. For instance, catching exceptions related to network connectivity problems or invalid login attempts ensures robustness against runtime failures. Additionally, logging detailed information about encountered errors may assist debugging efforts significantly.
---
阅读全文
相关推荐

















