最近、古いネットブックをUSBブートのLinuxで使用しています。ネットブック上で作成したファイルをEvernoteへアップロードしたいと思うことがあるのですが、ブラウザから操作するのは厳しいと感じています。
Pythonからメールでファイルを送るようにすればいいのではないかと思い、標準入力から読み込んだ内容をEvernoteへ送るプログラムを書きました。
プログラム
# -*- coding: utf-8 -*-
# ever_mail.py
# ---- CONFIGURATIONS ----
EVERNOTE_MAIL_ADDRESS = 'evernote_mail_address'
FROM_ADDRESS = 'from_address'
SMTP_HOST = 'smtp._host'
SMTP_PORT = 25
DEBUG = True
# ---- CONFIGURATIONS ----
import datetime
import email.header
import optparse
import smtplib
import sys
from email.mime.text import MIMEText
class EverMailClient(object):
def __init__(self, smtp):
assert isinstance(smtp, smtplib.SMTP)
self._smtp = smtp
def send(self, msg):
assert isinstance(msg, MIMEText)
mail_from = msg['From']
mail_to = msg['To']
self._smtp.sendmail(mail_from, mail_to, msg.as_string())
class EverMailTitle(object):
def __init__(self, title, notebook, tags):
self._title = title if title else str(datetime.datetime.now)
self._notebook = notebook if notebook else ''
self._tags = tags if tags else []
def __str__(self):
result = self._title
if 0 < len(self._notebook):
result += ' @' + self._notebook
for tag in self._tags:
result += ' #' + tag
return result
class EverMailOptionParser(optparse.OptionParser):
def __init__(self):
optparse.OptionParser.__init__(self)
self.add_option('--notebook', '-n', action='store')
self.add_option('--tag', '-t', action='append')
def create_smtp_client():
smtp = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
if DEBUG:
smtp.set_debuglevel(1)
return smtp
def create_message_from_stdin(title):
assert isinstance(title, EverMailTitle)
body = sys.stdin.read()
msg = MIMEText(bytes(body))
msg['Subject'] = email.header.Header(str(title), 'utf-8')
msg['From'] = FROM_ADDRESS
msg['To'] = EVERNOTE_MAIL_ADDRESS
msg.set_charset('utf-8')
return msg
if __name__ == '__main__':
option_parser = EverMailOptionParser()
(options, args) = option_parser.parse_args()
note_title = args[0] if args and 0 < len(args) else ''
title = EverMailTitle(note_title,
options.notebook,
options.tag)
msg = create_message_from_stdin(title)
smtp = None
try:
smtp = create_smtp_client()
client = EverMailClient(smtp)
client.send(msg)
finally:
if smtp: smtp.close()
使用例
$ cat your_important_file | python ever_mail.py TITLE -nNOTEBOOK -tTAG -tTAG
工夫したところは、optparseモジュールを使ってオプションの解析を実装したところです。
暇があれば、画像の添付なども対応したいと思います。
参考
15.5. optparse — コマンドラインオプション解析器
Eメールを送信するだけでEvernoteに簡単送信!
0 件のコメント:
コメントを投稿