電子メールと直接対話する Web アプリケーションを作成するには何が必要かを研究しています。あなたが something@myapp.com に送信するように、アプリはそれをバラバラにして、誰からのものか、DB にあるかどうか、件名は何かなどを判断します。
私はPythonとフラスコを使用しています/最もよく知っています。
私のフラスコアプリコードとやり取りするための電子メールを取得する方法について、誰かが私を正しい方向に導くことができますか?
あなたが取ることができるいくつかのアプローチがあります:
私は最近、単純なブックマーク Web アプリを使って、これらの方針に沿って何かをしました。何かをブックマークする通常のブックマークレットの方法がありますが、iPhone の Reeder などのアプリからリンクを電子メールで送信できるようにしたいとも考えていました。最終的にどうなったかは GitHub で確認できます: subMarks。
私は自分のメールに Google Apps for your Domain を使用しているので、自分のアプリが参照できるように特別なアドレスを作成しました。自分のメール サーバーを構築/構成しようとはまったく考えていませんでした。
上記のmail_daemon.py
ファイルは 5 分ごとに cron ジョブとして実行されます。Python パッケージを使用して電子メール サーバーに接続し、poplib
そこにある電子メールを処理してから切断します (指摘せざるを得ない部分の 1 つは、電子メールが処理される前に自分からのものであることを確認することです:))
次に、My Flask アプリはブックマークのフロント エンドを提供し、データベースからブックマークを表示します。
実際のフラスコ アプリにはメール処理コードを入れないことにしました。これはかなり遅く、ページにアクセスしたときにしか実行されない可能性があるためですが、必要に応じてこれを行うこともできます。
物事を進めるための最低限のコードを次に示します。
import poplib
from email import parser
from email.header import decode_header
import os
import sys
pop_conn = poplib.POP3_SSL('pop.example.com')
pop_conn.user('my-app@example.com')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message into an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
# check message is from a safe recipient
if 'me@example.com' in message['from']:
# Get the message body text
if message['Content-Type'][:4] == 'text':
text = message.get_payload() #plain text messages only have one payload
else:
text = message.get_payload()[0].get_payload() #HTML messages have more payloads
# decode the subject (odd symbols cause it to be encoded sometimes)
subject = decode_header(message['subject'])[0]
if subject[1]:
bookmark_title = subject[0].decode(subject[1]).encode('ascii', 'ignore') # icky
else:
bookmark_title = subject[0]
# in my system, you can use google's address+tag@gmail.com feature to specifiy
# where something goes, a useful feature.
project = message['to'].split('@')[0].split('+')
### Do something here with the message ###
pop_conn.quit()