Python通过邮件发送文件
时间: 2024-05-27 14:06:35 浏览: 83
Python可以通过邮件发送文件,可以使用smtplib和email模块来实现。以下是一个示例代码:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 发送邮件的基本信息
sender = 'youremail@yourdomain.com'
password = 'yourpassword'
receiver = 'receiveremail@receiverdomain.com'
subject = 'Email Subject'
# 创建邮件对象,并添加邮件内容
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
# 添加邮件正文
body = 'Email Body'
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open('filename', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename='filename.txt')
msg.attach(attachment)
# 发送邮件
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, password)
text = msg.as_string()
server.sendmail(sender, receiver, text)
print('Email sent successfully!')
except Exception as e:
print(e)
finally:
server.quit()
```
这个示例代码通过SMTP服务器发送邮件。需要注意的是,如果使用Gmail邮箱发送邮件,需要在Gmail账户中开启\"允许安全性较低的应用程序\"选项。同时,需要修改代码中的SMTP服务器地址和端口号,以及发件人、收件人、附件等相关信息。
阅读全文