Python:将html文件附加到电子邮件

时间:2015-11-17 21:29:53

标签: python html email smtp

我有一个脚本可以发送带有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 \

这是我用以下代码收到的输出: enter image description here

这是html doc在电子邮件脚本之外的方式(它应该看起来的方式): enter image description here

1 个答案:

答案 0 :(得分:0)

我鼓励您使用图书馆,而不是处理内置的unpythonic内置邮件模块,例如强烈推荐的信封:

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

安装:

pip install envelopes

Python代码:

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)