import json
from datetime import datetime
from urllib.request import urlopen
from urllib import request
import smtplib
from email.mime.text import MIMEText
# 将读取网站内容的步骤封装成函数;
def readUrl(url):
# 生成字典, 指定用户代理为火狐浏览器, 而不是python脚本;
headers = {'User-Agent': 'Firefox/23.0'}
# 向url地址发起请求, 返回一个Request对象;
req = request.Request(url, headers=headers)
# 返回一个urlOpen对象, 该对象中包含访问的所有结果, 比如: 网页内容, 网页的状态码(200, 404)
urlObj = urlopen(req)
# 将读取的内容以utf-8编码显示;(中文显示不乱码)
urlContent = urlObj.read().decode('utf-8')
# print(urlContent)
return urlContent
smtpServer = 'smtp.163.com'
sender = 'asimov_w@163.com'
passwd = '*****'
# receiver = ['','', '' ]
# receiver = ''
receiver = '1019022410@qq.com'
subject = '主题没有'
sj=datetime.now()
content=" %s 有雨或雪请注意" %(sj)
# with open("interview.templates") as f: # 发文件
# content=f.read()
def mail_content():
# 是一个MIMETEXT对象, 如果发送的是普通的文本文件, 则添加
msg = MIMEText(content, 'html', 'utf-8')
msg['From'] = sender
############## 如果要给多个用户发送邮件, 需要将列表连接成字符串;######################
msg['To'] = "".join(receiver)
msg['Subject'] = subject
return msg
def sendMail():
try:
# 1. 连接smtp服务器;
smtpObj = smtplib.SMTP(smtpServer)
# 2. 登陆账户
smtpObj.login(sender, passwd)
# 生成合法格式的内容, 否则发送失败;
msg = mail_content()
# 3. 发送邮件
smtpObj.sendmail(sender, receiver, msg.as_string())
except smtplib.SMTPException as e:
print("Error:邮件发送失败,", e)
else:
print("邮件发送%s成功" % (receiver))
def main():
url = "http://www.weather.com.cn/data/cityinfo/101110101.html"
info = readUrl(url)
# print(info)
d = json.loads(info) # 将json格式的子符串解码为python可以识别的数据类型;
weather = d['weatherinfo']['weather']
if '雨' in weather or '雪' in weather:
sendMail()
main()
邮箱自动提醒天气
最新推荐文章于 2023-12-06 14:46:48 发布