邮箱自动提醒天气

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()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值