LoginSignup
8
9

More than 5 years have passed since last update.

Gmailの件名をtwitterに投稿

Last updated at Posted at 2013-09-11

はい、仕事中にメールは外部に・自由な宛先に送ってもセフセフだけどtwitterアクセスは出来ない、という環境を想定しております。
メールはtweet後に自動で削除されます。連動している証拠隠滅と重複して投稿しようとすることを防止する目的です。
はい、自宅なりレンタルなりで何処かに設置して定期的に動作させる必要があります。
http://symfoware.blog68.fc2.com/blog-entry-891.html
Gmailの件名取得につきましては全面的にお世話になっております。というかコピペです。件名取得以外の要素をなるべく削り、投稿機能を付け足してメールを削除させるようにしただけです。全面的にお世話になりました。

gmail_twitter.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import imaplib, email, email.Header
import sys
from urllib import urlencode

#私が独自にOauth認証のトークン入れているものです。
#別にしておかないと事故で公開が怖いのです。
import oat
"""
Gmail取得については全面的に
http://symfoware.blog68.fc2.com/blog-entry-891.html
より頂いております。
"""
class imap4mail(object):


    def __init__(self, data):
        """
        コンストラクタで与えられたメールデータの解析を実行する
        """
        self.files = {}

        #メッセージをパース
        msg = email.message_from_string(data)
        #タイトル取得
        self.title = self.decode(msg.get('Subject'))


    def decode(self, dec_target):

        """
        メールタイトル、送信者のデコード
        """
        decodefrag = email.Header.decode_header(dec_target)
        title = ''

        for frag, enc in decodefrag:
            if enc:
                title += unicode(frag, enc)
            else:
                title += unicode(frag)
        return title


def analize_mail(mail):

    #取得したメールの件名を投稿
    oat.client.request('https://api.twitter.com/1.1/statuses/update.json', 'POST', urlencode({'status': mail.title.encode('utf-8')}))

if __name__ == "__main__":

    host = 'imap.gmail.com'
    user = 'example@gmail.com'
    password = 'password'
    mailbox = 'INBOX'

    #メールサーバ指定
    M = imaplib.IMAP4_SSL(host=host)
    #ログイン
    M.login(user, password)

    #メールボックス選択
    M.select(mailbox)

    typ, data = M.search(None, 'ALL')
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
        mail = imap4mail(data[0][1])
# twitterに投稿
        analize_mail(mail)
# 投稿後はメールを削除
        M.store(num, '+FLAGS', '\\Deleted')
    M.expunge()
    M.close()
    M.logout()

はい、コメントなども殆どそのままコピーです。私なんかがコメント変えたらアレですし。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9