The mail system of Django framework involves sending HTML, rich text and attachment mail

Keywords: Python Django Back-end

preface

Over the past few years, I have been struggling in the it industry. Along the way, many have summarized some high-frequency interviews in the python industry. I see most of the new blood in the industry, and I still have all kinds of difficult questions for the answers to all kinds of interview questions or collection

Therefore, I developed an interview dictionary myself, hoping to help everyone, and also hope that more Python newcomers can really join the industry, so that Python fire does not just stay in advertising.

Wechat applet search: Python interview dictionary

Or follow the original personal blog: https://lienze.tech

You can also focus on WeChat official account and send all kinds of interesting technical articles at random: Python programming learning.

Mail system

django has many built-in methods to make it easy for developers to send mail

Mail configuration

To send mail, you first need to configure the mail server connection and other information under the settings.py file of the project

EMAIL_USE_SSL = True # The Secure Sockets Layer is a secure socket layer, which depends on whether the mail server turns on the encryption protocol
EMAIL_HOST = 'smtp.qq.com'  # Mail server address
EMAIL_PORT = 465 # Mail server port 
EMAIL_HOST_USER = 'account@qq.com' # Account of login mail server
EMAIL_HOST_PASSWORD = 'password'  # Password to log in to the mail server
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER # Sender of the message
  • Note: email_ HOST_ The password set by password to log in to the mail server is the login password of the third-party client set in the background of the mail client. This value is not the direct account password

For example, the value password of QQ mailbox is set in the web version QQ mail client - > account - > Open POP3/SMTP service | IMAP/SMTP service

Send text mail

Send under the django.core.mail module can be used to send ordinary mail_ Mail function

send_mail(subject, message, from_email, recipient_list, fail_silently=False, html_message=None)
# Send mail to ` recipient_ At each recipient in the list `
'''
subject: Send message header
message: Send message body
from_email: Sender email address
recipient_list: A string list, each data is the email address of the recipient
html_message: If this value is specified, the content type sent is text/html For one html Mail content
''
  • Send normal mail view function
from django.core.mail import send_mail
def send_email(request):
    subject = 'Mail test'
    message = '<a href="http://Www.python. Org "> I'm happy to learn Python < / a > '
    send_mail(
        subject = subject,
        message = message,
        from_email = 'from@qq.com',
        recipient_list = ['recv@qq.com','recv1@qq.com']
    )
    return HttpResponse('Down')

Send HTML mail

The content of the message sent here is an HTML a tag, but when the real recipient receives the message, the a tag will not be interpreted as a real a tag, but a common string. This is because the type of the message currently sent is text/plain. You can use the html_message parameter to send HTML content

from django.core.mail import send_mail
def send_email(request):    
    subject = 'Mail test'
    message = '<a href="http://Www.python. Org "> I'm happy to learn Python < / a > '
    send_mail(
        subject = subject,
        message = '', # This parameter is required and must be filled in
        html_message = message,
        from_email = 'from@qq.com',
        recipient_list =['recv@qq.com','recv1@qq.com']
    )
    return HttpResponse('Down')

To send html format mail, you can also use the EmailMultiAlternatives class under the django.core.mail module to construct the mail body, and then send the mail

EmailMultiAlternatives(subject='', body='', from_email=None, to=None)
'''
subject: Mail title
body: Mail content
from_email: Email Sender 
to: Mail recipient list
'''
EmailMultiAlternatives.attach_alternative(content, mimetype)
# Add mail content supported by mimetype to the EmailMultiAlternatives instance
'''
content: Added message content
mimetype: Add content mime type
''
EmailMultiAlternatives.send()
# Send mail
  • A demo
from django.core.mail import EmailMultiAlternatives
def send_email(request):
    subject = 'Mail test'
    text_message = 'study Python,I am so happy'
    html_message = '<a href="http://Www.python. Org "> I'm happy to learn Python < / a > '
    email = EmailMultiAlternatives(
        subject = subject,
        body = text_message,
        from_email = '1747266529@qq.com',
        to = ['recv@qq.com','recv1@qq.com']
    )
    email.attach_alternative(html_message,'text/html') # Add HTML message section
    email.send() # Send mail
    return HttpResponse('Down')

Send rich text mail

We often need to add static resources such as pictures to our emails

You need to use the MIMEImage class under the email.mime.image module in python to construct the image content

Here, the EmailMessage class is used to send the mail, which comes from the django.core.mail module; then the attach of the corresponding class instance is used to add the image resource data, and finally the send function of the instance is used to send the mail

EmailMessage(subject='', body='', from_email=None, to=None)
'''
subject: Mail title
body: Mail content
from_email: Email Sender 
to: Mail recipient list
'''
  • Another demo
from sendmailpro.settings import STATICFILES_DIRS
import os
from email.mime.image import MIMEImage
from django.core.mail import EmailMessage
def send_email(request):
    subject = 'Picture mail test'
    file_1 = os.path.join(STATICFILES_DIRS[0],'img/1.png')
    with open(file_1, 'rb') as fp: 
        # Open first picture
        image_1 = MIMEImage(fp.read())
        
    file_2 = os.path.join(STATICFILES_DIRS[0],'img/2.png')
    with open(file_2, 'rb') as fp: 
        # Open second picture
        image_2 = MIMEImage(fp.read())
        
    body = "<img src='cid:first_id'><br><img src='cid:sec_id'>"
    # Send mail body content
    
	image_1.add_header('Content-ID','<%s>' % 'first_id') 
    # The position of the picture in the mail content is symmetrical by CID
    image_2.add_header('Content-ID','<%s>' % 'sec_id')
    
    message = EmailMessage( # Build sent mail body
                subject=subject,
                body=body,
                from_email='from@qq.com',
                to=['recv@qq.com','recv1@qq.com']
            )
    message.content_subtype = 'html'
    message.attach(image_1) # Add two pictures
    message.attach(image_2)
    message.send() # Send mail
    return HttpResponse('Down')

Send attachment mail

To send an attachment, you can use the EmailMessage class under the django.core.mail module to construct the attachment mail body

The attachment content is added to the mail body through the attach|attach_file functions of the EmailMessage instance

attach_file adding mail attachments can be directly added to the path, but attachment content needs to be provided to add attachment content

attach(filename=None, content=None, mimetype=None)
# Add attachment content
'''
filename: Attachment file name
content: Annex contents
mimetype: Accessory`MIME`type
'''
attach_file(path, mimetype=None)
# Add attachments directly through the path
'''
path: Attachment path
mimetype: Accessory MIME type
'''
  • A demo
from sendmailpro.settings import STATICFILES_DIRS
import os
from email.mime.image import MIMEImage
from django.core.mail import EmailMessage
def send_email(request):
    subject = 'Attachment mail test'
    email = EmailMessage(
        subject=subject,
        body='This is an email with a picture attachment',
        from_email='from@qq.com',
        to=['recv@qq.com','recv1@qq.com']
    )
    file_1 = os.path.join(STATICFILES_DIRS[0],'img/1.png')
    image_1 = open(file_1,'rb').read()
    email.attach('1.png',image_1,'image/png') # Use the attach instance function to add attachment content

    file_2 = os.path.join(STATICFILES_DIRS[0],'img/2.png')
    email.attach_file(file_2,mimetype='image/png') # Use the attach_file instance function to add an attachment path

    email.send()
    return HttpResponse('Down')

Posted by sameveritt on Thu, 18 Nov 2021 02:34:09 -0800