Django: How to send HTML emails with embedded images

前端 未结 5 1749
心在旅途
心在旅途 2020-12-03 03:18

How can I send HTML emails with embedded images? How the HTML should link to the images? The images should be added as MultiPart email attach?

Any example is very ap

5条回答
  •  情深已故
    2020-12-03 03:37

    I have tried the below code and it worked.

    Code:

    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("""\
        
       
          
    Hi {name},

    Welcome!
    """.format(image_cid=image_cid[1:-1],name='ABC'), subtype='html') # image_cid looks like # 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=, port=25) server.starttls() # send the message via the server. server.sendmail(msg['From'], recipients, msg.as_string()) server.quit()

提交回复
热议问题