Python 如何在电子邮件中发送多个文件.我可以发送 1 个文件,但如何发送 1 个以上的文件 [英] Python how do i send multiple files in the email. I can send 1 file but how to send more than 1

查看:80
本文介绍了Python 如何在电子邮件中发送多个文件.我可以发送 1 个文件,但如何发送 1 个以上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码在 Python 的电子邮件中发送 html 文件 SeleniumTestReport_part1.html.我想在电子邮件中发送 1 个以上的文件.我该怎么做?

I have the following code to send a html file SeleniumTestReport_part1.html in an email in Python. I want to send more than 1 file in the email. How do can i do this?

我要发送的文件是:SeleniumTestReport_part1.htmlSeleniumTestReport_part2.html
SeleniumTestReport_part3.html

The files I want to send are: SeleniumTestReport_part1.html SeleniumTestReport_part2.html
SeleniumTestReport_part3.html

我发送 1 个文件的代码是:

My code to send 1 file is:

def send_selenium_report():
    fileToSend = r"G:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part1.html"
    with open(fileToSend, "rt") as f:
        text = f.read()
    msg = MIMEText(text, "html")
    msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"
    msg['to'] = "4_server_dev@company.com"
    msg['From'] = "system@company.com"

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

谢谢,里亚兹

推荐答案

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

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()

这篇关于Python 如何在电子邮件中发送多个文件.我可以发送 1 个文件,但如何发送 1 个以上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆