如何使用Python指定新目录路径以在邮件中添加附件



我正在使用以下代码将附件添加到邮件中并发送。在下面的代码中,与脚本相同的目录中存在的文件。

我的代码位于" TestDir"文件夹中,并且要附加的文件在" TestDir/TestFiles"文件夹中。我如何更改下面的目录路径,以便将文件附加在'testdir/testfiles'文件夹中。

Code :
import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import Encoders
import os
def send_email(to, subject, text, filenames):
    try:
        gmail_user = 'xxxxx@gmail.com'
        gmail_pwd = 'xxxxx'
        msg = MIMEMultipart()
        msg['From'] = gmail_user
        msg['To'] = ", ".join(to)
        msg['Subject'] = subject
        msg.attach(MIMEText(text))
        for file in filenames:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(file, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file))
            msg.attach(part)
        mailServer = smtplib.SMTP("smtp.gmail.com:587")
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, to, msg.as_string())
        mailServer.close()
        print('successfully sent the mail')
    except smtplib.SMTPException,error:
        print str(error)
if __name__ == '__main__':
    attachment_file = ['t2.csv','t1.txt']
    to = "xxxxx@gmail.com"
    TEXT = "Hello everyone"
    SUBJECT = "Testing sending using gmail"
    send_email(to, SUBJECT, TEXT, attachment_file)

我创建了一个新的目录'testfiles',并将所有文件放入其中,并使用OS.listDir列出其中的文件。并在所有文件上迭代并将其附加到邮件中。

更新用于将文件附加到邮件的代码:

        dir_path = "/home/testdir/testfiles"
        files = os.listdir("testfiles")
        for f in files:  # add files to the message
            file_path = os.path.join(dir_path, f)
            attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
            attachment.add_header('Content-Disposition', 'attachment', filename=f)
            msg.attach(attachment)

我认为您的第二个代码段有一个错误。files = os.listdir(" testfiles"(应为files = os.listdir('dir_path; quath&quot(

最新更新