Send an email via Gmail using Python
Sending an email programmatically from a Gmail account is easy using Python and the smtplib library. The following snippet shows a function written in Python that sends an email with a chosen subject and a body as plain text.
Line 7 through 16 creates the email message. Since the from_address will be used as the Gmail username, the from_address and password need to be valid Gmail credentials. The to_address, subject and mail body is given to the function as parameters.
Line 17 gets the SMTP connection and ehlo() identifies us to the ESMTP server using EHLO (Extended HELLO). starttls() puts the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted.
Line 20 through 22 logs us in, sends the email and finally terminates the SMTP session.