且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 如何在电子邮件中发送多个文件.我可以发送 1 个文件,但如何发送 1 个以上的文件

更新时间:2023-10-23 19:35:16

如果您想将文件附加到电子邮件中,您可以使用迭代文件并将它们附加到邮件中.您可能还想在正文中添加一些文本.代码如下:

If you want to attach files to the email you can use just iterate over files and attach them to the message. You also may want to add some text to the body. Here is the code:

import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_selenium_report():
    dir_path = "G:/test_runners/selenium_regression_test_5_1_1/TestReport"
    files = ["SeleniumTestReport_part1.html", "SeleniumTestReport_part2.html", "SeleniumTestReport_part3.html"]

    msg = MIMEMultipart()
    msg['To'] = "4_server_dev@company.com"
    msg['From'] = "system@company.com"
    msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"

    body = MIMEText('Test results attached.', 'html', 'utf-8')  
    msg.attach(body)  # add message body (text or html)

    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)

    s = smtplib.SMTP()
    s.connect(host=SMTP_SERVER)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    print 'done!'
    s.close()