Skip to main content

Automatic Birthday mail sending with Python

 The first thing we do is import six libraries: 

Apart from this, Also create an Excel sheet for containing records like this: NameEmailContactBirthday, and Year

Approach:

  • For the sending email part, We define a sendEmail() function which will start a Gmail session, send the email, and quit the session. 
  • For the SMS part, we must have an account on www.fast2sms.com from where we will get an API key. This API key is used to send SMS over mobile numbers using your account on fast2sms then We create a sendsms() function which will verify the API key and send SMS.
  • In the driver code section, we read the data from Excel sheet and match today’s date with any of the birthdays. If there is a match, we call the sendEmail() and sendsms() functions and also we add the current year in the Excel sheet. Also, we have used ToastNotifier from win10toast library to show desktop notifications once the e-mail and SMS has been sent successfully.

Below is the implementation:


# import required packages import pandas as pd import datetime import smtplib import time import requests from win10toast import ToastNotifier # your gmail credentials here GMAIL_ID = 'your_email_here' GMAIL_PWD = 'your_password_here' # for desktop notification toast = ToastNotifier() # define a function for sending email def sendEmail(to, sub, msg): # conncection to gmail gmail_obj = smtplib.SMTP('smtp.gmail.com', 587) # starting the session gmail_obj.starttls() # login using credentials gmail_obj.login(GMAIL_ID, GMAIL_PWD) # sending email gmail_obj.sendmail(GMAIL_ID, to, f"Subject : {sub}\n\n{msg}") # quit the session gmail_obj.quit() print("Email sent to " + str(to) + " with subject " + str(sub) + " and message :" + str(msg)) toast.show_toast("Email Sent!" , f"{name} was sent e-mail", threaded = True, icon_path = None, duration = 6) while toast.notification_active(): time.sleep(0.1) # define a funtion for sending sms def sendsms(to, msg, name, sub): url = "https://www.fast2sms.com/dev/bulk" payload = f"sender_id=FSTSMS&message={msg}&language=english&route=p&numbers={to}" headers = { 'authorization': "API_KEY_HERE", 'Content-Type': "application/x-www-form-urlencoded", 'Cache-Control': "no-cache", } response_obj = requests.request("POST", url, data = payload, headers = headers) print(response_obj.text) print("SMS sent to " + str(to) + " with subject :" + str(sub) + " and message :" + str(msg)) toast.show_toast("SMS Sent!" , f"{name} was sent message", threaded = True, icon_path = None, duration = 6) while toast.notification_active(): time.sleep(0.1) # driver code if __name__=="__main__": # read the excel sheet having all the details dataframe = pd.read_excel("excelsheet.xlsx") # today date in format : DD-MM today = datetime.datetime.now().strftime("%d-%m") # current year in format : YY yearNow = datetime.datetime.now().strftime("%Y") # writeindex list writeInd = [] for index,item in dataframe.iterrows(): msg = "Many Many Happy Returns of the day dear " + str(item['NAME']) # stripping the birthday in excel # sheet as : DD-MM bday = item['Birthday'].strftime("%d-%m") # condition checking if (today == bday) and yearNow not in str(item['Year']): # calling the sendEmail function sendEmail(item['Email'], "Happy Birthday", msg) # calling the sendsms function sendsms(item['Contact'], msg, item['NAME'], "Happy Birthday") writeInd.append(index) for i in writeInd: yr = dataframe.loc[i,'Year'] # this will record the years in which # email has been sent dataframe.loc[i,'Year'] = str(yr) + ',' + str(yearNow) dataframe.to_excel('excelsheet.xlsx', index = False)





Comments

Popular posts from this blog

INSTALLING PYTHON (Anaconda)

 IN WINDOWS :  Download the Anaconda installer (TIP : IF IMAGES ARE BLURRED , TAP ON THEM FOR FULL SCREEN IMAGE) 1] Click the link the download will be started! 2]  Double click the downl oaded file to launch. 3] Click NEXT 4]  Read the licensing terms and click “I Agree”. 5] Select an install for “Just Me” 6] Select a destination folder to install Anaconda and click the Next button   7] Choose whether to add Anaconda to your PATH environment variable. We recommend not adding Anaconda to the PATH environment variable, since this can interfere with other software. Instead, use Anaconda software by opening Anaconda Navigator or the Anaconda Prompt from the Start Menu. 8] Choose whether to register Anaconda as your default Python. Unless you plan on installing and running multiple versions of Anaconda or multiple versions of Python, accept the default and leave this box checked 9] Click the Install button. If you want to watch the packages Anaconda is installing, c...

World Clock

CODE FOR THIS  IS BELOW: Here, in this post, we will see how can we Get Any Country Date And Time Using Python which will be something like a World clock using Python. For this, we need the datetime module and python’s timezone module i.e.  pytz . To install pytz python, type the below command in your terminal– pip install pytz We can print the names of all countries whose timezone is available using this module using the following code– from datetime import datetime import pytz # list of desired countries Country_Zones = ['America/New_York', 'Asia/Kolkata', 'Australia/Sydney', 'Canada/Atlantic', 'Brazil/East','Chile/EasterIsland', 'Cuba', 'Egypt', 'Europe/Amsterdam', 'Europe/Athens', 'EuropeBerlin', 'Europe/Istanbul', 'Europe/Jersey', 'Europe/London', 'Europe/Moscow', 'Europe/Paris', 'Europ...

Url Shortener Project Using Python

  What you need Basics of python knowledge on Dictionary and functions knowledge on Classes and objects.        OK!! HERE IS THE CODE 😊                 import random import string     def create_shortURL(link):             chars = string.ascii_lowercase      # chars = ['a','c','z']      short_url = ''.join(random.choice(chars) for i in range ( 5 ))      d = {}      URL = 'https://www.plc.ly/' + short_url # PLC = Python Learn Camp             d[URL] = link            # This is optional        if URL in d:          print ( 'Your URL:' ,d[URL])          print ( 'Shorten URL:' ,URL) ...