【问题标题】:Embed an image in Email content - Django在电子邮件内容中嵌入图像 - Django
【发布时间】:2019-12-18 16:24:51
【问题描述】:

我正在使用 Django 的电子邮件消息模块来触发带有嵌入图像的电子邮件。目前我的静态文件夹中有该图像。我尝试直接在 python 中使用 html 代码来触发电子邮件。但是图像没有嵌入到触发的电子邮件中。我尝试通过将图像源属性指定为静态路径和 url。有人可以帮忙吗?下面是我使用的代码。

代码:

recipient_list = ['a...@gmail.com']
from_email = 'a...@gmail.com'
message = ''
path = "{% static 'images/Welcome_image.jpg' %}" //Using this image in the below html also tried specifying the source as an url that points to the url path. Like https://abc/images/Welcome_imagr.jpg
message += "<table border='1' cellpadding='1' cellspacing='0' width='800'>\
            <tbody>\
                <tr>\
                    <td height='506'>\
                    <table border='0' cellpadding='0' cellspacing='0' width='600'>\
                        <tbody>\
                            <tr>\
                                <td valign='top'>\
                                    <img height='190' src=%s width='800'  tabindex='0'>\    //Using this image here but it is not rendered properly.
                                </td>\
                            </tr>\
                            <tr>\
                                <td height='306' valign='top'>\
                                    <table cellpadding='0' cellspacing='20' width='800'>\
                                        <tbody>\
                                            <tr>\
                                                <td align='left' height='804' style='font-family:arial,helvetica,sans-serif;font-size:13px' valign='top'>Hi User,<br><br>\
                                                    Welcome to the world.\
                                                </td>\
                                            </tr>\
                                        </tbody>\
                                    </table>\
                                </td>\
                            </tr>\
                        </tbody>\
                    </table>\
                    </td>\
                </tr>\
            </tbody>\
            </table>"%(path)

subject = "Welcome to the place!"
try:
    msg = EmailMessage(subject, message, from_email, recipient_list)
    msg.content_subtype = "html"  # Main content is now text/html
    if any(recipient_list):
        msg.send()
except Exception:
    print("Exception while sending mail")

【问题讨论】:

  • 您可以查看docs
  • 使用三重 " - """text in many lines""" 并且你不需要在每一行的末尾都使用 \
  • 您可以随时读取图像并转换为base64字符串并直接嵌入&lt;img src="data:image/jpeg;base64, ..."&gt;
  • 您应该附上一张图片并在电子邮件中引用它。 message.attach('design.png', img_data, 'image/png')。 .attach() 是发送电子邮件包的一部分docs.djangoproject.com/en/3.0/topics/email

标签: python html django django-templates django-email


【解决方案1】:

我已经尝试了以下代码并且它有效:

Python:

定义发送():

msg = EmailMessage()

# generic email headers
msg['Subject'] = 'Welcome'
msg['From'] = 'abc@gmail.com'
recipients = ['abc@gmail.com']

# set the plain text body
msg.set_content('This is a plain text body.')

# now create a Content-ID for the image
image_cid = make_msgid(domain='')
# if `domain` argument isn't provided, it will
# use your computer's name

# set an alternative html body
msg.add_alternative("""\
    <html>
   <body>
      <table border='0' cellpadding='1' cellspacing='0' width='800'>
         <tbody>
            <tr>
               <td height='506'>
                  <table border='0' cellpadding='0' cellspacing='0' width='600'>
                     <tbody>
                        <tr>
                           <td valign='top'>
                              <img height='190' src="cid:{image_cid}" width='800'  tabindex='0'>
                           </td>
                        </tr>
                        <tr>
                           <td height='306' valign='top'>
                              <table cellpadding='0' cellspacing='20' width='800'>
                                 <tbody>
                                    <tr>
                                       <td align='left' height='804' style='font-family:arial,helvetica,sans-serif;font-size:13px' valign='top'>
                                          Hi {name},<br><br>
                                          Welcome!
                                       </td>
                                    </tr>
                                 </tbody>
                              </table>
                           </td>
                        </tr>
                     </tbody>
                  </table>
               </td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
""".format(image_cid=image_cid[1:-1],name='ABC'), subtype='html')
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off

# now open the image and attach it to the email
with open('/path/image.jpg', 'rb') as img:
    # know the Content-Type of the image
    maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')

    # attach it
    msg.get_payload()[1].add_related(img.read(),
                                     maintype=maintype,
                                     subtype=subtype,
                                     cid=image_cid)
server = smtplib.SMTP(host=<hostname>, port=25)

server.starttls()
# send the message via the server.
server.sendmail(msg['From'], recipients, msg.as_string())

server.quit()

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 2015-01-29
    • 2014-10-03
    • 2015-03-14
    • 2016-02-22
    • 2011-10-30
    • 2013-08-23
    相关资源
    最近更新 更多