Chinaunix首页 | 论坛 | 博客
  • 博客访问: 661517
  • 博文数量: 139
  • 博客积分: 2655
  • 博客等级: 少校
  • 技术积分: 1723
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-02 16:03
文章分类

全部博文(139)

文章存档

2013年(2)

2011年(17)

2010年(14)

2009年(86)

2008年(20)

分类: Python/Ruby

2009-03-27 00:07:01

  最近天气一直不正常,用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 = ""
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;&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.'

阅读(6460) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~