Send_mail function of django basic learning

Preface

We know that the smtplib module in python is used for mail functions, and django encapsulates this module, making it very simple to use.
django.core.mail is the core module of django mail.
Two commonly used 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

# 参数介绍  
# subject: 邮件主题 
# message: 邮件内容 
# from_email: 发件人 
# recipient_list: 收件人,这是一个列表,可以有多个收件人 
# 以上4个在参数 在send_mass_mail中,会写在datatuple这个元组中 
# fail_silently: 是否报错,True的话表忽略异常 
# auth_user&auth_password:账号密码 
# connection: 表示这个的链接对象,后续会提到 
# html_message: send_mail方法独有,可以比较简单地实现一个html文本的传输,具体我也没使用过,不是很了解。

Under normal circumstances, we need to configure in the setting. In addition to the host and port that must be configured, generally we also write the account password here, so that we don’t need to pass these two parameters every time the function is called. When these two values ​​are not passed , They will read the value in the setting by default. The
return value is that multiple messages have been successfully sent, not how many individuals, generally use send_mail, all return 1

# settings.py
# 我使用的是新浪的,host可以在对应邮箱的设置中找到
EMAIL_HOST = 'smtp.sina.com'
EMAIL_PORT = 25
# 你的邮箱账号与密码
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '******'
# 由于使用25端口,一般都不使用TLS机密,SSL和TSL只需要设置一个,他们同时为True或False
EMAIL_USE_TLS = False
# 发件人,只有这个变量名可以自己自定义,设置在这里是为了减少每次去写
EMAIL_FROM = '[email protected]'

Instance

from django.core.mail import send_mail, send_mass_mail
from string import lowercase,uppercase,digits
from random import randint
from project.settings import EMAIL_FROM
def send_code_email(email):
  """
  发送验证码
  """
  # 0-9 a-z A-z
  code = ''
  seeds= lowercase+uppercase+digits
  length = len(seeds)
  # 生成4位验证码
  for i in range(4):
    code += seeds[randint(0, length-1)]
  send_title = '重置密码'
  send_message = '你的验证码是:{0}。'.format(code)
  send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])


def send_hello_email(email1, email2):
  """
  给email1发送 新年好
  给email2发送 Happy New Year
  """
  # message格式(subject, message, from_email, recipient_list)
  message1 = ('新年好', '新年好', 'EMAIL_FROM', [email])
  message2 = ('Happy New Year', 'Happy New Year', EMAIL_FROM, [email2])
  send_status=send_mass_mail((message1, message2), fail_silently=False)

Obviously you can see the difference between the two functions, send_mail can send one message (to multiple people) at a time, and send_mass_mail can send different messages (to multiple people) at a time.
For a deeper understanding, the previous parameter connection is increased. Combined with this parameter, in fact, each time a connection is established, send_mail only sends one message, while send_mass_mail establishes a connection and can send multiple messages. This way, the efficiency is significantly higher.
Advanced functions The
first two functions actually encapsulate the EmailMessage class, making them very simple to use, but their functions are very limited. For example, they cannot be copied (cc) or sent privately (bcc) and cannot be added.
If you want to use the functions just mentioned for attachments , you must directly use the EmailMessage class.
EmailMessage

# 类定义
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
  
# 使用
from django.core.mail import EmailMessage

email = EmailMessage(
  'Hello',
  'Body goes here',
  '[email protected]',
  ['[email protected]', '[email protected]'],
  ['[email protected]'],
  reply_to=['[email protected]'],
  headers={'Message-ID': 'foo'},
)

In this class of parameters, CC, private bcc, and reply_to are all a list.
It is worth mentioning that attachments, which is also a list, whose elements start with: MIMEBase object or (filename, content, mimetype) tuple, which includes the displayed file name, file data, and file type.
It also provides some methods, mainly to mention two: send() to send mail, and attach() to add attachments and
use Backend directly.
If we directly call EmailMessage.send() as above, only one message will be sent once a connection is connected. , Then what if I want to send multiple messages? At
this time, we need to understand 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 a list of EmailMessage objects, and then send multiple messages, and the send() method of EmailMessage calls this method, but the passed parameter is [self], and there is only one object.
So, in fact, if we can control the switch of the connection, then we can realize that multiple EmailMessage objects are sent out in email. At this time, we consider the way to automatically control the opening and closing operations through the context:

from django.core import mail

with 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. We definitely want to be able to use send_messages() to directly pass a list of EmailMessage objects to it. We noticed the above code get_connection() function, in fact, it can directly get a backend object, and then directly call the send_messages() method.

from django.core import mail

connection = mail.get_connection()
# get_EmailMessage_list返回一个EmailMessage对象的列表
messages = get_EmailMessage_list()
connection.send_messages(messages)

This directly calls send_messages(messages). If there is no open link at this time, it will open the connection first, and then close it automatically.
This seems a bit inflexible, so you can control open and close yourself!

from django.core import mail

connection = mail.get_connection()
connection.open()

email1 = mail.EmailMessage(
  'Hello',
  'Body goes here',
  '[email protected]',
  ['[email protected]'],
  connection=connection,
)
email1.send() 

email2 = mail.EmailMessage(
  'Hello',
  'Body goes here',
  '[email protected]',
  ['[email protected]'],
)
email3 = mail.EmailMessage(
  'Hello',
  'Body goes here',
  '[email protected]',
  ['[email protected]'],
)
connection.send_messages([email2, email3])

connection.close()

This example uses the use of EmailMessage.send() and connection.send_messages(). This is just for demonstration purposes, and it is not necessary to use backend type and customization at the same time

Having said so many backends, what exactly is it, in fact, the default is: backends.smtp.EmailBackend

# 在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

It is this class, which inherits BaseEmailBackend, is the default backend, and controls the entire send mail process. Of course, django also provides other backends, but they are not very useful.
Console backend: Write the email directly to your stdout.
Dummy backend: No practical effect.
You only need to specify your backend in the setting:

EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'

Of course, you can also customize the backend. You need to inherit BaseEmailBackend and implement the send_messages(email_messages), open, and close methods, but I don’t think this is necessary. After all, smtp.EmailBackend provides a more complete function.
Afterword

The content of this article is basically from the official django1.11 document. The text is based on the document and your own understanding. There may be misunderstandings. You are welcome to point out.
Reference article:

django1.11 official document email

to sum up

The above is the entire content of this article. I hope that the content of this article has a certain reference value for your study or work. Thank you for your support to Scripthome.

Guess you like

Origin blog.csdn.net/tofu_yi/article/details/115002748