DAY 31 - Organize a Secret Santa Game in your organization using a Python Script

 The script will perform below mentioned activities:

1.     Assign a Secret Santa randomly to each participant

2.     Save the final extract into an excel file

3.     Send an automated mail to each Secret Santa with a complete address details of his/her Secret Santa Child

 

Sample final extract file:



Sample Mail Format:


Prerequisite:

1.     Collect information of participants in an excel file as shown below.


2. Click on “Manage your Google Account” > Security > Less secure app access

Turn ON access for less secure app

Note - This setup is required to send a mail from Gmail using Python script


 


Python Script:

# -*- coding: utf-8 -*-

"""

Created on Wed Dec 2 12:15:58 2020


@author: Rakesh.Ranjan

"""



import random

import pandas as pd

import numpy as np

import os

import string 



ss_keys = []

ssc_values = []



input_file_name = "Secret Santa - Information needed-Test_File.xlsx"

output_file_name = "Secret Santa Assignment-11.xlsx"


#read input file into a dataframe 

input_file = pd.read_excel(input_file_name)


#extract email ID of the participants 

#to convert input_string into a list

ss_participants = list(input_file["Email ID"])

ss_child        = list(input_file["Email ID"])



#secret santa list .......converting each character to lowercase

ss_participants = list(map(lambda x:x.lower(),ss_participants))


#secret santa child list. Keep on removing name of child from the list after each iteration

ss_child = list(map(lambda x:x.lower(),ss_child))


#remove junk characters from Address field 

input_file.Address = input_file.Address.apply(lambda x:x.strip(string.punctuation + string.whitespace))


print('Total Count Of Participants: ' , len(ss_participants))

print ('###############################################################')

#iteration for each participant to find his/her secret santa child

for i in ss_participants:

    msg = ""

    email = i

    #logic to extract first name of secret santa from email_id

    ss_email_breakup_list = email.split(".")

    ss_name = ss_email_breakup_list[0].capitalize()

    msg = 'Hello ' + ss_name + ',' + os.linesep + os.linesep #used linesep for new line 

   


    #pick a random name. so we are using function# "random.choice" to find secret santa - child

    secret_santa_child = random.choice(ss_child)



    #written logic to exclude secret santa name so that he/she won't buy a gift for himself/herself

    while secret_santa_child == email:

          secret_santa_child = random.choice(ss_child)


    #remove secret santa - child name from the list so that same person won't receive the gift more than once

    ss_child.remove(secret_santa_child)


    #Keep adding a Secret santa name in the list - test_keys

    ss_keys.append(email)

    ##Keep adding a corresponding value of Secret santa child name in the list - test_values

    ssc_values.append(secret_santa_child)


    #logic to extract first name of secret santa - child from email_id

    ssc_email_id_breakup_list = secret_santa_child.split(".")

    ssc_name = ssc_email_id_breakup_list[0].capitalize()

    

         

    msg = msg + 'You are Secret Santa for :' + ssc_name + ' (' + secret_santa_child + ').' + 'Please send your gift at below address and ensure that it’s delivered before Dec 15th.' 

    

    address = (input_file[input_file["Email ID"].str.lower() == secret_santa_child.lower()].Address)

    

    msg = os.linesep + msg +  os.linesep  + os.linesep + "Address:" + os.linesep + address.values[0]

    msg = msg + os.linesep +  str(input_file[input_file["Email ID"].str.lower() == secret_santa_child.lower()].Pincode.values[0])

    msg = msg + os.linesep + "Mobile Number:" +  str(input_file[input_file["Email ID"].str.lower() == secret_santa_child.lower()]["Phone number"].values[0])

    msg = msg + os.linesep + os.linesep + "Thanks & Regards,"  + os.linesep + "Santa’s Elves"

    #print(msg)


    


    #email ID of the Secret Santa and Custom Message for Secret Santa 

    input_file.loc[input_file["Email ID"].str.lower() == secret_santa_child.lower(),"secret_santa"] = email

    input_file.loc[input_file["Email ID"].str.lower() == secret_santa_child.lower(),"Message"] = msg


#consolidated list of secret santa and his/her child

#print(ss_keys)

#print(ssc_values)

res = {ss_keys[i]: ssc_values[i] for i in range(len(ss_keys))}


print ('###############################################################')

print("Consolidated list of Secret Santa and his/her Secret Santa Child")

print ('###############################################################')

print(res)



selected_col = ["secret_santa","Message","Name","Email ID","Phone number","Address","Pincode"]

input_file[selected_col].to_excel(output_file_name)


#logic for automated mail  

sender_email_id ='XYZ@gmail.com'

sender_email_id_password = 'Password'


#function for sending automated mail 

def send_mail(sender_email_id,sender_email_id_password,receiver_email_id,message):


    import smtplib 

    

    # creates SMTP session 

    s = smtplib.SMTP('smtp.gmail.com', 587) 

    

    # start TLS for security 

    s.starttls() 

    

    # Authentication 

    s.login(sender_email_id, sender_email_id_password) 

        

    # sending the mail 

    s.sendmail(sender_email_id, receiver_email_id, message) 

    

    # terminating the session 

    s.quit() 

    

for i in range(0,input_file.shape[0]):

    

    receiver_email_id = input_file.iloc[i]["secret_santa"]

    message = input_file.iloc[i]["Message"]

    message = str(message)

    

    #used encode('utf-8') to fix error - "ascii' codec can't encode character '\u2019' in position 135: ordinal not in range(128)"

    send_mail(sender_email_id,sender_email_id_password,receiver_email_id,message.encode('utf-8'))


#RR #Day31 #Python #SecretSantaGame #HappyLearning #WeLearnEveryday



Comments

Popular posts from this blog

Day 32 - Python Script to track Available COVID-19 Vaccine Slots for 18+ in India

DAY 1 - Steps to prepare your windows laptop for Python Programming

Day 26 - Call Power BI REST APIs to get POWER BI REPORT Details