smtp发送邮件 java
时间: 2023-11-04 19:54:05 浏览: 67
SMTP(Simple Mail Transfer Protocol)是一种用于发送电子邮件的标准协议。在Java中,可以使用JavaMail API来实现基于SMTP发送邮件的功能。具体实现步骤如下:
1. 导入JavaMail API相关的依赖库。
2. 创建一个JavaMail session对象,用于与SMTP服务器进行通信。
3. 配置SMTP服务器的相关信息,如服务器地址、端口号、用户名、密码等。
4. 创建一个MimeMessage对象,用于表示待发送的邮件。
5. 设置邮件的发件人、收件人、主题和正文内容。
6. 发送邮件。
下面是一个简单的示例代码,展示了如何使用JavaMail API发送一封邮件:
```java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 配置SMTP服务器的相关信息
String host = "smtp.example.com";
String port = "587";
String username = "yourusername";
String password = "yourpassword";
// 设置发件人和收件人
String from = "sender@example.com";
String to = "recipient@example.com";
// 设置邮件主题和正文
String subject = "Hello, World!";
String body = "This is a test email.";
// 创建一个Properties对象,用于设置SMTP服务器的配置信息
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.starttls.enable", "true");
// 创建一个Session对象,用于与SMTP服务器进行通信
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建一个MimeMessage对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)