Skip to content

3 ways to send emails with only few lines of code and Gmail - Python - Part 3

Posted on:June 28, 2021

We will see how to send a simple email with the help of three different programming languages: Javascript, Ruby and Python Before you start you need to create a Gmail account. Do not forget to accept and allow the “Less secure apps” access in order use your scripts with your Gmail smtp connection. I’ll let you do this on your own, you don’t need a tutorial for this 😜

Python 🐍

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# The email addresses and password
sender_address = 'youremail@gmail.com'
sender_password = 'yourpassword'
gmail_port = 587

receiver_address = 'myfriend@yopmail.com'
mail_content = 'Easy peazy lemon squeezy'
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Sending email using Python'
message.attach(MIMEText(mail_content, 'plain'))
session = smtplib.SMTP('smtp.gmail.com', gmail_port)
session.starttls() # enable security
session.login(sender_address, sender_password)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()

print('Email Sent')

Here the final code:

import smtplib

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

# The email addresses and password
sender_address = 'youremail@gmail.com'
sender_password = 'yourpassword'
gmail_port = 587

receiver_address = 'myfriend@yopmail.com'
mail_content = 'Easy peezy lemon squeezy'

# Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Sending email using Python'

# The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))

# Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', gmail_port)
session.starttls() # enable security
session.login(sender_address, sender_password)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()

print('Email Sent')

The power of Python 🐍

Python beast

What’s next?

With those scripts, we went through the basics of the module, gem and library (read the docs 📚) but you can also do amazing things with them like loops, sending attachments, automated things… feel free to do want you want.