SoFunction
Updated on 2024-10-29

Python automated office of the timed delivery of mail implementation

This is the last chapter of Python's Office Automation chapter, where you learn to use the timing module --> schedule -- by sending emails on a timed task. (This is a short chapter).

Use of the Timing Module

Python has a lightweight library for scheduling timed tasks: schedule, which can perform timed tasks every minute, every hour, every day, every day of the week, and on specific dates. So it is very convenient for us to perform some lightweight timed tasks.

Introduction to the schedule module

Timed Tasks:

The schedule module in python makes it easy to use timed tasks by automatically executing some task at a specific time.

schedule installation:

pip install schedule If the installation fails, try changing to a domestic mirror source.

Various Uses of the schedule Module

The func function is executed every how many minutes, and args are the arguments to the function:

(count).(func, args)

The func function is executed once a day at 10:20, and args are the arguments to the function:

().("10:20").do(func, args)

The schedule module supports the following times:

typology clarification
minutes minutes
seconds unit of angle or arc equivalent one sixtieth of a degree
hour hourly
day sky
week weekly

schedule The module supports much more than that, and here to describes a few of the commonly used time methods.

Startup of schedule

typology clarification
schedule.run_pending fulfillment

PS: To be executed in "while" and to utilize blocking time of at least 1 second.

The code example is as follows:

# coding:utf-8

import smtplib
import time
import schedule  # pip install schedule

from  import MIMEText
from  import Header
from  import MIMEMultipart


'''
Third-party smpt [the email addresses involved in the script are fake, please test with your own real email address]
'''

mail_host = ""     # Setting up mailbox servers
mail_user = "conan868242"       # Set up your own mailbox
mail_pass = "cb997b01a87232b2"  # Here is the passphrase for the mailbox, the authorization code; not the password.

sender = "conan868242@"     # Define the sender mailbox (which is actually yourself)
receivers = ["3241716373@"]   # Define recipient mailboxes (can be multiple recipients)

# message = MIMEText('<p style="color:red;">This is a test</p>', "html", "utf-8") # Define the content of the message; "plain" is the format, which means it's the content of a normal file
message = MIMEMultipart()       # Define mail objects with attachments

message["From"] = Header(sender)                            # Define send message within message --> sender
message["Subject"] = Header("Python Test Emailing", "utf-8")   # Define the title of the message within message
# print("Encrypted sent content \n", message.as_string()) # Printout of encrypted sent content

attr = MIMEText(open('', 'rb').read(), 'base64', 'utf-8')    # Define what to send in a message with an attachment; (an attribute by default);.
                                                                    # Read out the file to be sent as open
                                                                    # Define the content as "base64".
attr['Content-Type'] = 'application/octet-stream'   # Define the format for the attribute; "application/octet-stream" represents a protocol on the stream.
                                                    # i.e. define the type of "attachment"
attr['Content-Disposition'] = 'attachment;filename=""'       # Define a name for the transmitted attachment

(attr)        # Use the "attach" function of "message" to add "attachments" to the message.
message = MIMEText('This is an e-mail with an attachment', "plain", "utf-8")      # Define the text content of the message (i.e. add the main content of the message)

def send():
    print("The mail started to be sent.")
    try:    # Catch exceptions for sending mail
        smtpObj = ()             # Instantiate the SMTP protocol object
        (mail_host, 25)       # Linking SMTP servers
        (mail_user, mail_pass)  # Login Email Verification
        (sender, receivers, message.as_string())    # Send email; "message" encrypts the sent content string with "as_string()"
    except  as error:
        print("error:{}".format(error))


if __name__ == '__main__':
    (10).(send)     # E-mails every ten seconds

    while True:     # Start a timed task with a 1-second delay.
        schedule.run_pending()
        (1)

PS: You can consider adding the time difference between sending an email and the timed task for debugging the timed task, I'll be lazy and not write it here haha.

The results of the run are as follows:

This article on Python automated office of the realization of the timed e-mail is introduced to this article, more related Python timed e-mail content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!