📜  使用Python自动发送生日邮件

📅  最后修改于: 2022-05-13 01:54:45.917000             🧑  作者: Mango

使用Python自动发送生日邮件

您是否厌倦了向朋友发送生日祝福,或者您忘记向您的朋友发送祝福,或者您想在凌晨 12 点祝福他们,但您总是睡着了?为什么不通过编写Python脚本来自动化这个简单的任务。

我们要做的第一件事是导入六个库:  

  • 熊猫
  • 约会时间
  • smtplib
  • 时间
  • 要求
  • win10吐司

除此之外,还要创建一个 Excel 表来包含这样的记录:姓名电子邮件联系人生日

方法:

  • 对于发送电子邮件部分,我们定义了一个sendEmail()函数,它将启动 Gmail 会话、发送电子邮件并退出会话。
  • 对于 SMS 部分,我们必须在 www.fast2sms.com 上有一个帐户,我们将从那里获得 API 密钥。此 API 密钥用于使用您在 fast2sms 上的帐户通过手机号码发送短信,然后我们创建一个sendms()函数,该函数将验证 API 密钥并发送短信。
  • 在驱动程序代码部分,我们从 Excel 表中读取数据,并将今天的日期与任何生日相匹配。如果匹配,我们调用sendEmail()sendms()函数,并且我们在 Excel 表中添加当前年份。此外,我们还使用了来自win10toast库的ToastNotifier来在成功发送电子邮件和 SMS 后显示桌面通知。

下面是实现:

Python
# 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):
   
    # connection 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 function 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)