使用 Python 傳送 HTML 電子郵件
如果您使用 Python 傳送文字訊息,則所有內容都將被視為簡單文字。即使您在文字訊息中包含 HTML 標記,它也會顯示為簡單文字,並且 HTML 標記不會根據 HTML 語法進行格式化。但 Python 提供了將 HTML 訊息作為實際 HTML 訊息傳送的選項。
在傳送電子郵件訊息時,您可以指定 Mime 版本、內容型別和字元集來發送 HTML 電子郵件。
示例
以下是將 HTML 內容作為電子郵件傳送的示例。試用一次 −
#!/usr/bin/python import smtplib message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email"
廣告