前言
最近在CSDN上发现许多使用Python自动发送邮件追女神的整活博客,于是想顺手做一个每天定时发送邮件给朋友的程序,内容包括舔狗日记、每天的天气变化、及人文问候。
注意
-
测试环境: win10 python3.6
-
第三方库 requests、yagmail、lxml
-
使用yagmail需要开通个人发送邮箱的SMTP服务,以QQ邮箱为例:
-
如果xdm需要发送给多人(懂的都懂),可以使用代码最后的注释块,当然天气的内容仅适用于同地区的人,异地你舔不到……
-
可以添加更多的内容,如土味情话等;也可以打包为.exe,在服务器上每天定时运行。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import requests from lxml import etree import yagmail
def tiangouApi(): url = "https://api.dzzui.com/api/tiangou" result = requests.get(url).text lis = result.split('<br>') return lis[1]
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 = "收件人所在地区天气网站" 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)
'''
|
效果