Use Django's built-in functions and celery mail

Mailbox configuration

Open stmp Service

163 E-mail, for example, click Settings inside stmp

 

Open client license key

 As shown above, because I have opened, so there is more than a page.

In this way, prepare the mailbox has been completed.

 

Django mail using built-in functions

1. Add the following configuration settings file

# Mail settings 
EMAIL_BACKEND = ' django.core.mail.backends.smtp.EmailBackend ' 
EMAIL_HOST = ' smtp.163.com ' 
EMAIL_PORT = 25
 # E-mail mailbox 
EMAIL_HOST_USER = ' E-mail mailbox ' 
# in the mailbox of the client provided side authorization password 
EMAIL_HOST_PASSWORD = ' authorization code ' 
# recipients to see the sender 
EMAIL_FROM = ' green orchards <send mail mailbox> '

 

2. Write the code to send mail

 
 
from django.shortcuts import render, redirect, HttpResponse
from django.core.mail import send_mail
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

DEF
emailtest (Request): # send the activation email, including the activation link: HTTP: //127.0.0.1: 8000 / the User / the Active / 3 # active links need to include the user's identity information and identity information should be encrypted # encryption user's identity information, generates an activation token the userid. 3 = in email = " received email account " Serializer = the Serializer (settings.SECRET_KEY, 1800 ) info = { ' Confirm ' : the userid} token = serializer.dumps (info) token = token .decode () # mail Subject = " green orchards welcome message " the message ="" SENDER = settings.EMAIL_FROM Receiver = [Email] html_message = " <h2> green orchards welcome you to become registered members </ h2> </ br> Click on the following link to activate the account <a href = 'http: 127.0.0.1 : 8000 / " \ " 127.0.0.1:: 8000 / User / Active /% S </a> User / Active / HTTP% S '> " % (token, token) the send_mail (Subject, Message, SENDER, Receiver, html_message = html_message) # returns a response, goto return HttpResponse ( " e-mail sent successfully, please note that the reception " )

Supporting url

= the urlpatterns [ 
    URL (R & lt ' ^ emailtest / $ ' , views.emailtest, name = " emailtest " ),   # mail test 
]

 

3. Enter the following address in your browser, you can see "Mail Sent" message

http://127.0.0.1:8000/user/emailtest/

Received mail as shown in FIG.

received e-mail

Mail content details

 

Use celery mail

When using the built-in function to send a message django, django stmp server to send mail takes time, stmp server sends a message to the user takes time, but this time in sending mail, the user is waiting for the server to return a response, if the waiting time too long, it will undoubtedly greatly reduce the user experience.

This time, we can use celery to asynchronously send messages that Django server to send mail while celery, returns the response to the user. Here, we use sleep to simulate sending mail from time to time.

 

1. Installation celery

pip install celery

 

2. configuration settings file

# Mail settings 
EMAIL_BACKEND = ' django.core.mail.backends.smtp.EmailBackend ' 
EMAIL_HOST = ' smtp.163.com ' 
EMAIL_PORT = 25
 # E-mail mailbox 
EMAIL_HOST_USER = ' E-mail mailbox ' 
# in the mailbox of the client provided side authorization password 
EMAIL_HOST_PASSWORD = ' client license key ' 
# recipients to see the sender 
EMAIL_FROM = ' green orchards <send mail mailbox> ' 

# Django cache configuration 
cACHES = {
     " default " : {
         " BACKEND ": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/9",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

 

3. In the New Project celery_tasks folder, the new tasks in the file folder, write tasks file ;

from django.core.mail Import send_mail
 from django.conf Import Settings
 from Celery Import Celery
 Import Time 

# at the end of the task handler when the need to add these words 
# Import os 
# Import Django 
# os.environ.setdefault ( "DJANGO_SETTINGS_MODULE", " project name .settings ") 
# django.setup () 

# create an instance of an object class Celery 
App = Celery ( ' celery_tasks.tasks ' , Broker = ' Redis: //127.0.0.1: 6379/8 ' ) 


# define the task function 
app.task @
 DEFsend_register_active_email (to_email, username, token):
     "" " send activation messages " "" 
    Subject = " green Orchard welcome message " 
    Message = "" 
    SENDER = settings.EMAIL_FROM 
    Receiver = [to_email] 
    html_message = " <H2>% S, welcomed you become green orchards registered members </ h2> </ br> click on the following link to activate the account href='http:127.0.0.1:8000/ <a "\"
                    user/active/%s'> HTTP: 127.0.0.1: 8000 / User / Active / S </a>% " % (username, token, token) 
    the send_mail (Subject, Message,sender, receiver, html_message=html_message)
    time.sleep(5)

 

4. Where transmitted messages call in at celery_tasks tasks send message function ;

from django.shortcuts Import the render, redirect, HttpResponse
 from django.core.mail Import send_mail
 from itsdangerous Import TimedJSONWebSignatureSerializer AS the Serializer
 from django.conf Import Settings 

DEF emailtest (Request):
     # send the activation email, including the activation link: http: //127.0 .0.1: 8000 / user / Active /. 3 
    # active links need to include the user's identity information and the identity information should be encrypted 
    # encrypted user identity information, generates an activation token 
    the userid. 3 = 
    username = " mumun " 
    in Email = " closed Mail mailbox "
    Serializer = the Serializer (settings.SECRET_KEY, 1800 ) 
    info = { ' Confirm ' : the userid} 
    token = serializer.dumps (info) 
    token = token.decode ()
     # using celery send mail 
    send_register_active_email.delay (In Email, username, token) 

    # returns a response, goto 
    return HttpResponse ( " e-mail sent successfully, please note that the reception " )

Supporting url

= the urlpatterns [ 
    URL (R & lt '^ emailtest / $', views.emailtest, name = "emailtest"), # mail test 
]

 

5. turn redis services ;

E:\>cd E:\YifChanSoft\Database\Redis\RedisSoft\Redis-x64-3.2.100

E:\YifChanSoft\Database\Redis\RedisSoft\Redis-x64-3.2.100>redis-server --service-install redis.windows-service.conf --loglevel verbose

E:\YifChanSoft\Database\Redis\RedisSoft\Redis-x64-3.2.100>redis-cli
127.0.0.1:6379> select 8
OK
127.0.0.1:6379[8]> keys *
(empty list or set)
127.0.0.1:6379[8]> keys *
1) "_kombu.binding.celery"
2) "_kombu.binding.celery.pidbox"
3) "_kombu.binding.celeryev"

Screenshot turn redis service

 

6. The project code copy somewhere, enter the premises, start tasks of worker model ,
note, used as a file code of worker's tasks should have started django initialization code in advance, otherwise the worker can not call conf information;

That should have the following

# In-tasking need to add a few words when the end of this 
Import os
 Import Django 
os.environ.setdefault ( " DJANGO_SETTINGS_MODULE " , " project name .settings " ) 
django.setup ()

Open worker mode :

celery -A celery_tasks.tasks worker -l info

There is a problem , given as follows

ValueError: not enough values to unpack (expected 3, got 0)

The reason
run celery4.x this problem occurs on win10
solve

pip install eventlet

And add parameters in the open mode worker

celery -A celery_tasks.tasks worker -l info -P eventlet

Worker shot mode is turned on, and there are content, but because of too much, it is only half cut

 

 

7. Enter the following address in your browser, you can see "Mail Sent" message

http://127.0.0.1:8000/user/emailtest/

Incoming mail is as follows

 

Guess you like

Origin www.cnblogs.com/yifchan/p/python-1-34.html