SoFunction
Updated on 2025-04-14

Solve the problem that the Pytest script cannot send emails in Cron timed tasks

introduction

Running Pytest using Cron timed tasksWhen scripting, sometimes you will encounter the problem that the script can be successfully executed, but the email sending function cannot work properly. This problem is usually caused by insufficient environment configuration, incorrect path settings, or improper mail server configuration. This article will explore how to solve this problem and provide detailed steps and solutions.

1. Environment variable optimization: Ensure that Cron tasks can be executed correctly

First, make sure that the script environment you run in the Cron timing task is consistent with the environment you usually run manually in the terminal. In a development environment, Pytest scripts usually rely on some environment variables that need to be properly configured in a Cron task.

Solution:

It can be optimized by splitting longer commands into scripts andcronCall this script to avoid directcronWrite too long commands in. This is not only simple, but also easy to manage and maintain.

1.1. Create a script

First, create a new script file in the project directory, for examplerun_manage.sh, the content is as follows:

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Set environment variables (replace with the address of your real virtual environment)export PATH=/root/myenv/bin:$PATH
export PYTHONPATH=/root/myenv/bin/packages:$PYTHONPATH

# Activate the virtual environment (replace with the address of your real virtual environment)source /root/myenv/bin/activate

# Execute script (replace/path//project/ with your script path)/root/myenv/bin/python /path/to/project/ >> /var/log/ 2>&1

Make sure the script is executable (replace with your real run_manage.sh path):

chmod +x /path/to/run_manage.sh

1.2. Modify cron configuration

Then, incronCall the script in . RevisecronThe configuration is as follows:

00 08 * * * cd /path/to/project && /path/to/run_manage.sh

This avoidscronWrite too long commands in it, improving readability and maintainability.

2. The script can be executed, but the email sending fails

When the script can run successfully after ensuring that the environment of the Cron task is configured correctly, but the mail sending is still unsuccessful, the problem may be in the configuration of the mail server or the mail settings of the Pytest.

Solution:

Check the Python mail configurationMake sure that the mail-related settings are correctly configured in the configuration file of the Pytest project. The email configuration of QQ is as follows:

def send_email(total, passed, failed):
 # Email content settings subject = "Pytest Test Report"
 body = f"""
 <html>
   <body>
     <p>Hi all:</p>

   
     <p>The following are the results of this interface test:</p>
<ul>
     <li ><strong>Total number of tests: {total}</strong></li>
     <li ><strong>Pass number:{passed}</strong></li>
     <li style="color: red;"><strong>Number of failures:{failed}</strong></li>
</ul>
     <p>                               Testing Team</p>
   </body>
 </html>
"""
 mail_host = ""  # Set up the server sender_email = "ZZZZZZZZZ@"  # username receiver_email = "ZZZZZZZZZZZZ@"
 password = "###############" # Authorization code
 # Set MIME mail object msg = MIMEMultipart()
 msg['From'] = "ZZZZZZZZZ@"
 msg['To'] = receiver_email
 msg['Subject'] = subject

 # Embed report into email body using 'html' format (MIMEText(body, 'html'))

 # Send email try:
     with (mail_host, 587) as server:
         ()  # Send EHLO again to update the secure session         ()  # Start TLS encryption         ()  # Send EHLO command         (sender_email, password)  # Log in with the authorization code         (sender_email, receiver_email, msg.as_string())
     print("Email sent successfully")
 except  as e:
     print(f"SMTP error occurred: {e}")
 except Exception as e:
     print(f"Failed to send email: {e}")

3. Configuration file: Ensure that SMTP service works properly

If the email is still unsuccessful, the problem may be due to the mail service itself, especially the SMTP server configuration. You can try configuringfile to adjust the relevant parameters of email sending.

3.1. Edit the file

When using Postfix and other mail servers,Files control the configuration of the mail service. You can check and make sure that the following configuration items are correctly set:

# editsudo nano /etc/postfix/

Make sure the following settings are correct:

 # Enable SASL authentication smtp_sasl_auth_enable = yes
 smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
 smtp_sasl_security_options = noanonymous
 smtp_sasl_tls_security_options = noanonymous
 # TLS configuration smtp_use_tls = yes
 smtp_tls_security_level = encrypt
 smtp_tls_CAfile = /etc/ssl/certs/
 alias_maps = hash:/etc/aliases
 alias_database = hash:/etc/aliases

 mydestination = localhost, ,ajcloud,net
 myhostname = 
 mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
 mailbox_size_limit = 0
 recipient_delimiter = +
 inet_interfaces = all
 inet_protocols = all
 relayhost = []:587
 debug_peer_level = 3
 debug_peer_list = 
 smtp_helo_name = 
 smtpd_helo_required = yes
 myorigin = /etc/mailname
 smtp_generic_maps = hash:/etc/postfix/generic

These settings allow Postfix to authenticate through the specified SMTP server and enable TLS encryption to ensure the security of the message.

3.2. Configure the sasl_passwd file

If you use SMTP authentication, you also need to configure itsasl_passwdFile, specify the authentication information of the SMTP server:

# Edit sasl_passwdsudo nano /etc/postfix/sasl_passwd

The content of the file should be:

[]:587    your-email@:your-email-password

Then run the following command to generate a password hash:

sudo postmap /etc/postfix/sasl_passwd

For postfixAdd these two configuration items to the file, you can follow the following steps:

3.3. Configure generic files

Add the following configuration items to the file:

myorigin = /etc/mailname
smtp_generic_maps = hash:/etc/postfix/generic

What are the functions of these two configuration items:

  • myoriginUsed to specify the source domain name of the message, usually set to/etc/mailname, it will use the domain name in the file as the sender address of the email.
  • smtp_generic_mapsUsed to specify how Postfix handles sender address mapping,/etc/postfix/genericFiles are often used to map local sender addresses to mail addresses of external SMTP servers.

If you haven't created it/etc/postfix/genericFile, you need to create the file and configure the mapping rules. For example:

sudo nano /etc/postfix/generic

Add mapping rules similar to the following in the file:

# Format: Local User -> External Email Addressroot@   [Fill in the scriptsender_email]
root@localhost          [Fill in the scriptsender_email]
[Fill in the scriptreceiver_email] [Fill in the scriptreceiver_email]

3.4. Generate the hash file of the generic file

After configuration, it needs to be generatedgenericThe hash file of the file, the command is as follows:

sudo postmap /etc/postfix/generic

3.5. Restart Postfix service

After the configuration is completed, restart the Postfix service to make the configuration take effect:

sudo systemctl restart postfix

3.6. Add MAILTO to cronf

MAILTO=[Fill in the scriptreceiver_email]

4. Troubleshoot other FAQs

  • Mail Firewall/Anti-virus: Sometimes a firewall or antivirus software may block SMTP connections, ensuring that the relevant ports (usually 587 or 465) are open in the firewall.

Summarize

By correctly configuring environment variables, checking Pytest email settings, debugging scripts and server configuration, the problem of email sending failure when running Pytest scripts through Cron tasks can be effectively solved. Ensure that the environment of the Cron task is consistent with the manual runtime, check the mail server configuration, and troubleshoot errors in combination with log output, and finally, the mail function can be successfully run in the timing task.

The above is the detailed content to solve the problem that the Pytest script cannot send emails in Cron timed tasks. For more information about the Cron Pytest script cannot send emails, please follow my other related articles!