【问题标题】:text file not embedded into HTML when sending email via Python通过 Python 发送电子邮件时,文本文件未嵌入 HTML
【发布时间】:2021-12-29 18:05:29
【问题描述】:

我有这个 python 代码使用 MIME 在 gmail 服务器上发送收据。

email["Subject"] = "Your PetShop reciept"
    email["From"] = sender
    email["To"] = reciever 
    
    plain = f"""\
    Hi {name}, thank you for shopping with us!
    Below is your eReciept:
    {reciept}
    
    We hope you have a lovely day!
    ----------------------------------------------
    If you are having trouble viewing this message
    please contact our customer service helpline:
    12334
"""
    
    html = f"""
<html>
    
    <body style="background-color:#33476c">
        <h1 style="font-family:Arial">Hi {name}, thanks for shopping with us!</h1>
        <h3 style="font-family:Arial">Below is your eReciept:</h3>
        <br>
        </br>
        <object data="hi.txt" type="text/plain"
            width="500" style="height: 300px">
        <a href="hi.txt">No Support?</a>
        </object>
        <p style="font-size:24px">------------------------------------------------------------------------------------------------------------------------------------------</p>
        <p style="font-size:14px">If you are having issues accessing this email,
        please feel free to call our customer service helpline 12344</p>
    </body>
</html>"""
    part1 = MIMEText(plain,"plain")
    part2 = MIMEText(html,"html")
    
    email.attach(part1)
    email.attach(part2)

但是我想嵌入到我的 html 中的文本文件没有显示在电子邮件中。其他所有内容都可以,但文本文件不会。我该怎么办?文本文件与我的 python 文件位于同一目录中。

【问题讨论】:

  • 对我来说看起来很正常,您正在发送多部分邮件。默认情况下,邮件“客户端”(Gmail ?)将显示 HTML,如果它能够呈现 HTML,否则将使用文本版本(这将是基本邮件客户端的行为)。因此,您看到的是 HTML 或文本(最坏的情况) - 而不是两者。查看收到邮件的源代码,两个版本都应该在原始源中可见。不过,您可以做的是将文本版本作为 附件 而不是内联发送。

标签: python html mime smtplib


【解决方案1】:

曾经遇到过同样的问题。

我必须附上文件:

# open the file to be sent  
file = "name_of_file_with_extension"
attachment = open("Path to the file", "rb") 

# create mimebase instance
payload = MIMEBase('application', 'octet-stream') 
payload.set_payload((attachment).read()) 
encoders.encode_base64(payload) 
payload.add_header('Content-Disposition', "attachment; filename= %s" % file) 
email.attach(p)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    相关资源
    最近更新 更多