当任务调度器用于运行scrip时,Python脚本不附加PDF附件

2024-04-26 03:50:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下程序发送带有pdf附件的电子邮件。程序运行成功,我收到了带有附件的电子邮件,但是当我使用任务调度器运行程序时,我收到了带有正文但没有附件的电子邮件。原因是什么?我需要这个程序运行和发送电子邮件在每天晚上7点。有没有其他方法可以让程序在不使用任务调度器的情况下在特定时间运行?你知道吗

以下是我的程序:

    import smtplib
    import os
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email import encoders
    from os import path
    from glob import glob

    email_user = '#sender address#'
    email_send = '#reciever address#'
    subject = 'Subject'

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = email_send
    msg['Subject'] = subject

    body = "Hello:\nPlease find attached the reports"
    msg.attach(MIMEText(body, 'plain'))

    path = (r'''#path of the files to be attached''')
    files = [f for f in os.listdir(path) if os.path.isfile(f)]
    filenames = filter(lambda f: f.endswith(('.pdf','.PDF')), files)
    for filename in filenames:
        attachment = open(filename, 'rb')
        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',"attachment; filename = 
           "+filename)

        msg.attach(part)
    text = msg.as_string()
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.starttls()
    server.login(email_user,'#password#')


    server.sendmail(email_user,email_send,text)
    server.quit()

Tags: pathtextfromimport程序附件serveros
1条回答
网友
1楼 · 发布于 2024-04-26 03:50:12

os.listdir剥离路径信息,因此只有当工作目录与“path”中的目录相同时,此脚本才会工作。你的任务调度程序显然不在那里工作。所以您需要提供完整的路径:

path = (r'''#path of the files to be attached''')
files = [os.path.join(path, f) for f in os.listdir(path)]
files = filter(os.path.isfile, files)

我看到你进口了glob,但你不用。这将是最好的方法,因为它返回完整路径,并且可以进行扩展过滤。您可以使其不区分大小写,如下所示:

files = glob(os.path.join(path, '*.[pD][dD][fF]'))

相关问题 更多 >

    热门问题