[英]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\\
我鼓勵你使用一個庫,而不是處理 - 而是 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.