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

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
  • Define Gmail account info and recipient email:
# The email addresses and password
sender_address = '[email protected]'
sender_password = 'yourpassword'
gmail_port = 587

receiver_address = '[email protected]'
mail_content = 'Easy peazy lemon squeezy'
  • Setup the MIME:
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Sending email using Python'
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')

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 = '[email protected]'
sender_password = 'yourpassword'
gmail_port = 587

receiver_address = '[email protected]'
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 ๐Ÿ

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.

Thanks for reading this tiny scripts serie ๐Ÿ˜Š
See you soon @Kinoba

Table of contents

26