Skip to content

Instantly share code, notes, and snippets.

@dbieber
Last active January 22, 2021 02:56
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save dbieber/5146518 to your computer and use it in GitHub Desktop.
Save dbieber/5146518 to your computer and use it in GitHub Desktop.
Send an email through Gmail programmatically using Python's smtplib. Code modified from http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html
#!/usr/bin/python
# Adapted from http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html
import getpass
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "you@should.login"
gmail_pwd = "wrong password"
def login(user):
global gmail_user, gmail_pwd
gmail_user = user
gmail_pwd = getpass.getpass('Password for %s: ' % gmail_user)
def mail(to, subject, text, attach=None):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
if attach:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
# Example!
def example():
email = raw_input("Your Gmail address: ")
login(email)
mail("dbieber@princeton.edu", "Automate your life: sending emails", "Why'd the elephant sit on the marshmallow?")
example()
@bradvogel
Copy link

@pcarpio
Copy link

pcarpio commented Dec 10, 2015

thanks for the code, works perfect

@siva82kb
Copy link

Thank you for the code. It works very well. Just what I was looking for.

@Naramsim
Copy link

Naramsim commented Jul 8, 2017

Which ports do I have do open to send these emails? @dbieber

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment