最近在CSDN上发现许多使用Python自动发送邮件追女神的整活博客,于是想顺手做一个每天定时发送邮件给朋友的程序,内容包括舔狗日记、每天的天气变化、及人文问候。
import requests
from lxml import etree
import yagmail
# 调用舔狗日记的api 获取内容
def tiangouApi():
url = "https://api.dzzui.com/api/tiangou"
result = requests.get(url).text
lis = result.split('<br>')
return lis[1]
# 登录邮箱,设置登录的账号,密码和port等信息
def send_email(contents, send_to):
yag = yagmail.SMTP(user='你的邮箱',
password='你的授权码',
host='发信服务器,如使用QQ邮箱的为smtp.qq.com')
# 设置发送给谁,邮件主题,邮件内容
yag.send(to=send_to,
subject='每日一邮',
contents=contents)
print('发送成功!')
yag.close()
def parse(url):
text = tiangouApi()
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
html = requests.get(url, headers=headers)
bs = etree.HTML(html.text)
# 今天天气相关数据:日期,星期几,天气,最低气温,最高气温
today_date = bs.xpath('//ul[@class = "week"]/li[1]/b/text()')[0]
today_week = bs.xpath('//ul[@class = "week"]/li[1]/span/text()')[0]
today_weather = bs.xpath('//ul[@class = "txt txt2"]/li[1]/text()')[0]
today_low = bs.xpath('//div[@class = "zxt_shuju"]/ul/li[1]/b/text()')[0]
today_high = bs.xpath(
'//div[@class = "zxt_shuju"]/ul/li[1]/span/text()')[0]
print(('今天是%s,%s,%s,%s~~%s度') %
(today_date, today_week, today_weather, today_low, today_high))
# 明天天气相关数据,维度和上述一致
tomorrow_date = bs.xpath('//ul[@class = "week"]/li[2]/b/text()')[0]
tomorrow_week = bs.xpath('//ul[@class = "week"]/li[2]/span/text()')[0]
tomorrow_weather = bs.xpath('//ul[@class = "txt txt2"]/li[2]/text()')[0]
tomorrow_low = bs.xpath('//div[@class = "zxt_shuju"]/ul/li[2]/b/text()')[0]
tomorrow_high = bs.xpath(
'//div[@class = "zxt_shuju"]/ul/li[2]/span/text()')[0]
tomorrow = ('明天是%s,%s,%s,温度范围%s~%s度,温差%d度。') % \
(tomorrow_date, tomorrow_week, tomorrow_weather, tomorrow_low,
tomorrow_high, int(int(tomorrow_high)-int(tomorrow_low)))
# 计算今明两天温度差异,这里用的是最高温度
temperature_distance = int(tomorrow_high) - int(today_high)
if temperature_distance > 0:
a = '明日升温%d,记得配好美美的穿搭哦,小可爱。' % temperature_distance
elif temperature_distance < 0:
a = '明日降温%d,记得自己添衣服,我不在的日子记得照顾好自己。' % temperature_distance
else:
a = '最高气温不变,在每一个平凡的日子里,也要记得翩翩起舞哦!'
content = str(tomorrow) + str(a)
content = text + '<br>' + content
return content
# 发送给一人
url = "收件人所在地区天气网站" # 代码使用的是天气网的信息 如青岛 为 https://www.tianqi.com/qingdao/
contents = parse(url)
send_to = '收件人邮箱地址'
send_email(contents, send_to)
'''
# 当然 如果你想要的给一群人发送 可使用如下代码 在emails中添加对应邮箱地址即可
emails = ['123@qq.com', '456@qq.com', '', '']
for email in emails:
send_email(contents, email)
'''