2021-08-04-dj-027 send mail in Django, set QQ mailbox, and log logger send mail to administrator

Posted by melrse on Sat, 01 Jan 2022 13:12:08 +0100


The password and account settings in the source code need to be added by yourself : finish the source code of this section

1, Email specific people

1. Open mail service

If you want to send mail, you must first have an email, open relevant services, and then the email will give you an authorization code.
Here is a demonstration of Netease 163 and QQ email

1.1 Netease mailbox settings



1.2 QQ mailbox settings

2. System configuration and mail sending operation

2.1 configure QQ mailbox as mail service

EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT=25
EMAIL_HOST_USER = '*********'
EMAIL_HOST_PASSWORD='*******'
DEFAULT_FROM_EMAIL = '**********@qq.com'

2.2 function analysis of sending mail

Source code:

def send_mail(subject, message, from_email, recipient_list,
              fail_silently=False, auth_user=None, auth_password=None,
              connection=None, html_message=None):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If from_email is None, use the DEFAULT_FROM_EMAIL setting.
    If auth_user is None, use the EMAIL_HOST_USER setting.
    If auth_password is None, use the EMAIL_HOST_PASSWORD setting.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """

Parameter subject, message,from_email and recipient_list is required.

subject: a string representing the title
message: a string representing the content
from_email: string, sender. If None, Django will use default_ FROM_ Value of email setting
recipient_list: a list of strings, each of which is an email address
fail_ Silent: a Boolean value. If False, send_mail() will throw SMTP lib. Exe when an error occurs SMTPException. Possible exceptions that can be encountered in the smtplib document are subclasses of their smtpexception.
auth_user: optional user name, used to verify login to SMTP server. If not, Django will use email_ HOST_ The value specified by user.
auth_password: the selected password used to verify login to the SMTP server. If not, Django will use email_ HOST_ The value specified by password.
connection: optional, the real used for sending mail. If not specified, the default is true details. Query the mail parameter document for more information.
html_message: if html is provided_ Message, the message may become an instance of multipart/alternative. The content type of message is text/plain and HTML_ The content type of message is text/html.
The return value will be the only information successfully sent (the number can only be 0 or 1, because a message is sent at the same time).

The three main parameters are subject message and recipient_list

2.3 realize mail sending in login view

                            #Email
                            loginsource=request.META['REMOTE_ADDR']
                            message=loginsource+user1.name
                            subject='login information'
                            from django.core.mail import send_mail
                            send_mail(subject=subject,message=message,recipient_list=['Own mailbox'],from_email=None)

After configuration, add the above code before the successful login jump in the login view function.
Here is a function to monitor the login of users and send emails to you. You can even delimit the user list to select people.
effect:

2, Log response auto mail

During the log configuration in the previous articles, I found that there is an email configuration in the official document, which is implemented here.

1. System configuration

First, a filter

    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },

Another such handler

       'mail_admins': {
            'level': 'ERROR',
            'formatter': 'verbose',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['require_debug_false'],
            'include_html': True,
        }

This is followed by such loggers

       'seriouslog': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True
        },

Modify and add these settings to join the administrator mailbox

DEFAULT_FROM_EMAIL = SERVER_EMAIL = '1015833437@qq.com'  # Set sender
# Administrator mailbox
ADMINS = (
    (r'amo', r'catkingfirst@163.com'),
)

# Non empty link, 404 error occurs, send notification to MANAGERS
SEND_BROKEN_LINK_EMAILS = True
MANAGERS = ADMINS

2. Call logging to trigger mail sending

Or trigger it in the middleware. This is an unregistered authentication. At this time, according to the filter settings, you need to set DEBUG to FALSE

                logging.getLogger('seriouslog').error(msg)

The first one below is that the include html is false and the second one is true

Topics: Python Django