📅  最后修改于: 2023-12-03 14:46:41.319000             🧑  作者: Mango
如果你想向你的朋友、家人和同事发送生日祝福,但又经常忘记他们的生日,那么你需要一个生日提醒应用程序来帮助你。
在Python中,你可以使用datetime模块来处理日期和时间,并使用smtplib模块来发送电子邮件。下面的代码展示了如何编写一个简单的生日提醒应用程序,可以定期检查是否有人即将过生日,并向他们发送祝福邮件。
import datetime
import smtplib
# 生日存储在一个字典中,键是姓名,值是生日日期字符串
birthdays = {
'Alice': '2000-01-01',
'Bob': '1995-05-25',
'Charlie': '1987-12-31'
}
# SMTP服务器信息
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = 'your_username@gmail.com'
smtp_password = 'your_password'
# 发送邮件的函数
def send_email(to, subject, body):
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
message = 'Subject: {}\n\n{}'.format(subject, body)
server.sendmail(smtp_username, to, message)
server.quit()
# 检查生日的函数
def check_birthdays():
today = datetime.date.today()
for name, birthday in birthdays.items():
bday = datetime.datetime.strptime(birthday, '%Y-%m-%d').date()
if bday.month == today.month and bday.day == today.day:
subject = 'Happy Birthday, {}!'.format(name)
body = 'Dear {},\n\nHappy Birthday! Best wishes to you on your special day.\n\nBest regards,\nYour Name'.format(name)
send_email(smtp_username, subject, body)
# 定时检查生日
while True:
check_birthdays()
# 每隔一天检查一次
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
wakeup_time = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 0, 0)
time_to_sleep = (wakeup_time - datetime.datetime.now()).total_seconds()
time.sleep(time_to_sleep)
上述代码示例中,我们使用一个字典来存储生日信息,SMTP服务器来发送电子邮件,以及检查函数来检查是否有人即将过生日。
你可以使用上述代码示例作为模板,自定义你自己的生日提醒应用程序。注意,为了使这个应用程序正常运行,你需要提供SMTP服务器的用户名和密码。