How To Use Python To Send An Email On The Last Day Of Each Month

This example will tell you how to use the python datetime module to get the last day of each month, and how to use the python smtplib module to send an email at the last day of each month with linux cron job.

1. Get The Last Day Of Current Month By Python datetime Module.

# Import datetime module
import datetime

"""
  Get the last day of the input date month.
  :param any_day: any date.
  :return: string

  how to use : res = last_day_of_month(datetime.date(year, month, day))

  # Notice: year, month and day must be an integer number.
  year = 2021
  month = 1 
  day = 6
"""

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=next_month.day)

# Get the current date
now = datetime.datetime.now().date()

# Get current year, month and day by split above date value.
year,month,day = str(now).split("-")  
# Convert year, month, day to integer number value.
year = int(year)
month = int(month)
day = int(day)

# Get the last day of the month.
last_day = last_day_of_month(datetime.date(year, month, day))

# Check whether the current date is the end of the month.
if str(now) == last_day:
    print('yes')
else:
    print('no')

2. Send Email By Python smtplib Module.

There are two python files in send email step, send_email.py, and alert.py.

send_email.py – send email.

import sys

# Import python smtplib module
import smtplib  
from email.mime.text import MIMEText
from email.utils import formataddr

'''
SendEMail class is used to send email by smtp protocol.
'''
class SendEMail(object):
    
    # SendEMail class constructor.
    def __init__(self, sender, title, content):
        
        # Receiver email address. 
        self.sender = sender  
        
        # Email title.
        self.title = title

        # Email content.
        self.content = content

        # Sender email address.
        self.sys_sender = '[email protected]'

        # Sender password.
        self.sys_pwd = '666666'


    def send(self):
        try:
            """
            Create a MIMEText object. The first parameter is the email content. The second parameter is the subtype of MIME, after passing in 'html', the final MIME value is' text / html '.
            The last parameter is 'utf-8', we must use 'utf-8' encoding to ensure multi language compatibility
            """
            msg = MIMEText(self.content, 'html', 'utf-8')
            
            # Sender title and email address
            msg['From'] = formataddr(["Development team", self.sys_sender])
            
            # Receiver email address.
            msg['To'] = formataddr(["", self.sender])
            
            # The email subject.
            msg['Subject'] = self.title
            
            # SMTP email server with domain / ip and port number.
            server = smtplib.SMTP("smtp.google.com", 25)
            
            # Login sender email account.
            server.login(self.sys_sender, self.sys_pwd)
          
            # Send the email.
            server.sendmail(self.sys_sender, [self.sender, ], msg.as_string())
            
            # Quit the email account.
            server.quit()
            return True
        except Exception as e:
            print(e)
            return False


if __name__ == '__main__':
    
    # Number of parameters, due to sys.argv [0] is the script name, so subtract 1
    num = len(sys.argv) - 1
    if num < 3 or num > 3:
        exit("Parameter error, must pass in 3 parameters! The current number of parameters is %s" % num)
    
    # The first parameter is the sender's email address.
    sender = sys.argv[1]  

    # The second parameter is the email subject.
    title = sys.argv[2]

    # The third parameter is email content.
    content = sys.argv[3]

    # Create an instance of SendEMail and invoke it's send() method to send an email by smtp. 
    sendEmailObj = SendEMail(sender, title, content)
    ret = sendEmailObj.send()
    if ret:
        print('Send email success!')
    else:
        print('Send email fail!')

alert.py – check whether the current date is the last day of the month, if yes then create an instance of the above SendEMail class, and send an email by invoking the instance’s send() method.

"""
Send an email at the end of the month.
"""

import datetime
from send_mail import SendMail

class AlertServices(object):
    def __init__(self):
        pass

    def last_day_of_month(self,any_day):
        """
        Get the last day of the month
        :param any_day: any date value.
        :return: string
        """
        next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
        return next_month - datetime.timedelta(days=next_month.day)
    
    def send_email_at_month_end(self):

        # Get current date.
        now = datetime.datetime.now().date()

        # Get year, month, day by split current date.
        year,month,day = str(now).split("-") 
        # Convert above year, month, day to integer number.
        year = int(year)
        month = int(month)
        day = int(day)
        
        # Get the last day of current month.
        last_day = self.last_day_of_month(datetime.date(year, month, day))
        
        # Check whether the current date is the end of the month, if not then print an error message and return.
        if str(now) != last_day:
            print("It is not the end of the month.")
            return False
        
        # If the current date is the last day of the month then send the email.
        
        # The receiver email address
        sender = "[email protected]"  
        # The email subject.
        title = "It is the end of the month"
        # The email content.
        content = "Do not forget to check your bank account"

        # Send email by create the SendEMial object and invoke it's send() method.
        sendEmailObj = SendEMail(sender, title, content)
        ret = sendEmailObj.send()
        if ret:
            print('Send email success!')
        else:
            print('Send email fail!')
            
if __name__ == '__main__':
    # Create an instance of AlertServices class. 
    alert = AlertServices()
    # Invoke AlertServices object send_email_at_month_end() method.
    alert.send_email_at_month_end()

Define the Linux cron task plan and execute it at 9 am every day.

0 9 * * * root /usr/bin/python /usr/tom/alert.py

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.