免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2707 | 回复: 0
打印 上一主题 下一主题

通过邮件定时发送天气预报给自己 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-27 00:07 |只看该作者 |倒序浏览
  最近天气一直不正常,用python写了个简单的脚本(够丑的)定时给自己发天气邮件(以前写过一个perl的,不知放哪去了).网上也有好些例子可以参考,好些人借助Fetion发天气短信(这个挺好)但由于我现在用联通的号,一时也用不了......
               
               
                #!/usr/bin/env python
# -*- encoding:utf-8 -*-
#-------------------------------------------------------------------------
#FileName:     weather_broadcast.py
#Description:  automatically get the weather information from internet,deal with it and send it out everyday to my sisters,best friends and myself^_^.  Actually, It can be sent out as short messages by the ChinaMobile Fetion which will be useful(Because of some reasons, I use chinaunicom now. I use email everyday,so it's enough for me...)
#Author:       Xiang Guo(gx2008758@gmail.com)
#Time  :       Wed Mar 24 23:44:34 CST 2009
#-------------------------------------------------------------------------
#Now there are still 2 things to be done:
#(1).dealing with the IOError and socket.gaierror
#(2).Write a class to include the all functions
#-------------------------------------------------------------------------
import os, sys, os.path
import datetime
import urllib
import smtplib, email
import hashlib
urlbase = "http://www.weather.com.cn/html/weather/"
cities={'苏州':'101190401','徐州':'101190801','南京':'101190101'}
#remove the old pages,not necessary
def rm_pages(city):
        localfile=city + '.shtml'
    if os.path.isfile(localfile):
       cmd='rm -f ./%s' %localfile
           os.popen(cmd)
#get_weather_message      
def get_message(city):
    url=urlbase + cities[city] + '.shtml'
    localfile=city+'.shtml'
    #have to be modified,consider the loop!!!
      #(2).socket or IO error
     #socket.gaierror: (-2, 'Name or service not known')
     #IOError: [Errno socket error] (-2, 'Name or service not known')
    try:
      urllib.urlretrieve(url,localfile)
    except IOError:
      urllib.urlretrieve(url,localfile)
   
    cmd="sed -i -e '1,/c_1_1/d; /c_1_2/,/dd_0/d; /surf/,$d; /紫外线/,/舒适指数/d' %s" %(localfile)
           os.popen(cmd)
           cmd="sed -i -e 's/[^>]*>//g;/ &nbsp/d' %s" % (localfile)
           os.popen(cmd)
           cmd="sed -i -e 's/^\s*//g;/^$/d' %s" % (localfile)
           os.popen(cmd)
           cmd="sed -i -e 's/\/ / -/g;s/星期.*//g;s/高温://g;s/低温://g' %s" %(localfile)
           os.popen(cmd)
    message=city+'未来三天的天气:\n'
    tomorrow='%s日:  ' %(int(datetime.date.today().day)+1)
    f=open(localfile)
    message+=tomorrow+f.readline().replace('\r\n', ',')+f.readline().replace('\r\n', ' ,')+f.readline()
   
    message+=f.readline().replace('\n', ':  ')+f.readline().replace('\r\n', ',')
    htemp=f.readline().replace('\r\n', ' ,')
    ltemp=f.readline().replace('\r\n', '')
    message+=ltemp + ' -'+ htemp
    message+=f.readline()
   
    message+=f.readline().replace('\n', ':  ')+f.readline().replace('\r\n', ',')
    htemp=f.readline().replace('\r\n', ' ,')
    ltemp=f.readline().replace('\r\n', '')
    message+=ltemp + ' -'+ htemp
    message+=f.readline()
    #don't forget to close the opened
    f.close()
    print message
    return message
def send_mail(send_from, send_to, subject, text,auth=(), send_server='localhost'):
    msg = email.MIMEMultipart.MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = email.Utils.COMMASPACE.join(send_to)
    msg['Date'] = email.Utils.formatdate(localtime=True)
    #utf8 encoding to avoid irrecognizable characters to mailclient with gbk encoding(such as sina,sohu etc)
    #msg['Subject'] = subject
    msg['Subject'] = email.Header.Header(subject,'utf-8')
    msg.attach(email.MIMEText.MIMEText(text,_subtype='plain',_charset='utf-8'))
    #you can added one attachment use below lines
    #part = email.MIMEBase.MIMEBase('application', 'octet-stream')
    #part.set_payload( attachment_bytes )
    #email.Encoders.encode_base64(part)
    #part.add_header('Content-Disposition', 'attachment; filename=%s' % subject)
    #msg.attach(part)
    smtp = smtplib.SMTP(send_server)
    #the two lines below are neccessary to
    smtp.docmd("EHLO server" )   
    smtp.starttls()              
    smtp.login(*auth)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
if __name__=="__main__" :
  weather_msg=''
  for city in cities.keys():
      #rm_pages(city)
      weather_msg+=get_message(city)
  send_mail(
        'gx2008758@gmail.com',
           ['bestfrineds@gmail.com','sisters@sina.com','gx2008758@gmail.com'],
        "^_^天气预报^_^",
    weather_msg,
        ('gx2008758@gmail.com', 'uguessit'),
        'smtp.gmail.com' )
  print 'Done.'


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/65354/showart_1881075.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP