やりたい事4:電力レポートをメール送信する

収集した電力量をWebページで確認できるようにしましたが、GAEに登録したDBに対してのアクセス量には無料で利用できる制限値があり、「大量のデータを自由にダウンロード出来ない」という制限があります(課金すれば制限を超えることはできますが、、、)

ということで、少しづつでもローカルPCにデータを保存しておきたいと思い、「前日分の計測結果をメールで送信」することにしました。

メール送信機能は、Webサーバー側に実装するのですが、以下のソースコードで実現することが出来ます

ソース

#==============================================================
def send_email():
    try:
       #=================================
       # 昨日の時間範囲
       #=================================
       post_datetime = datetime.datetime.now()
       post_datetime = post_datetime + timedelta(hours=9)
       post_datetime_s = datetime.datetime(post_datetime.year, post_datetime.month, post_datetime.day,0,0,0,0)
       post_datetime_s = post_datetime_s - timedelta(hours=24)
       post_datetime_e = post_datetime_s + timedelta(hours=24)
       post_datetime_s = post_datetime_s - timedelta(hours=9)
       post_datetime_e = post_datetime_e - timedelta(hours=9)
       sql = ("SELECT * FROM ListHour WHERE date_time >= DATETIME('%s') AND date_time < DATETIME('%s') ORDER BY date_time ASC" % (post_datetime_s, post_datetime_e))
       power_consumption = db.GqlQuery(sql)
       power_consumption = power_consumption.fetch(60)
       
       out_power = []
       gen_watt_total = 0
       use_watt_total = 0
       txt = ""
       for fav in power_consumption:
           gen_watt = fav.watt_value1
           use_watt = fav.watt_value1 + fav.watt_value2
           
           gen_watt_total = gen_watt_total + gen_watt
           use_watt_total = use_watt_total + use_watt
           txt = txt + (fav.date_time + timedelta(hours=9)).strftime("%Y/%m/%d %H:%M") + ',' + str(gen_watt / fav.write_cnt) + ',' + str(use_watt / fav.write_cnt) + '\r\n'
       
       gen_watt_total = float(gen_watt_total) / (30.0 * 1000.0)
       use_watt_total = float(use_watt_total) / (30.0 * 1000.0)
       
       sender_address = "メールアドレス"
       subject = u"電力計測結果" + post_datetime_s.strftime(" %Y/%m/%d")
       body = u'昨日の電力量の結果を送信します。\n\n'
       body += u'総発電電力:' + str.format('{0:03.2f}', gen_watt_total) + u'kWh\n'
       body += u'総使用電力:' + str.format('{0:03.2f}', use_watt_total) + u'kWh\n'
       mail.send_mail(sender=sender_address,
                  to=sender_address,
                  subject=subject,
                  body=body,
                  attachments=[post_datetime_s.strftime("watt_%Y_%m_%d") + '.txt', txt])
    except:
       logging.error("send mail error")
       logging.error(traceback.format_exc())

以下のメールアドレスの所は、送信したいメールアドレスに書き換えます

sender_address = "メールアドレス"

これで、以下のようなメールが届きます

本文や、添付ファイルの内容は、もうちょっと見直ししたほうが良さそうですが、ひとまずメール通知は実装完了です