自动运行导出到Excel并通过Outlook发送结果任务,通常涉及以下几个基础概念:
openpyxl
或pandas
)来创建、读取和写入Excel文件。以下是一个简单的Python脚本示例,展示如何将数据导出到Excel并通过Outlook发送邮件:
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 创建一个简单的数据集
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)
# 导出到Excel文件
excel_file_path = 'output.xlsx'
df.to_excel(excel_file_path, index=False)
# 设置Outlook邮件发送
sender_email = 'your_email@example.com'
receiver_email = 'recipient_email@example.com'
password = 'your_password'
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = 'Automated Excel Report'
body = 'Please find the attached Excel report.'
msg.attach(MIMEText(body, 'plain'))
with open(excel_file_path, "rb") as attachment:
part = MIMEApplication(attachment.read(), Name="output.xlsx")
part['Content-Disposition'] = f'attachment; filename="output.xlsx"'
msg.attach(part)
# 发送邮件
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(sender_email, password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()
print("Email sent successfully!")
openpyxl
或pandas
库。通过以上步骤和示例代码,你可以实现一个自动运行导出到Excel并通过Outlook发送结果的任务。
领取专属 10元无门槛券
手把手带您无忧上云