python 接口自动化发送邮件
时间: 2023-09-27 09:08:01 浏览: 119
你可以使用Python的smtplib库来实现自动化发送邮件的接口。
首先,你需要导入smtplib和email库:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
```
接下来,你可以编写一个函数来发送邮件,例如send_email:
```python
def send_email(sender, receiver, subject, message, attachment=None):
# 创建一个MIMEMultipart对象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(message, 'plain'))
# 如果有附件,添加附件
if attachment:
with open(attachment, 'rb') as file:
attachment_data = file.read()
attachment_part = MIMEApplication(attachment_data)
attachment_part.add_header('Content-Disposition', 'attachment', filename=attachment)
msg.attach(attachment_part)
# 连接SMTP服务器并发送邮件
with smtplib.SMTP('smtp.example.com', 587) as smtp:
smtp.starttls()
smtp.login('your_email@example.com', 'your_password')
smtp.send_message(msg)
```
在上述代码中,你需要替换以下内容:
- `'smtp.example.com'`:SMTP服务器地址,根据你自己
阅读全文