SoFunction
Updated on 2024-10-29

Django send email and itsdangerous module with the use of analysis

Program Requirements:After registering on the user registration page, the system will send an email to the user's email address, and the user will click on the link to activate the account, where the user information in the link needs to be encrypted.

One of the activation of their mailbox smtp service operation will not be explained, on a very clear explanation, you can also go online to search for detailed steps

First of all, configure the configuration related to sending emails in the settings file of the Django project as follows:

# Fixed writing
EMAIL_BACKEND = ''
# smtp server address
EMAIL_HOST = ''
# Fixed port number
EMAIL_PORT = 25
# Mailboxes for sending emails
EMAIL_HOST_USER = '2746565701@'
# Client authorization password set in mailbox
EMAIL_HOST_PASSWORD = 'ytnvwapcbxmcdfig'
# The sender as seen by the recipient, in pointed brackets must match the user above
EMAIL_FROM = 'Daily Fresh<2746565701@>'

The user module's file about itsdangerous and mail sending code is as follows, the rest of the project's operation code is deleted here, and a class-based view is used here:

Basic logic:

  • Encrypt the user information in the link using itsdangerous module to generate an encrypted user information token;
  • Call the methods related to Django Send Mail to send emails (the configuration of emails is already configured);
  • The link sent in the email has a variable parameter that contains the user id encrypted;
  • After receiving the email, the user clicks on the link and jumps to the corresponding view class for processing;
  • The view class responsible for activation, decrypting the user's information, obtaining the user id, and querying to the corresponding user (the process determines whether the encrypted information has timed out);
  • Change the value of the is_active field in the Users table in the database for the corresponding user to 1 to indicate that this user is active;
  • Jump to the home page;
# Import the encryption classes to be used in itsdangerous
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# Import timeout exception in itsdangerous
from itsdangerous import SignatureExpired
# Import configuration files
from  import settings
# Importing Send Mail in Django
from  import send_mail
from .models import User



# Create your views here.
class RegisterView(View):
  """Register."""
  ....................
   
  def post(self, request):
    """Perform the registration process."""  

    # Send an activation email with an activation link: https://127.0.0.1:8000/user/active/3
    # The activation link needs to contain the user's identity information and encrypt that identity information.

    # Encrypt the user's identity information to generate an activated token
    serializer = Serializer(settings.SECRET_KEY, 3600) # Create an object that loves the encryption class in the itsdangerous module, where SECRET_KEY is used from settings and the second parameter is the timeout time
    info = {'confirm': } # encrypted message, a dictionary whose value is the id of the user who received the message
    # Encrypted using dumps method, encrypted as bytes of data
    token = (info) # bytes of data
    token = () # bytes to str
    # Send an e-mail
    subject = 'Daily Fresh Welcome Message' # Subject of the e-mail
    message = '' E-mail messages,since there arehtml__message(modal particle intensifying preceding clause),So just leave it blank.
    sender = settings.EMAIL_FROM # Senders, import the above configured senders directly from the configuration file
    receiver = [email] # Recipient's email, is a list, here is the front-end user registration passed email
    # html structured message containing encrypted user information token
    html_message = '<h1>{},Welcome to become a registered member of Daily Fresh</h1>Please click on the link below to activate your user<br><a href="http:127.0.0.1:8000/user/active/{}" rel="external nofollow" >http:127.0.0.1:8000/user/active/{}</a>'.format(username, token, token)
    # Call Django's method for sending emails, here passed 5 parameters
    send_mail(subject, message, sender, receiver, html_message=html_message)
    # Return to Answers: Jump to Home Page
    return redirect(reverse('goods:index'))


class ActiveView(View):
  """User activation"""
  def get(self, request, token):
    """Perform user activation"""
    # Perform decryption to obtain information about the user to be activated
    serializer = Serializer(settings.SECRET_KEY, 3600)
    try:
    # Decrypted by the loads method of the itsdangerous module
      info = (token)
      # Get the id of the user to be activated
      user_id = ('confirm')
      # Get user information based on id
      user = (id=user_id)
      # Activate the user operation by changing the is_active parameter of the corresponding user in the database to 1
      user.is_active = 1
      ()
      # Jump to the login screen
      return redirect(reverse('user:login'))
    except SignatureExpired as e:
      # The activation link has expired
      return HttpResponse('The activation link has expired!')

This is the whole content of this article, I hope it will help you to learn more.