Detailed explanation of django mail sending module smtp

  • 2021-07-24 11:21:29
  • OfStack

Preface

An smtp mail sending module has been built into Python, and Django has been simply encapsulated on this basis, so that we can send mail more conveniently and flexibly in Django environment.

All functions are in django. core. mail.

Step 1 Get started quickly

You can handle an email in two lines:


from django.core.mail import send_mail

send_mail(
  'Subject here',
  'Here is the message.',
  'from@example.com',
  ['to@example.com'],
  fail_silently=False,
)

Import function module, then send mail, so easy!

By default, the SMTP server host and port are set using EMAIL_HOST and EMAIL_PORT in the configuration file, and EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are user names and passwords. If EMAIL_USE_TLS and EMAIL_USE_SSL are set, they control whether the corresponding encrypted links are used.

2. Single send_mail ()

Method prototype: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)[source]

Let's look at the send_mail () method under 1, which accepts 1 series of parameters, of which subject, message, from_email, and recipient_list parameters are required, and others are optional.

subject: Message subject. String. message: E-mail content. String. from_email: Message sender. String. recipient_list: Recipient. 1 A string list of mailbox addresses. Every 1 member in recipient_list sees the other members in the "To:" area of the mail message. fail_silently: 1 Boolean value. If it is False, an smtplib. SMTPException exception will be thrown when send_mail fails to send. auth_user: The optional username is used to authenticate the SMTP server. Specify this parameter if you want to specify which email account to use. If this value is not provided, Django will use the value of EMAIL_HOST_USER in settings. If you don't provide either, what else do you send? ? ? auth_password: Optional password used to authenticate the SMTP server. If this value is not provided, Django will use the value of EMAIL_HOST_PASSWORD in settings. And the above parameter is one. connection: Optional e-mail backend for sending mail. html_message: If html_message is provided, you can send a message with an HTML code.

The return value of the send_mail () method will be the number of messages successfully sent out (it will only be 0 or 1 because it can only send 1 message).

3. Mass send_mass_mail ()

Method prototype: send_mass_mail(datatuple,fail_silently = False,auth_user = None,auth_password = None ,connection = None)[source]

send_mass_mail () is used to handle mass mail tasks, known as mass mailing.

Among its parameters, datatuple is a required parameter, which accepts 1 tuple, and each element of the tuple has the following format:

(subject, message, from_email, recipient_list)
The above four fields have the same meaning as in send_mail ().

For example, the following code will send two different messages to two different groups of recipients; However, only one connection to the mail server can be opened:


message1 = ('Subject here', 'Here is the message', 'from@example.com', ['first@example.com', 'other@example.com'])

message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])

send_mass_mail((message1, message2), fail_silently=False)

The return value of the send_mass_mail () method is the number of messages successfully sent.

When the send_mail () method is used, it will establish a connection with the SMTP server once every time it is called, that is, it will be sent once and connected once, which is very inefficient. While send_mass_mail (), only one link is established, and all mails are sent out, which is more efficient.

4. Prevent head injection attacks

Sometimes, we have to construct e-mail according to the input of the user's form, which has the risk of header injection attack. Django provides us with a certain prevention ability, but more often, you need to write your own security prevention code.

Here is an example that receives the subject, message content and sender entered by the user and sends the message to the system administrator:


from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect

def send_email(request):
  subject = request.POST.get('subject', '')
  message = request.POST.get('message', '')
  from_email = request.POST.get('from_email', '')
  if subject and message and from_email:
    try:
      send_mail(subject, message, from_email, ['admin@example.com'])
    except BadHeaderError:
      return HttpResponse('Invalid header found.')
    return HttpResponseRedirect('/contact/thanks/')
  else:
    # In reality we'd use a form class
    # to get proper validation errors.
    return HttpResponse('Make sure all fields are entered and valid.')

An BadHeaderError exception pops up if the user's input is checked for the possibility of a header injection attack.

Step 5 Send multimedia mail

By default, messages sent are in plain text format. But sometimes we want to include hyperlinks, pictures, even videos and JS actions.

Django provides us with an EmailMultiAlternatives class, which can send text and HTML content at the same time. Here is an example. Let's just write it according to it:


from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

It should be reminded that the recipient's mail service provider does not definitely support multimedia mail, perhaps for security reasons or other reasons. In order to ensure that your email content can be read, please send plain text email at the same time.


Related articles: