2015/11/02

[Python][Google App Engine]メール受信 その4

メール受信 その1では、メール受信を行うまでの過程を
メール受信 その2では、受信したメールの情報を取得する方法を書きました。
メール受信 その3では、受信したメールのcontent typeの情報を取得する方法を書きました。
で、そこで何回かメール受信を試してみて、メールのタイトルがない場合

subject = mail_message.subject
このスニペットがある場合、エラーになってしまうので、エラーハンドリングについて書く。
import webapp2
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
 
class HogeHandler(InboundMailHandler):
  def receive(self, mail_message):
    original = mail_message.original
    content_type = original.get_content_type()
    sender = mail_message.sender
    try:
      subject = mail_message.subject
    except AttributeError:
      subject = ""
    plaintext_bodies = mail_message.bodies('text/plain')
    html_bodies = mail_message.bodies('text/html')
    for content_type, body in html_bodies:
       decoded_html = body.decode()

       
エラーの内容がAttributeErrorなので上のようなtry~exceptにしました。

0 コメント:

コメントを投稿