在接收电子邮件时运行python脚本

时间:2017-01-09 08:01:14

标签: python crontab shared-hosting

我拥有一个可以运行anacrontab的共享主机。当我在该服务器上收到电子邮件时,我想运行python脚本。 anacrontab足够吗? 或者使用Gmail之类的客户端会更好?

1 个答案:

答案 0 :(得分:0)

import imapclient, pyzmail, html2text

def latestMail():
    imapObj = imapclient.IMAPClient('imap.yourServer.com', ssl=False)
    imapObj.login('imapUser', 'imapPass')
    imapObj.select_folder('Inbox', readonly=False)
    UIDs = imapObj.search(criteria='ALL', charset=None)
    rawMessages = imapObj.fetch(UIDs[0], ['BODY[]', 'FLAGS'])
    message = pyzmail.PyzMessage.factory(rawMessages[UIDs[0]]['BODY[]'])
    return message

def parser(message):
    if message.text_part is not None and message.html_part is not None:
        multipart = True
    else:
        multipart = False

    if message.text_part is not None:
        try:
            body = message.text_part.get_payload().decode(message.text_part.charset)
        except TypeError:
            body = message.text_part.get_payload()

    if message.html_part is not None and multipart is False:
        try:
            body = html2text.html2text(message.html_part.get_payload().decode(message.html_part.charset))
        except Exception:
            raise Systemexit
    return body


try:
    message = latestMail()
    clean = parser(message)
    print clean
except IndexError:
    print "No messages left"
    raise os._exit(0)
except Exception as e:
    print e

Crontab配置:

HOME=/var/www/html/whatever
* * * * * root /var/www/html/whatever/myMailChecker.py

结论:

这将每分钟调用你的imap服务器的收件箱并解析你的邮件并解析它的内容,你可以做任何你想做的事情,比如在你的mysql表中用邮件内容等创建一个新条目..或者运行另一个脚本如果干净is not None