Skip to content

Sending email in Python

How to send email in Python? There are many ways to acheive this: smptlib, sendmail or even Gmail SMTP port can be used. Read on to know how.

smtplib

The smtplib is a Python library for sending emails using the Simple Mail Transfer Protocol (SMTP). The smtplib is a built-in module; we do not need to install it. It abstracts away all the complexities of SMTP.

sendmail

Check the email package, construct the mail with that, serialise it, and send it to /usr/sbin/sendmail using the subprocess module:

from email.mime.text import MIMEText
from subprocess import Popen, PIPE

msg = MIMEText("Message body")
msg["From"] = "anand@poopcode.com"
msg["To"] = "subash@poopcode.com"
msg["Subject"] = "Email subject."
popen = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
popen.communicate(msg.as_string())

Google

Google’s SMTP servers are free to use and works really well to deliver
emails.

Note that Google has a sending limit: “Google will temporarily disable your
account if you send messages to more than 500 recipients or if you send a large number of undeliverable messages. “

import smtplib

# From and to addresses
from = 'anand@poopcode.com
to  = 'subash@poopcode.com'
# Writing the message (this message will appear in the email)
msg = 'Your message'
# Gmail Login Credentials
username = 'username'
password = 'password'
# Sending the mail  
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(from, to, msg)
server.quit()

See also  How to generate random numbers in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.