python将csv文件发送到邮箱
时间: 2023-08-30 10:12:19 浏览: 45
可以使用Python的smtplib和email库来实现将CSV文件发送到邮箱。
以下是一个简单的示例代码:
```python
import smtplib
import os
import csv
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 设置发件人和收件人
sender_email = 'your_email@example.com'
receiver_email = 'recipient_email@example.com'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = 'CSV File'
# 读取CSV文件并附加到邮件中
file_path = 'path_to_csv_file.csv'
with open(file_path, 'r') as file:
csv_data = file.read()
csv_attachment = MIMEApplication(csv_data, _subtype='csv')
csv_attachment.add_header('content-disposition', 'attachment', filename=os.path.basename(file_path))
msg.attach(csv_attachment)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_email@example.com'
smtp_password = 'your_email_password'
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
smtp.starttls()
smtp.login(smtp_username, smtp_password)
smtp.send_message(msg)
```
请注意,您需要将示例代码中的电子邮件和SMTP服务器详细信息替换为您自己的详细信息,并将"file_path"替换为您要发送的CSV文件的路径。