如何使用Python在电子邮件正文中发送图像。我用Google搜索,但能够找到附件方法。如何将其内联发送?
这是我的代码: -
from django.core.mail import EmailMessage
subject = 'Report for ' + filename
content = 'Hello All \nPFA ' + filename + '. \n\n\nThis is an auto generated mail. Please do not reply to this email. '
receipients =['x','y']
sender = ''
message = EmailMessage(subject,content,sender,bcc = receipients)
message.attach_file(filepath)
message.send()
答案 0 :(得分:1)
我认为你不能通过直接设置文本内容来做到这一点。最简单的方法可能是使用django模板渲染系统发送带有html的邮件。这样,您可以按照您想要的方式直接包含图像(例如<img src="...">
)
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
mail = EmailMultiAlternatives(
subject,
render_to_string('template.txt',
sender,
recipients
)
mail.attach_alternative(render_to_string('template.html', {'image_src': '...'}), 'text/html'))
mail.send()
请注意,在收件人邮件系统无法读取html(几乎从未发生过)的情况下,也包括纯文本邮件(没有图像)是一种良好的做法。更明确一点,template.html
和template.txt
与您要发送的内容相同,但有或没有任何HTML。例如
template.txt
Hello All \nPFA \n\n\nThis is an auto generated mail. Please do not reply to this email.
template.html
<p> Hello All </p>PFA </br> <img src=" {{ image_src }} "> ...
答案 1 :(得分:0)
我会使用base64
并在电子邮件正文中嵌入数据,例如:
<img width="16" height="16" alt="star" src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" />