SoFunction
Updated on 2024-11-15

Tutorial on logging into Gmail and sending Gmail emails with Python

This quick article describes using Gmail as your e-mail server to send e-mail via Python's built-in SMTP library. It's not complicated, I promise.

Here's how to log into GMail in Python:
 

import smtplib
 
# The below code never changes, though obviously those variables need values.
session = ('', 587)
()
()
(GMAIL_USERNAME, GMAIL_PASSWORD)

Here's how to send an email in Python:
 

headers = "\r\n".join(["from: " + GMAIL_USERNAME,
            "subject: " + email_subject
            "to: " + recipient,
            "mime-version: 1.0",
            "content-type: text/html"])
 
# body_of_email can be plaintext or html!          
content = headers + "\r\n\r\n" + body_of_email
(GMAIL_USERNAME, recipient, content)

Depending on your mastery of Python, this could be a fairly small or fairly long piece of code.


For me, the first time I took a program to send an email was like the moment I saw the scene inside the Matrix, like the first time I set up a website on Godaddy, or like the first time I was puzzled with JOptionPane. Here's an implementation (a simple one that makes implementing a similar application very easy), and while I've seen a lot of code for sending emails before, this still impressed me.


Also, despite the simplicity of the code above, I gave it my best shot the first time around and it took me over two hours to write that code. So I hope that helps some others.