如何使用python给别人发邮件
时间: 2023-07-20 10:06:42 浏览: 51
你可以使用 Python 的内置 `smtplib` 模块来发送邮件。以下是一个例子:
```python
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
# 设置发件人和收件人
sender_email = 'your_email@example.com'
recipient_email = 'recipient_email@example.com'
# 创建邮件内容
message = MIMEText('Hello, this is a test email from Python!')
message['From'] = formataddr(('Sender Name', sender_email))
message['To'] = formataddr(('Recipient Name', recipient_email))
message['Subject'] = 'Test Email'
# 发送邮件
try:
smtp_server = smtplib.SMTP('smtp.example.com', 587)
smtp_server.starttls()
smtp_server.login(sender_email, 'your_password')
smtp_server.sendmail(sender_email, [recipient_email], message.as_string())
smtp_server.quit()
print('Email sent successfully!')
except Exception as e:
print('Error:', e)
```
在这个例子中,我们使用 `smtplib` 模块连接到 SMTP 服务器并身份验证,然后使用 `sendmail()` 方法发送邮件。要发送 HTML 内容的电子邮件,请使用 `MIMEText` 类并将内容类型设置为 `text/html`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)