python发送邮件的方法
时间: 2023-10-12 12:55:49 浏览: 47
Python发送邮件的方法可以使用smtplib库。以下是一个简单的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(sender_email, receiver_email, subject, body, smtp_server, smtp_port, username, password):
# 创建邮件对象
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = subject
# 添加正文
message.attach(MIMEText(body, 'plain'))
# 创建SMTP连接
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# 登录SMTP服务器
server.login(username, password)
# 发送邮件
server.send_message(message)
# 关闭连接
server.quit()
# 示例用法
sender_email = 'sender@example.com'
receiver_email = 'receiver@example.com'
subject = 'Hello from Python'
body = 'This is a test email sent from Python.'
smtp_server = 'smtp.example.com'
smtp_port = 587 # SMTP端口号,一般为587或465
username = 'your_username'
password = 'your_password'
send_email(sender_email, receiver_email, subject, body, smtp_server, smtp_port, username, password)
```
你需要替换示例中的发件人、收件人、SMTP服务器、用户名和密码等信息来符合你的实际需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)