python拆分Excel数据,自动发邮箱

查看 45|回复 1
作者:Eks6666   
[Python] 纯文本查看 复制代码
import pandas as pd
import poplib  
import email  
from email.header import decode_header
from email.parser import Parser
df = pd.read_excel("年假明细表.xlsx")
depts = df["部门"].unique()
for dept in depts:
    department_df = df[df["部门"] == dept]
    filename = f"{dept}_年假情况.xlsx"
    department_df.to_excel(filename, index=False)
def send_email_with_attachment(
        sender_email, recipient_email, subject, body, attachment_path, userName_AuthCode, attach_name):
    # 邮箱服务端
    message = MIMEMultipart()
    # email = MIMEText(content, 'plain', 'utf-8')
    message['Subject'] = subject  # 定义邮件主题
    message['From'] = "AI通知机器人"  # 发件人
    message['To'] = ",".join(recipient_email)  # 收件人(可以添加多个,若只有一个收件人,可直接写邮箱号)
    body = body
    # 邮件正文
    message.attach(MIMEText(body, 'plain'))
    # 发送邮件
    attachment = open(attachment_path, "rb")
    part = MIMEBase("application", "octet-stream")
    # 设置附件信息
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition",
                    "attachment; filename=attach_name")
    message.attach(part)
    # 添加附件到邮件
    # message.attach(part)
    # QQ邮箱的端口号是465,其他邮箱的端口号可自行百度,非QQ邮箱,一般使用SMTP即可,不需要有SSL
    smtp = smtplib.SMTP_SSL(mailserver, port=465)
    smtp.login(sender_email, userName_AuthCode)
    smtp.sendmail(sender_email, ','.join(
        recipient_email), message.as_string())
    smtp.quit()
    # logging.info('恭喜,邮件发送成功了')
if __name__ == "__main__":
    # split_Excel("年假情况.xlsx", "年假_按部门汇总")
    mailserver = 'smtp.163.com'
    # 发件人-填写自己的邮箱
    sender_email = '[email protected]'
    # 邮箱发件授权码-为发件人生成的授权码,具体步骤见文章中截图
    userName_AuthCode = 'OCRSEVQEMWCIXKNY'
    # 定义邮件的接收者-我随便写的,若收件人较多,可用列表表示
    # recipient_email = ['[email protected]']
    subject = '你们部门的年假情况'
    body = '附件是你们部门的年年假情况,请查阅'
    department_emails = {
        "采购部": ['[email protected]', "[email protected]"],  # 可以添加多个收件人
        "船务部": ['[email protected]'],
        # ...其他部门
    }
    df = pd.read_excel("年假情况.xlsx")
    depts = ["采购部", "船务部"]
    for dept in depts:
        attachment_path = f'年假_按部门汇总\年假情况_{dept}.xlsx'  # 附件路径
        recipient_email = department_emails.get(dept)
        print(recipient_email)
        attach_name = f"年假情况_{dept}"
        send_email_with_attachment(
            sender_email, recipient_email, subject, body, attachment_path, userName_AuthCode, attach_name)

年假, 邮箱

zylz9941   

小白坐等成品
您需要登录后才可以回帖 登录 | 立即注册

返回顶部