Python Program Introduction Site

Gmail >> CSV

2021.04.04

5 comments

今回の設定にはConfigParserを使います。
ConfigParserをWindowsで使う場合に面倒なのが
CP932のデコードエラーです。
これを回避するためにリードの部分でUTF-8を用いています。

いつものことですが、インポートは簡単に行っていると思われていますが
これには、インストールをpip、conda、easy_installや、その他の周りくどい方法で行っています。
Windowsを諦めて、他の方法でやることを強制されているようで反発したくなります。

この結果を後程、解析し出現頻度の高い単語のランク付けをしたいと考えています。

あと、他の送信元も含めて単語のベクトル化を行い
その傾向を探りたいと考えています(マインドマップの図のようなイメージです)

GmailをPythonで操作するには
Googleの開発者コンソールにログインしてGmail APIを有効にする必要があります。

設定ファイル(config.ini)
[defalt]
user = your name
[option]
password : your gmail password
mail : your gmail address

コード(gmail_serach_save.py)

import imapclient
import ssl
import configparser
import pprint
import pyzmail
import csv

config = configparser.ConfigParser()
config.read(“./config.ini”,  “UTF-8″)
password = config[‘option’][‘password’]
gmail_address = config[‘option’][‘mail’]
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
imapobj = imapclient.IMAPClient(‘imap.gmail.com’, ssl=True, ssl_context=context)imapobj.login(gmail_address, password)
imapobj.select_folder(‘INBOX’)

UIDs = []
UIDs = imapobj.gmail_search(‘翔泳社’)

raw_messages = imapobj.fetch(UIDs, [‘BODY[]’])
pprint.pprint(raw_messages)
f = open(‘gmailtext.csv’,’w’, newline=”)
spamwriter = csv.writer(f)

for UID in UIDs:
message = pyzmail.PyzMessage.factory(raw_messages[UID][b’BODY[]’])
text = message.get_subject()
From = message.get_addresses(‘from’)
To = message.get_addresses(‘to’)
spamwriter.writerow([From,text,To])
f.close()
imapobj.logout()

関連記事

コメント

  1. この記事へのコメントはありません。

  1. この記事へのトラックバックはありません。

python3X