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.
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.
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"] = "email@example.com" msg["To"] = "firstname.lastname@example.org" msg["Subject"] = "Email subject." popen = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) popen.communicate(msg.as_string())
Google’s SMTP servers are free to use and works really well to deliver
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 = 'email@example.com to = 'firstname.lastname@example.org' # 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()