繁体   English   中英

Python:将 html 文件附加到电子邮件的正确 MIME 类型是什么

[英]Python: What is the correct MIME type for attaching html file to email

我有一个脚本,可以发送包含 html 内容的电子邮件。按预期工作...我在发送电子邮件附件时遇到问题。

附件是存储在脚本活动目录中的 html 文件...“test.html”

如何将 html 文件附加到电子邮件中? 我已经尝试了我发现的与此相关的其他各种帖子的片段,但每个片段都返回了“没有这样的文件或目录”的相同输出。

代码如下:

import smtplib
import os
import email.encoders
import email.mime.text
import email.mime.base
import mimetools
import base64



from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

    # me == Outgoing email address
    # you == Recipient's email address
me = "secret"
you = "secret"

    # Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "TEST"
msg['From'] = me
msg['To'] = you
emailMsg = email.MIMEMultipart.MIMEMultipart('alternative')

    # Create the body of the message (a plain-text and an HTML version).
html = """\
    <html>
    <head></head>
    <body>test</p>
</body>
</html>"""


    # Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
filename = "C:/CHRIS/ServerStatus/Oceaneering_Server_Status.html"
f = file(filename)
attachment = MIMEText(f.read(), _subtype='html')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
msg.attach(attachment)

    # Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

    # mail.login(username, password) to Outgoing email account
mail.login('secret', 'secret')
mail.sendmail(me, you, msg.as_string())
mail.quit()

我已经更新了我的代码,希望让这个问题回到主题......我在 Dirk 和这个链接的帮助下取得了一些进展: Attach a txt file in Python smtplib ...

我现在已经能够物理发送附件,但是附件仍然是作为一种文本类型的文件发送的,并且不会像原始 html 文件那样打开。

所以改写我的问题......更改此代码的 MIME 类型以将 .html 文件正确附加到基于 html 的电子邮件的纠正措施是什么?

我的py脚本和需要发送的html文件的相对路径和目录如下:C:\\CHRIS\\ServerStatus\\

这是我收到的带有代码的输出: 在此处输入图片说明

这是 html 文档在电子邮件脚本之外的样子(它应该看起来的样子): 在此处输入图片说明

我鼓励你使用一个库,而不是处理 - 而是 unpythonic- 内置邮件模块,例如强烈推荐的信封:

https://tomekwojcik.github.io/envelopes/index.html

安装:

pip install envelopes

蟒蛇代码:

import os
from envelopes import Envelope

filename = "C:/CHRIS/ServerStatus/Oceaneering_Server_Status.html"

envelope = Envelope(
    from_addr=(me),
    to_addr=(you),
    subject=u'Test',
    text_body=u'Plain text version',
    html_body=html
)
envelope.add_attachment(filename)

envelope.send('smtp.gmail.com', login='secret', password='secret', tls=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM