python发送邮件带附件
时间: 2023-10-17 07:18:42 浏览: 104
可以使用 Python 的内置模块 `smtplib` 和 `email` 来发送带附件的邮件。以下是一个示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件服务器地址和端口
smtp_server = 'smtp.example.com'
smtp_port = 587
# 发件人邮箱和密码
sender_email = 'sender@example.com'
sender_password = 'password'
# 收件人邮箱
receiver_email = 'receiver@example.com'
# 创建带附件的邮件对象
message = MIMEMultipart()
message['Subject'] = '这是一封带附件的邮件'
message['From'] = sender_email
message['To'] = receiver_email
# 邮件正文
text = MIMEText('这是邮件正文')
message.attach(text)
# 附件
with open('example.pdf', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='pdf')
attachment.add_header('Content-Disposition', 'attachment', filename='example.pdf')
message.attach(attachment)
# 登录邮件服务器并发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, message.as_string())
```
注意,需要将 `smtp_server`、`smtp_port`、`sender_email`、`sender_password`、`receiver_email` 和附件的路径等信息替换成实际值。
阅读全文