使用python imaplib处理Amazon SES退回通知到电子邮件

时间:2016-03-15 07:56:21

标签: python-2.7 amazon-ses imaplib

我想从Amazon SES发送到我的电子邮件端点的邮件传递通知中检索无效的电子邮件。我不知道如何在imaplib模块中为imap4.search()imap4.fetch()方法提供参数。

请帮助

1 个答案:

答案 0 :(得分:0)

导入imaplib class EmailHandler:

def __init__(self):
    self.imap_address = 'imap.gmail.com'
    self.login_id = 'example@gmail.com'
    self.password = '******'
    self.inbox = 'desired inbox'
    self.addresses = []
    self.M = imaplib.IMAP4_SSL(self.imap_address)

def login(self):
    try:
        self.M.login(self.login_id, self.password)
        self.M.select(self.inbox)
    except imaplib.IMAP4.error:
        print sys.exc_info()

def extract_invalid_ids(self):
    val, data = self.M.search(None, '(OR BODY "bounce" BODY "complaint")')
    if val == 'OK':
        for num in data[0].split():
            val, data = self.M.fetch(num, '(RFC822.TEXT)')
            body = data[0][1]
            body_json_string = body.split('}}')[0] + '}}'
            body_json = json.loads(body_json_string)
            self.addresses.extend(body_json['mail']['destination'])
        print self.addresses
    else:
        print val

参考:http://www.isi.edu/in-notes/rfc3501.txt