Reputation: 93
I own a shared hosting which can run anacrontab. I would like to run a python script when I receive an email on that server. Is anacrontab enough? Or would using a client such as Gmail be better?
Upvotes: 0
Views: 6317
Reputation: 870
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 config:
HOME=/var/www/html/whatever
* * * * * root /var/www/html/whatever/myMailChecker.py
Conclusion:
This will call your imap servers' Inbox every minute and parse trough your mail and parse it's content, you can do whatever you want after like create a new entry in your mysql table with the mail content etc.. or run another script if clean is not None
etc.
Upvotes: 1