import smtplib from email import message_from_string def initialize(): _smtp_conn = None try: _smtp_conn = _connect_to_server() except Exception as e: print(e) print("SMTP Connection established successfully") print(_send_rawemail(_smtp_conn)) def _connect_to_server(): _smtp_conn = None server = "smtp.gmail.com" # default the ssl config to non SSL i.e. either None or StartTLS func_to_use = getattr(smtplib, 'SMTP') # Get the SSL config to use ssl_config = "StartTLS" port = "587" _smtp_conn = func_to_use(server, port) _smtp_conn.ehlo() # Use the StartTLS command if the config was set to StartTLS if (_smtp_conn.has_extn('STARTTLS') and (ssl_config == "StartTLS")): _smtp_conn.starttls() _smtp_conn.ehlo() # Provide 'username' and 'password' for a valid email address # which is configured as per the SMTP protocol # For security reasons, I have not provided the valid credentials. password = "password" username = "user@domain.com" if password and username: if _smtp_conn.has_extn('AUTH'): _smtp_conn.login(username, password) return _smtp_conn def _send_rawemail(_smtp_conn): raw_email = """To: testmail@gmail.com From:user@domain.com Subject:body with Unicodes This is email body with Unicodes漢字. """ msg = message_from_string(raw_email) email_from = msg.get('from', '') if not len(email_from): return "Failed to send the email. Sender not found" # In case the user provides 'CC' or 'BCC' but does not provide 'To' if not len(msg['to']): return "Failed to send the email. Receiver not found" email_to = [x.strip() for x in msg['to'].split(",")] if msg['cc']: email_to.extend([x.strip() for x in msg['cc'].split(",")]) if msg['bcc']: email_to.extend([x.strip() for x in msg['bcc'].split(",")]) email_to = list(filter(None, email_to)) try: _smtp_conn.sendmail(email_from, email_to, msg.as_string()) except Exception as e: print("An exception occurred.") return "{0} {1}".format(type(e).__name__, str(e)) return "Message sent successfully." if __name__ == "__main__": initialize()