I am new to python and wrote a email redirect script. It extracts mails from a server and than resend them. I would like to get some feedback:
import sys
import smtplib
import poplib
import re
import argparse
def validate_email_address(address):
email_pattern = '^[^@]+@[^@]+\.[^@]+$'
if not re.match(email_pattern, address ):
raise argparse.ArgumentTypeError('{} is not a valid email address'.format(address))
return address
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('popServer', help='pop server host or address of extracted account')
arg_parser.add_argument('smtpServer', help='smtp server host or address of extracted account')
arg_parser.add_argument('address', help='extract messages from this account', type=validate_email_address)
arg_parser.add_argument('password', help='password of extracted account')
arg_parser.add_argument('target', help='redirect messages to this account', type=validate_email_address)
arg_parser.add_argument('-useTSL', action='store_true')
arg_parser.add_argument('-useSSL', action='store_true')
args = arg_parser.parse_args()
timeout = 10
try:
if args.useSSL: pop_conn = poplib.POP3_SSL(args.popServer, timeout=timeout)
else: pop_conn = poplib.POP3(args.popServer, timeout=timeout)
pop_conn.user(args.address)
pop_conn.pass_(args.password)
mail_count = len(pop_conn.list()[1])
print('Mail count:{}'.format(mail_count))
if mail_count > 0:
print('Requesting mails from {0} for {1}'.format(args.popServer, args.address))
for i in range(1, mail_count + 1):
try:
print("Receiving mail {0}/{1}".format(i,mail_count))
message = (pop_conn.retr(i)[1])
pop_conn.dele(i)
message = [line.decode('utf-8', errors='ignore') for line in message]
message = '\n'.join(message)
print("Redirecting mail {0}/{1}".format(i,mail_count))
if(args.useSSL): smtp_conn = smtplib.SMTP_SSL(args.smtpServer, timeout=timeout)
else: smtp_conn = smtplib.SMTP(args.smtpServer, timeout=timeout)
if(args.useTSL): smtp_conn.starttls()
smtp_conn.login(args.address, args.password)
smtp_conn.sendmail(args.address, args.target, message.encode(encoding='ascii', errors='ignore'))
smtp_conn.quit()
except smtplib.SMTPException as SMTP_exception:
print('Request of mail failed:{0}'.format(SMTP_exception))
pass
except poplib.error_proto as pop_error:
print('Receiving of mail failed:{0}'.format(pop_error))
pass
except poplib.error_proto as pop_error:
print('Receiving of mail failed:{0}'.format(pop_error))
except OSError as os_error:
print('Name resolution or server connection failed:{}'.format(os_error))