SoFunction
Updated on 2024-10-29

django send_mail function implementation details

preamble

Two common functions

It provides two functions that are very simple to use:

def send_mail(subject, message, from_email, recipient_list,
  fail_silently=False, auth_user=None, auth_password=None,
  connection=None, html_message=None):
 pass    
def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
   auth_password=None, connection=None):
 pass
# Parameter introduction
# subject: Subject of the message
# message: content of the message
# from_email: From
# recipient_list: recipients, this is a list, can have more than one recipient
# The above four parameters in send_mass_mail are written in the tuple datatuple
# fail_silently: whether to report errors, True then the table ignores exceptions.
# auth_user&auth_password:account password
# connection: the link object that represents this, which will be mentioned later.
# html_message: send_mailMethods are unique,It can be relatively simple to implement ahtmlTransmission of text,I haven't used it exactly.,Not really.。

In general, we need to configure in the setting, in addition to the host and port must be configured, generally we will also write the account password here, so that each time you call the function does not have to pass these two parameters, when not passing these two values, they will default to read the value of the setting

The return value is the number of messages successfully sent, not the number of individuals, generally use send_mail, are returned 1

# 
# I'm using Sina, host can be found in the settings of the corresponding mailboxes
EMAIL_HOST = ''
EMAIL_PORT = 25
# Your e-mail account and password
EMAIL_HOST_USER = 'viptestfordjango@'
EMAIL_HOST_PASSWORD = '******'
# Since port 25 is used, TLS secrets are generally not used, SSL and TSL only need to be set one, they are both True or False at the same time
EMAIL_USE_TLS = False
# Sender, only this variable name can be customized, set here to reduce the number of times you have to write the
EMAIL_FROM = 'viptestfordjango@'

an actual example

from  import send_mail, send_mass_mail
from string import lowercase,uppercase,digits
from random import randint
from  import EMAIL_FROM
def send_code_email(email):
 """
 Send CAPTCHA
 """
 # 0-9 a-z A-z
 code = ''
 seeds= lowercase+uppercase+digits
 length = len(seeds)
 # Generate 4-digit CAPTCHA
 for i in range(4):
  code += seeds[randint(0, length-1)]
 send_title = 'Reset Password'
 send_message = 'Your verification code is:{0}。'.format(code)
 send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
def send_hello_email(email1, email2):
 """
 Send a Happy New Year to email1
 Send email2 Happy New Year
 """
 # messagespecification(subject, message, from_email, recipient_list)
 message1 = ('Good New Year', 'Good New Year', 'EMAIL_FROM', [email])
 message2 = ('Happy New Year', 'Happy New Year', EMAIL_FROM, [email2])
 send_status=send_mass_mail((message1, message2), fail_silently=False)

It's clear to see the difference between the 2 functions, send_mail sends one message (to multiple people) at a time, while send_mass_mail can send different messages (to multiple people) at a time.

Deeper understanding, the front to improve a parameter connection, combined with this parameter, in fact, each establish a connection, send_mail only send a kind of message, and send_mass_mail to establish a connection, you can send more than one message, this way, the efficiency is obviously much higher.

Advanced Features

The first two functions are in fact the EmailMessage class to encapsulate, so that they use, quite simple, but their functions are very limited, for example, can not be copied (cc) or sent privately (bcc) as well as can not be added to the attachments (attachments)

If you want to use the functionality just described, you have to use the EmailMessage class directly.

EmailMessage

# Class Definitions
class EmailMessage(object):
 def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
     connection=None, attachments=None, headers=None, cc=None,
     reply_to=None):
 pass
# Use
from  import EmailMessage
email = EmailMessage(
 'Hello',
 'Body goes here',
 'from@',
 ['to1@', 'to2@'],
 ['bcc@'],
 reply_to=['another@'],
 headers={'Message-ID': 'foo'},
)

This class parameters cc,private send bcc,reply reply_to are all a list.

It is worth mentioning attachments, which is also a list whose elements begin with: the MIMEBase object or the tuple (filename, content, mimetype), i.e., including the displayed filename, file data, and file type.

It also provides some methods, mentioning 2 main ones:send()Sending emails, and attach() adding attachments

Use Backend directly

If we go straight to calling the() This way, only one message will be sent per connection, so what if I want to send more than one message?

At this point it is necessary to understand the backend

In fact, the django sending_email function is controlled by the backend's, this class provides several methods:

open() : Open a connection

close() : Close this connection

send_messages(email_messages) : Accepts a list of EmailMessage objects and then sends multiple messages out, while EmailMessage'ssend()method is to call this method, except that the argument passed is [self],which is just one object.

Then, in fact, if we can control the connection of the switch, then we can realize multiple EmailMessage object in email send out, this time, we consider the context through the automatic control of the opening and closing operation way:.

from  import mail
with mail.get_connection() as connection:
 (
  subject1, body1, from1, [to1],
  connection=connection,
 ).send()
 (
  subject2, body2, from2, [to2],
  connection=connection,
 ).send()

This seems a bit clunky, and we'd definitely like to be able to use thesend_messages() , passing it a list of EmailMessage objects directly. We notice that the code aboveget_connection()function, in fact, it is able to go directly to get a backend object, and then by directly calling thissend_messages()Methods.

from  import mail
connection = mail.get_connection()
# get_EmailMessage_list returns a list of EmailMessage objects
messages = get_EmailMessage_list()
connection.send_messages(messages)

This is a direct call tosend_messages(messages) If there is no OPEN link at this point, it will open the connection first and execute OFF to close it automatically.

This seems a bit inflexible, so you can also control open and close yourself!

from  import mail
connection = mail.get_connection()
()
email1 = (
 'Hello',
 'Body goes here',
 'from@',
 ['to1@'],
 connection=connection,
)
()
email2 = (
 'Hello',
 'Body goes here',
 'from@',
 ['to2@'],
)
email3 = (
 'Hello',
 'Body goes here',
 'from@',
 ['to3@'],
)
connection.send_messages([email2, email3])
()

This example uses the()together withconnection.send_messages()This is just for demonstration purposes, and it is not necessary to also use the

Backend types and customization

After all that talk about backend, what it really is, it actually is by default:

# In... Under.
class EmailBackend(BaseEmailBackend):
 def __init__(self, host=None, port=None, username=None, password=None,
     use_tls=None, fail_silently=False, use_ssl=None, timeout=None,
     ssl_keyfile=None, ssl_certfile=None,**kwargs):
  pass

is this class, it inherits BaseEmailBackend, is the default backend, control the entire send mail process, of course, django also provides other backend, but the role is not very big.

Console backend: Writes mail directly to your stdout.

Dummy backend: has no real effect.

All you need to do is specify your backend in the setting.

EMAIL_BACKEND = ''

Of course, you can also customize the backend, you need to inherit BaseEmailBackend, and implement send_messages(email_messages),open,closemethod, but I don't feel that it's necessary, after allProvides a more complete function now.

words afterword

The content of this article is basically from the django1.11 official documents, the text part is based on the documents and their own understanding, there may be understanding errors, you are welcome to point out.

Well, the above is the full content of this article, I hope that the content of this article on your learning or work has a certain reference learning value, if there are questions you can leave a message to exchange, thank you for my support.

Reference Article:

   django1.11 official documentation email