#!/usr/local/bin python
"""
This script is used to forward email
"""
import os, sys, poplib, getopt, getpass, email, smtplib
from_email = '???'
to_email = '???'
pop3_server_url = '???'
pop3_server_port = 110
pop3_user = '???'
pop3_pass = '???'
delete_after = True
subject_filter = '????'
def match_filter(subject, sfilter):
return subject.find(sfilter) == 0
def forward_mail(femail, temail, mail):
for (header, value) in mail.items():
if not header in ('Content-Type', 'Content-Transfer-Encoding', 'Subject', 'Mime-Version'):
del mail[header]
mail["From"] = femail
mail["To"] = temail
for (header, value) in mail.items():
print "%s: %s" % (header, value)
server = smtplib.SMTP('localhost')
server.set_debuglevel(0)
server.sendmail(femail, temail, mail.as_string())
server.quit()
def process_mail(pop3_mail):
mail = email.message_from_string(pop3_mail)
subject = mail.get("Subject")
if match_filter(subject, subject_filter):
print "Forward email: %s" % (subject)
forward_mail(from_email, to_email, mail)
return True
else:
print "Skip email: %s" % (subject)
return False
if __name__ == '__main__':
def usage():
print "Usag:"
print "python forward_mail.py -s <pop3_server> -p <pop3_port> -u <user> -c <credential> -f <from_email> -t <to_email>"
try:
opts, args = getopt.getopt(sys.argv[1:], "s:p:u:c:f:t:")
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-s"):
pop3_server_url = arg
elif opt in ("-p"):
pop3_server_port = int(arg)
elif opt in ("-u"):
pop3_user = arg
elif opt in ("-c"):
pop3_pass = arg
elif opt in ("-f"):
from_email = arg
elif opt in ("-t"):
to_email = arg
if pop3_user is None:
pop3_user = getpass.getUser()
if pop3_pass is None:
pop3_pass = getpass.getpass()
pop3 = poplib.POP3(pop3_server_url, pop3_server_port)
pop3.user(pop3_user)
pop3.pass_(pop3_pass)
msg_count = len(pop3.list()[1])
print "Total messages in Inbox: %d" % (msg_count)
for i in range(msg_count):
resp, text, octets = pop3.retr(i+1)
if process_mail('\n'.join(text)) and delete_after:
print "Forwarded email is deleted"
pop3.dele(i+1)
pop3.quit()
2008-02-05
Email forwarding script
Subscribe to:
Posts (Atom)