Django: How to send HTML emails with embedded images

前端 未结 5 1766
心在旅途
心在旅途 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:49

    If you want to send email with image as attachment (in my situation it was image that has been caught directly from form, after its saving) you can use the following code as example:

    #forms.py
    
    from django import forms
    from django.core.mail import EmailMessage
    from email.mime.image import MIMEImage
    
    
    class MyForm(forms.Form):
        #...
        def save(self, *args, **kwargs):
            # In next line we save all data from form as usual.
            super(MyForm, self).save(*args, **kwargs)
            #...
            # Your additional post_save login can be here.
            #...
            # In my case name of field was an "image".
            image = self.cleaned_data.get('image', None)
            # Then we create an "EmailMessage" object as usual.
            msg = EmailMessage(
                'Hello',
                'Body goes here',
                'from@example.com',
                ['to1@example.com', 'to2@example.com'],
                ['bcc@example.com'],
                reply_to=['another@example.com'],
                headers={'Message-ID': 'foo'},
            )
            # Then set "html" as default content subtype.
            msg.content_subtype = "html"
            # If there is an image, let's attach it to message.
            if image:
                mime_image = MIMEImage(image.read())
                mime_image.add_header('Content-ID', '')
                msg.attach(mime_image)
            # Then we send message.
            msg.send()
    

提交回复
热议问题