Django-Send mail

Source: Internet
Author: User

An SMTP mail-sending module has been built into Python, and Django is simply encapsulated on this basis, making it easier and more flexible to send messages in a Django environment.

All the functions are in Django.core.mail.

First, get started quickly

Two lines will take care of an email:

Send_mailsend_mail' Subject here ' themessage. ' ' [email protected] '[' [email protected] 'fail_silently=False,  ' 

Import the function module and send mail, so easy!

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

Second, single send_mail ()

Method Prototypes: 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 take a look send_mail() at the method, which receives a series of parameters, where subject, message, from_email and recipient_list parameters are required, and others are optional.

    • Subject: Message subject. String.
    • Message: The specific content of the mail. String.
    • From_email: Mail sender. String.
    • recipient_listRecipient A list of strings made up of mailbox addresses. recipient_listEach member of the message will see the other members in the to: area of the mail message.
    • fail_silently: A Boolean value. If it is false, send_mail a smtplib will be thrown when the send fails. Smtpexception exception.
    • auth_user: An optional user name is used to authenticate the SMTP server, which is specified if you specifically specify which mailbox account to use. If this value is not provided, Django will use EMAIL_HOST_USER the value in Settings. If neither is provided, what else do you send???
    • auth_password: An optional password is used to authenticate the SMTP server. If this value is not provided, Django will use EMAIL_HOST_PASSWORD the value in Settings. And the above parameter is a family.
    • Connection: Optional email backend for sending mail.
    • html_message: If provided html_message , you can send a message with HTML code.

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

Third, mass send_mass_mail ()

Method Prototypes: Send_mass_mail (datatuple,fail_silently = False,auth_user = None,auth_password = None, connection = none) [Source]

send_mass_mail()Used to handle large-volume mail tasks, known as Mass.

In its parameters, Datatuple is a required parameter, and the format of each element of a tuple is received as follows:

(Subject, message, From_email, recipient_list)

The meaning of the above four fields is the same as the one send_mail() in.

For example, the following code sends two different messages to two different sets of recipients, but only one connection to the mail server is opened:

Message1 = (' Subject here ', ' This is the message ', ' [email protected] ', [' [email protected] ', ' [email protected] '] message 2 = (' Another Subject ', ' Here is another message ', ' [email protected] ', [' [email protected] ']) send_mass_mail ((Message1, ME Ssage2), Fail_silently=false)

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

send_mail()When you use a method, each time it is called, it establishes a connection with the SMTP server, which is a very inefficient process. Instead send_mass_mail() , only one link is established, and all messages are sent out for a higher efficiency.

Iv. prevention of head injection attacks

Sometimes we have to construct e-mail based on the input of the user form, there is the risk of a head injection attack, and Django gives us some protection, but more often, you need to write your own security code.

Here's an example of receiving a user-entered subject, message content, and sender, sending the message to the system administrator:

FromDjango.core.mailImportSend_mail,BadheadererrorFromDjango.httpImportHttpResponse,HttpresponseredirectDefSend_email(Request):Subject=Request.POST.Get(' Subject ',‘‘)Message=Request.POST.Get(' Message ',‘‘)From_email=Request.POST.Get(' From_email ',‘‘)IfSubjectandMessageandFrom_email:Try:Send_mail(Subject,messagefrom_email[  "[email protected] ' ]) 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 is Entered and valid. ' )               /span>              

If the user's input is checked for the possibility of a head injection attack, a badheadererror exception pops up.

V. Send multimedia mail

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

Django provides us with a emailmultialternatives class that can send both text and HTML content, and here's an example, as we write:

FromDjango.core.mailImportEmailmultialternativesSubject,From_email,To=' Hello ',' [Email protected] ',' [Email protected] 'text_content =  ' This was an important message. ' html_content =  ' <p>this ' an <strong>important</ Strong> message.</p> ' msg = emailmultialternatives (subjecttext_contentfrom_email[tomsg. Attach_alternative (html_content "text/html" Span class= "P" >) msg. Send ()               

To be reminded, the recipient's mail service provider does not necessarily support multimedia mail, perhaps for security, perhaps for other reasons. To ensure that your email content is readable, be sure to send a plain text message at the same time.

After the tutorial in the actual combat project one, there are specific examples of sending mail, please refer to learning. Direct links use Django to send mail

Django-Send mail

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.