How to Automatically Send Happy Birthday Emails With Python

CodingCampus
5 min readNov 23, 2023

--

Do you constantly forget to wish your friends a happy birthday? Well, you are not alone. As a Python programmer, you can automate the entire process of sending happy birthday emails and bring joy to your friends! The Happy birthday message should read as “Happy Birthday To My Dear Friend.” You are free to customize the message by editing the program.

Pre-requisites and getting Ready

To follow the tutorial, you need to match the following pre-requisites

  • Know the basics of Python
  • Have a code editor installed. In our case, we’ll use Visual Studio Code.
  • Have pip installed
  • Have a CSV data file where you have your friends listed in a chosen format.

There are also library pre-requisites that you will need to create the Happy Birthday Script. These include:

To install pandas using pip, use the following command.

pip install pandas

Next comes smtplib. Just like pandas, you can install them with the pip command.

pip install smtplib

Next comes the CSV file. Let’s name it friend_birthday.csv

Put your friend details in the following format: — Name, Email, Contact, BirthDay, Year; separated by comma(,). It should look like this.

name,email,contact, birthday, year
Soumik,soumikiggaboi@gmail.com, NO, 1994-5-10, 1994
Hreezey,hreezeymillionaire@gmail.com, NO, 1992-10-12, 1992
Prateek,prateekeatsleepgame@gmail.com, NO, 1990-7-8, 1990

You need to put the friend_birthday.csv file in the same folder as your script.

Awesome! We have all our pre-requisites done. Now, let’s start with our Happy_Birthday.script

When you put it in the same folder, and open it using the Visual Studio Code, it will be shown as below.

Friend Birthday Format in Visual Studio Code

Automatically sending Happy Birthday Emails with Python

Our program logic is to connect to GMAIL through smtplib and sends the email through it. We are keeping our program as simple as possible and not using HTML. If you opt to use HTML within your message, you need to use MIMEText and MIMEMultipart, which you can import from email.mime.text and email.mime.multipart respectively.

Let’s look at the code below.

#import all the necessary libraries
import pandas as pd
from datetime import datetime
import smtplib
import time
#import your email address and password
#suggested to create new email ID to do it
EMAIL_ID = "email_address"
EMAIL_PWD = "password"
def sendEmailToFriend(send_to,subject,msg_to_friend):
#connect to your email address
email_obj = smtplib.SMTP('smtp.gmail.com', 587)
#Starting the email session
email_obj.starttls()
#using the login credentials
email_obj.login(EMAIL_ID, EMAIL_PWD)
#Sending the email to the friend or known acquitance
email_obj.sendmail(EMAIL_ID, send_to, f"Subject: {subject}nn{msg_to_friend}")
#ending the session
email_obj.quit()
print("Email successfully sent to" + str(send_to) + "n The subject is: " + str(subject) + "nThe message is:" + str(msg_to_friend))#main codeif __name__ == "__main__": #Take data from the excel sheet
dataframe = pd.read_csv(r"E:ProjectsPythonSend_Happy_Birthday_Emailfriend_birthday.csv")
#Time and date today
today = datetime.now().strftime("%d-%m")
#Year format currentYear = datetime.now().strftime("%Y") #index where we store which friends birthday are wished
friend= []
for index,item in dataframe.iterrows():
msg = "Happy Birthday To My Dear Friend" + str(item['NAME'])
#getting the birthdate from the excel sheet
bday = item['Birthday'].strftime("%d-%m")
#check the conditions, if matching send the birthday message
if (today == bday) and currentYear not in str(item['Year']):
#call the functions
sendEmailToFriend(item['Email'], "Happy Birthday", msg)
friend.append(index)
for i in friend:

yr = dataframe.loc[i, 'Year']
dataframe.loc[i, 'Year'] = str(yr) + ',' + str(currentYear)
dataframe.to_excel('friend_birthday.csv', index=False)

That’s a total of 73 lines of code! But, don’t worry, we will explain the important parts to give you what’s going on!

Importing the necessary libraries

import pandas as pd
from datetime import datetime
import smtplib
import time

Here, we import the required libraries to run our script. We import pandas, datetime, smtplib, and time.

Import your email address and password

EMAIL_ID = "email_address"
EMAIL_PWD = "password"

You need to put your Gmail address in place of “email_address” and Gmail password in place of “password”.

Note: it is advisable to create a new email for security as anyone who gets your script can compromise your email address.

SendEmailToFriend Function

def sendEmailToFriend(send_to,subject,msg_to_friend):
#connect to your email address
email_obj = smtplib.SMTP('smtp.gmail.com', 587)
    #Starting the email session
email_obj.starttls()
#using the login credentials
email_obj.login(EMAIL_ID, EMAIL_PWD)
#Sending the email to the friend
email_obj.sendmail(EMAIL_ID, send_to, f"Subject: {subject}nn{msg_to_friend}")
#ending the session
email_obj.quit()
print("Email successfully sent to" + str(send_to) + "n The subject is: " + str(subject) + "nThe message is:" + str(msg_to_friend))

With the SendEmailToFriend function, we set up our connection to Gmail and then send the message to the friend.

email_obj = smtplib.SMTP('smtp.gmail.com', 587)
email_obj.starttls()
email_obj.login(EMAIL_ID, EMAIL_PWD)

The first two lines of code establish the connection to Gmail servers. Next, log in to your Gmail by using the login() function and passing the EMAIL_ID and EMAIL_PWD variables that we defined earlier.

email_obj.sendmail(EMAIL_ID, send_to, f"Subject: {subject}nn{msg_to_friend}")

This line of code sends the email and passes your EMAIL_ID, send_to variable, which contains your friend’s email address, and then the Subject with msg_to_friend variable that we define later.

Finally, we close the connection by using email_obj.quit() and then printing out that the email has been successfully sent.

The main function

if __name__ == "__main__":
#Take data from the excel sheet
dataframe = pd.read_csv(r"E:ProjectsPythonSend_Happy_Birthday_Emailfriend_birthday.csv")
#Time and date today
today = datetime.now().strftime("%d-%m")
#Year format
currentYear = datetime.now().strftime("%Y")
    #index where we store which friends' birthday are wished    friend = []    for index,item in dataframe.iterrows():
msg = "Happy Birthday To My Dear Friend" + str(item['NAME'])
#getting the birthdate from the excel sheet
bday = item['Birthday'].strftime("%d-%m")
#check the conditions, if matching send the birthday message
if (today == bday) and currentYear not in str(item['Year']):
#call the functions
sendEmailToFriend(item['Email'], "Happy Birthday", msg)
friend.append(index)
for i in friend: yr = dataframe.loc[i, 'Year'] dataframe.loc[i, 'Year'] = str(yr) + ',' + str(currentYear) dataframe.to_excel('friend_birthday.csv', index=False)

The first thing we do is import our friend’s data from friends_birthday.csv. This is done by using the following line of code.

dataframe = pd.read_excel(friend_birthday.csv)

Next, we use the DateTime library to get today’s time and the currentYear.

today = datetime.datatime.now().strftime("%d-%m")

currentYear = datetime.datetime.now().strftime("%Y")

We also create an empty list which we will use to store information about our friends.

Next, we use a simple for loop to go through each data row and see if a friend’s birthday is today or not. If it is, then call the SendEmailToFriend function.

Lastly, we update the index on our friend_birthday.csv and set it to False for every friend to whom the script has sent an email.

If everything goes right, your friend should receive the Happy Birthday Email message on their birthday.

Happy Birthday Email Sent To Friend

--

--