python-3.x - 带有图像的Python 3 EmailMessage html消息

标签 python-3.x smtp html-email

我正在尝试将图像显示为用Python发送的邮件的一部分。 Python文档上有一个不起作用的示例。

from datetime import datetime
import sys

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid



from email.mime.image import MIMEImage

attachment = '/user/file/test.png'


import email.policy
msg = EmailMessage()
msg['To'] = Address("Srujan", 'myemail@example.com')
msg['From'] = Address("Srujan", 'myemail@example.com')
msg['Subject'] = "Nice message goes with it "+str(datetime.now())
id = make_msgid()
msg.set_type('text/html')
msg.set_content(" This is the Data Message that we want to send")
html_msg = "<br> <b><u> This is the Text .... </u></b><br> <img src='cid:{image_id}' />".format(image_id=id[1:-1])
msg.add_alternative(html_msg, subtype="html")
image_data = open(attachment, "rb")
image_mime = MIMEImage(image_data.read())
image_data.close()
msg.add_attachment(image_mime,   cid=id, filename = "myown.png" ,)


try:
    with smtplib.SMTP('example.com') as s:
        s.ehlo()
        s.starttls()
        s.ehlo()
        
        s.send_message(msg)
        s.close()
    print("Email sent!")
except:
    print("Unable to send the email. Error: ", sys.exc_info()[0])
    raise
我注意到最后一部分是message/rfc822,然后包含image/png
To: Srujan <"myemail@example.com"> From: Srujan
<"myemail@example.com"> Subject: Nice message goes with it 2016-01-21
17:39:23.642762 MIME-Version: 1.0 Content-Type: multipart/mixed;
boundary="===============3463325241650937591=="

--===============3463325241650937591==
Content-Type: multipart/alternative; boundary="===============0739224896516732414=="

--===============0739224896516732414==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

 This is the Data Message that we want to send

--===============0739224896516732414==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit MIME-Version: 1.0

<br> <b><u> This is the Text .... </u></b><br> <img
src='cid:20160122013923.64205.76661' />

--===============0739224896516732414==--

--===============3463325241650937591==
Content-Type: message/rfc822
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="myown.png"
Content-ID: <20160122013923.64205.76661>
MIME-Version: 1.0

Content-Type: image/png
MIME-Version: 1.0
Content-Transfer-Encoding: base64

iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAIAAAAVFBUnAAAABmJLR0QA/wD/AP+gvaeTAAAgAElE
QVR4nOzdd2BUVfYH8HNfmZJAChAEQ1FAqoKgCAsWLEgTG4gKP11FQNG1AauIgGBXVhRUsCK4i6gI

现在,附件消息具有两个内容类型值。电子邮件仅包含文本,没有图像。
我已经使用MultiPart类成功完成了此任务,但希望通过EmailMessage实现。

最佳答案

遗憾的是,关于此主题的Python文档不完整/错误。我想做同样的事情,遇到同样的问题(附件有两种内容类型)

通过使用attach()方法而不是add_attachment()对象上的EmailMessage解决了该问题。唯一的警告是,您必须先将EmailMessage转换为multipart/mixed类型。一个例子:

from smtplib import SMTP
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.headerregistry import Address
from ssl import SSLContext, PROTOCOL_TLSv1_2

# Creating and populating email data:
msg = EmailMessage()
msg['From'] = Address(display_name='Recipient', addr_spec='rcpt@example.org')
msg['To'] = Address(display_name='Sender', addr_spec='sender@example.org')
msg['Subject'] = 'An email for you'    
msg.set_content('This should be in the email body')  
# It is possible to use msg.add_alternative() to add HTML content too  

# Attaching content:
att = MIMEText('This should be in an attached file') # Or use MIMEImage, etc
# The following line is to control the filename of the attached file
att.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
msg.make_mixed() # This converts the message to multipart/mixed
msg.attach(att) # Don't forget to convert the message to multipart first!

# Sending the email:
with SMTP(host='smtp.example.org', port=587) as smtp_server:
    try:
        # You can choose SSL/TLS encryption protocol to use as shown
        # or just call starttls() without parameters
        smtp_server.starttls(context=SSLContext(PROTOCOL_TLSv1_2))
        smtp_server.login(user='user@smtp.example.org', password='password')
        smtp_server.send_message(msg)

    except Exception as e:                
        print('Error sending email. Details: {} - {}'.format(e.__class__, e))

关于python-3.x - 带有图像的Python 3 EmailMessage html消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34937694/

相关文章:

python - 如何在 python Bokeh 中对按钮单击执行 onclick 操作?

python-3.x - 找不到 Jinja 嵌套模板

asp.net - 通过 google 应用程序使用 smtp 中继发送邮件

html - 任何字体都可以用作网络字体吗(特别是用于 HTML 电子邮件)

outlook - HTML 电子邮件 - Outlook.com 无法识别我的图像垂直对齐控件

python-3.x - 将文件拆分为 block

python - 如何将元组列表的字符串转换为 Python 元组列表

ssl - UIPath : The Remote Certificate is invalid according to validation procedure

linux - 可以通过 RS-232 直接发送电子邮件 (SMTP)

html - 电子邮件模板 - 背景图像与文本叠加在确切位置