Logo

dev-resources.site

for different kinds of informations.

How to Send Emails in Python Using Gmail’s Free SMTP Mail Server API

Published at
11/11/2024
Categories
python
api
gmail
server
Author
thetanweerali
Categories
4 categories in total
python
open
api
open
gmail
open
server
open
Author
13 person written this
thetanweerali
open
How to Send Emails in Python Using Gmail’s Free SMTP Mail Server API

This is the easiest way you can start sending emails with Python using only two libraries, smtplib and email.

We will be using Gmail’s free RESTful API in this example.

Here's the code

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

message = MIMEMultipart()
message["To"] = 'To line here.'
message["From"] = 'From line here.'
message["Subject"] = 'Subject line here.'

title = '<b> Title line here. </b>'
messageText = MIMEText('''Message body goes here.''','html')
message.attach(messageText)

email = 'Your Gmail address here.'
password = 'Your app password here.'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo('Gmail')
server.starttls()
server.login(email,password)
fromaddr = 'From line here.'
toaddrs  = 'Address you send to.'
server.sendmail(fromaddr,toaddrs,message.as_string())

server.quit()
Enter fullscreen mode Exit fullscreen mode

How the code works ?

First, let’s import smtplib then MIMEMultipart and MIMEText from email.mime.multipart and email.mime.text respectively:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Enter fullscreen mode Exit fullscreen mode

We then call MIMEMultiPart() and instantiate it to the variable Message. We then give a string value to each variable which are Message, To, From and Subject, it should look like this:

Message = MIMEMultipart()
Message["To"] = 'To line here.'
Message["From"] = 'From line here.'
Message["Subject"] = 'Subject line here.'
Enter fullscreen mode Exit fullscreen mode

We'll also give a title to our email through the title variable and add a message through MIMEText() and instantiate it to the variable messageText and finally attach our email message to our main variable Message using the attach() function, it should look like this:

title = '<b> Title line here. </b>'
messageText = MIMEText('''Message body goes here.''','html')
Message.attach(messageText)
Enter fullscreen mode Exit fullscreen mode

Let’s add our Gmail address and our App password, click the link here if you don’t know how to get one:

email = 'Your Gmail address here.'
password = 'Your App password here.'
Enter fullscreen mode Exit fullscreen mode

Then we'll have to connect to Gmail's SMTP server, we'll do that using the smtplib library and we'll need two variables which are the server we want to connect to and the port which are smtp.gmail.com and 587 respectively.

Using the smtplib library we'll be calling the SMTP function and add the server and port variables as its arguments, it should look like this:

smtplib.SMTP('smtp.gmail.com:587') (don't forget the : between them)

We'll then instantiate it to the variable server:

server = smtplib.SMTP('smtp.gmail.com:587')
Enter fullscreen mode Exit fullscreen mode

We then add an ehlo statement using server.ehlo(‘Gmail’), this should be your domain name, this is useful when sending en email to another mail server that supports ESMTP, let’s keep it simple and just put Gmail:

server.ehlo('Gmail')
Enter fullscreen mode Exit fullscreen mode

Let’s also start the TLS protocol with server.starttls(), this tells the mail server we want to send our email through a secure connection:

server.starttls()
Enter fullscreen mode Exit fullscreen mode

We'll then login to the mail sever using this line:

server.login(email,password)
Enter fullscreen mode Exit fullscreen mode

Let’s add a from address and to address(es), using fromaddr and toaddrs respectively:

fromaddr = 'Your Gmail address.'
toaddrs  = 'Destination address.'
Enter fullscreen mode Exit fullscreen mode

Finally, we send our email using server.sendmail(fromaddr,toaddrs,message.as_string()) and we close our connection to the mail server using server.quit():

server.sendmail(fromaddr,toaddrs,message.as_string())
server.quit()
Enter fullscreen mode Exit fullscreen mode

Save that in a file called send_email.py, open a Terminal if you're on Linux or a Command Prompt if you're on Windows and launch it using python send_email.py and you should see this:

Linux Terminal launching a Python script

If nothing happens, well good news it's working!

You should have received an email to your destination email(s), here's what I got:

Email received to a Gmail account after launching the Python script

Sending email using Python and Gmail's free SMTP server is the easiest way you can start sending email within your Python code, this is exactly what I've done when I built my first online busines ever. You can read more about it here.

server Article's
30 articles in total
Favicon
Singularity: Streamlining Game Development with a Universal Framework
Favicon
VPS Servers for Linux - Everything You Need to Know
Favicon
SLOT THAILAND™ LINK SITUS SLOT GACOR TERBAIK GAMPANG MAXWIN 2024
Favicon
Why adventuresinminecraft.com is the Best Minecraft Server for Customization and Survival
Favicon
Free VPS Hosting and Windows VPS to Understand How They Work on Websites
Favicon
How to Send Emails in Python Using Gmail’s Free SMTP Mail Server API
Favicon
How to write GraphQL resolvers effectively
Favicon
Path-Based Reverse Proxying with Caddy
Favicon
How I Set Up My Own Server (and Why You Should Too)
Favicon
Unlocking the Power of AWS Route 53: Your Complete Guide to DNS Management
Favicon
Unlock Efficient Data Exchange: Import & Export Excel in ASP.NET Core
Favicon
Copy file between server and local machine ( from windows to linux server )
Favicon
Client Boundaries
Favicon
Server actions in Next.js
Favicon
Self-host - Part 3 - MySQL and PostgreSQL Database Backup to Local Drive
Favicon
need suggestions
Favicon
SQL Operators Made Easy for Beginners
Favicon
What is Localhost in Development Mode?
Favicon
How to Customize the Fastify Logger
Favicon
Websocket starter in Rust with client and server example
Favicon
Unraid: Das ultimative Tool für deine Heimserver 🚀
Favicon
Drawbacks to Using Rack Server Unit as Desktop Computer?
Favicon
How to View Your index.php File in a Browser
Favicon
NextJs Server Actions: Why and How
Favicon
Self-host - Part 2 - Zero-Downtime Deployment using Docker Swarm
Favicon
Decoding Web Hosting: Understanding the landlords of the digital Realm Landscape
Favicon
Kaptan ve Tayfa - Kaptan Sunucu Kurulumu
Favicon
argc, argv의 차이
Favicon
Server side (vulnerability scanning)
Favicon
Running npm install on a Server with 1GB Memory using Swap

Featured ones: