运行 python 接收电子邮件时的脚本
Run python script at reception of email
我拥有一个可以 运行 anacrontab 的共享主机。当我在该服务器上收到一封电子邮件时,我想 运行 一个 python 脚本。
anacrontab 够吗?
或者使用 Gmail 之类的客户端会更好吗?
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 table 中创建一个新条目邮件内容等.. 或者 运行 另一个脚本如果干净 is not None
等
我拥有一个可以 运行 anacrontab 的共享主机。当我在该服务器上收到一封电子邮件时,我想 运行 一个 python 脚本。 anacrontab 够吗? 或者使用 Gmail 之类的客户端会更好吗?
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 table 中创建一个新条目邮件内容等.. 或者 运行 另一个脚本如果干净 is not None
等