For details about send_mail in django, djangosend_mail
Preface
We should all know that the smtplib module in python is used for mail, and django encapsulates this module to make it easy to use. Django. core. mail is the core module of django mail. I will not talk about it much below. Let's take a look at the detailed introduction along with the small series.
Two common functions
It provides two functions, which 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 description # subject: mail subject # message: Mail content # from_email: sender # recipient_list: recipient, this is a list with multiple recipients # the above four are written in the sendupl parameter in send_mass_mail In e, the # fail_silently: whether to report an error. If it is True, the table ignores the exception. # auth_user & auth_password: account password # connection: indicates the link object. # html_message: the send_mail method is unique and can easily implement the transmission of an html text. I have never used it, but I am not very familiar with it.
In general, we need to configure in setting. In addition to the host and port that must be configured, we usually write the account and password here, so that each call to the function does not need to pass these two parameters, if these two values are not passed, they will read the values in setting by default.
The returned value is that multiple messages are successfully sent, rather than the number of people. Generally, if send_mail is used, 1 is returned.
# Settings. py # I am using Sina, host can be found in the settings of the corresponding mailbox EMAIL_HOST = 'smtp .sina.com 'EMAIL _ PORT = 25 # Your mailbox account and password EMAIL_HOST_USER = 'viptestfordjango @ sina.com' EMAIL _ HOST_PASSWORD = '* * ***** '# Because port 25 is used, generally, no TLS secret is used. SSL and TSL only need to be set. They are both True or FalseEMAIL_USE_TLS = False # sender. Only the variable name can be customized, it is set here to reduce the number of times to write EMAIL_FROM = 'viptestfordjango @ sina.com'
Instance
From django. core. mail import send_mail, send_mass_mailfrom string import lowercase, uppercase, digitsfrom random import randintfrom project. settings import EMAIL_FROMdef send_code_email (email ): "Send verification code" #0-9 a-z A-z code = ''seeds = lowercase + uppercase + digits length = len (seeds) # generate a four-digit verification code 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 New Year to email1 send Happy New Year to email2" "# message format (subject, message, from_email, recipient_list) message1 = ('new year', '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 is obvious that the two functions are different. send_mail sends a message to multiple users at a time, while send_mass_mail can send different messages to multiple users at a time ).
For a deeper understanding, the previous step is to increase the connection parameter. In combination with this parameter, send_mail only sends one message for each connection established, while send_mass_mail creates one connection and can send multiple messages, in this way, the efficiency is much higher.
Advanced functions
The first two functions are actually encapsulated for the EmailMessage class, which is quite simple to use, but their functions are very limited. For example, they cannot be copied (cc) alternatively, bcc and attachments cannot be added)
If you use the function just mentioned, you must use the EmailMessage class directly.
EmailMessage
# Class definition 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 django. core. mail import EmailMessageemail = 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 '},)
In this parameter, cc is copied, bcc is sent, and reply_to is returned.
It is worth mentioning that attachments is also a list. Its elements start with the MIMEBase object or (filename, content, mimetype), which includes the displayed file name and file data, file type.
It also provides two methods:send()Send emails and attach () add attachments
Use Backend directly
If we callEmailMessage.send()In this way, only one message will be sent for one connection. What if I want to send multiple messages?
At this time, we need to know about backend.
In fact, the django sending_email function is controlled by backend. This class provides several methods:
open() : Open a connection
close(): Close this connection
send_messages(email_messages): Accept the list of an EmailMessage object and send multiple messages.send()The method is to call this method, but the passed parameter is [self], and there is only one object.
In fact, if we can control the connection switch, we can implement multiple EmailMessage objects to be sent by email. At this time, we consider using context-based Automatic Control to enable and disable operations:
from django.core import mailwith mail.get_connection() as connection: mail.EmailMessage( subject1, body1, from1, [to1], connection=connection, ).send() mail.EmailMessage( subject2, body2, from2, [to2], connection=connection, ).send()
This method is a bit clumsy and we certainly hope to use it.send_messages()Directly pass the list of an EmailMessage object to it. We noticed the above Codeget_connection()Function, in fact, it can directly obtain a backend object, and then directly call thissend_messages()Method.
From django. core import mailconnection = mail. get_connection () # get_EmailMessage_list returns a list of EmailMessage objects. messages = get_EmailMessage_list () connection. send_messages (messages)
This direct callsend_messages(messages)If there is no open link at this time, it will first open the connection and automatically close the link after it is disabled.
This seems to be a little inflexible. You can also control open and close in person!
from django.core import mailconnection = mail.get_connection()connection.open()email1 = mail.EmailMessage( 'Hello', 'Body goes here', 'from@example.com', ['to1@example.com'], connection=connection,)email1.send()email2 = mail.EmailMessage( 'Hello', 'Body goes here', 'from@example.com', ['to2@example.com'],)email3 = mail.EmailMessage( 'Hello', 'Body goes here', 'from@example.com', ['to3@example.com'],)connection.send_messages([email2, email3])connection.close()
This example usesEmailMessage.send()Andconnection.send_messages()This is only a demonstration function, and does not need to be used at the same time
Backend type and customization
After talking about so many backends, what is it? In fact, the default value is:backends.smtp.EmailBackend
# In django. core. mail. Backends. smtp. 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
This class inherits the BaseEmailBackend, which is the default backend and controls the entire send mail process. Of course, django also provides other backend services, but it does not play a major role.
Console backend: Write the email directly to your stdout.
Dummy backend: it does not work.
You only need to specify your backend in setting:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
You can also customize backend. You need to inherit BaseEmailBackend and implement send_messages.(email_messages),open,closeMethod, but I don't think this is necessary. After allsmtp.EmailBackendProvides comprehensive functions.
Postscript
The content of this article is basically from the official django1.11 document. The text is based on the document and your own understanding, and may be incorrect.
Well, the above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.
References:
Django1.11 official document email