Categories
Uncategorized

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

#

E-Mail settings

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25 #

Send e-mail messages

EMAIL_HOST_USER = '

Send e-mail messages

' #

Set in the mail client authorization password

EMAIL_HOST_PASSWORD = '

Authorization Codes

' #

The recipient can see the sender

EMAIL_FROM = '

Green orchards

'

 

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 activation e-mail, including the activation link: http: //127.0.0.1: 8000 / user / active / 3

#

Active links need to include the user's identity information and identity information should be encrypted

#

Encrypted user identity information, generates an activation token

userid = 3 email = "

Incoming mail email account

" serializer = Serializer(settings.SECRET_KEY, 1800) info = {'confirm': userid} token = serializer.dumps(info) token = token.decode() #

send email

subject = "

Green orchards welcome message

" message = "" sender = settings.EMAIL_FROM receiver = [email] html_message = "

green orchards welcome you to become registered members please click on the following link to activate the account

" \ "user/active/%s'>http:127.0.0.1:8000/user/active/%s" % (token, token) send_mail(subject, message, sender, receiver, html_message=html_message) #

Returns a response, goto

return HttpResponse("

Mail sent successfully, please note reception

")

Supporting url

urlpatterns = [
    url(r'^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. Install celery

pip install celery

 

2. configuration settings file

#

E-Mail settings

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25 #

Send e-mail messages

EMAIL_HOST_USER = '

Send e-mail messages

' #

Set in the mail client authorization password

EMAIL_HOST_PASSWORD = '

Client Authorization Codes

' #

The recipient can see the sender

EMAIL_FROM = '

Green orchards

' #

diango 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, file writing tasks;

from django.core.mail import send_mail
from django.conf import settings
from celery import Celery
import time

#

When the task handler that end need to add a few words

# import os # import django #

os.environ.setdefault ( "DJANGO_SETTINGS_MODULE", "project name .settings")

# django.setup() #

Create an instance of a class Celery

app = Celery('celery_tasks.tasks', broker='redis://127.0.0.1:6379/8') #

Defined task function

@app.task def send_register_active_email(to_email, username, token): """

Send activation email

""" subject = "

Green orchards welcome message

" message = "" sender = settings.EMAIL_FROM receiver = [to_email] html_message = "

% s, you are welcome to become green orchards registered members please click on the following link to activate the account

" \ "user/active/%s'>http:127.0.0.1:8000/user/active/%s" % (username, token, token) send_mail(subject, message, sender, receiver, html_message=html_message) time.sleep(5)

 

4. The function call to send the message in the local tasks under celery_tasks send messages;

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 activation e-mail, including the activation link: http: //127.0.0.1: 8000 / user / active / 3

#

Active links need to include the user's identity information and identity information should be encrypted

#

Encrypted user identity information, generates an activation token

userid = 3 username = "mumun" email = "

Incoming mail mailbox

" serializer = Serializer(settings.SECRET_KEY, 1800) info = {'confirm': userid} token = serializer.dumps(info) token = token.decode() #

Use celery to send mail

send_register_active_email.delay(email, username, token) #

Returns a response, goto

return HttpResponse("

Mail sent successfully, please note reception

")

Supporting url

urlpatterns = [
    url(r'^emailtest/$', views.emailtest, name="emailtest"),  # 发邮件测试
]

 

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

#

When the task handler that end need to add a few words

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

Problems, being given as follows

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

Run celery4.x will solve this problem on the reasons for win10

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

 

Leave a Reply