server.starttls() server.login(sender_email, password) except smtplib.SMTPConnectError as err: print "Unable to connect to SMTP server." server.quit() exit(2) except smtplib.SMTPAuthenticationError as err: print "Login attempt failed. Incorrect username/password or " \ "the account does not allow less secure apps to login." server.quit() exit(3) if server is not None: try: for address in to_list: address = str(address).strip() if is_valid_email(address): msg.__delitem__('To') msg['To'] = address text = msg.as_string() print "Sending mail to: " + address try: server.sendmail(sender_email, address, text) except Exception: print "Exception while sending mail." else: print address + " is not a valid email. Skipping." finally: server.quit()