Skip to content

Instantly share code, notes, and snippets.

@gregcaporaso
Created September 29, 2012 19:07
Show Gist options
  • Save gregcaporaso/3804942 to your computer and use it in GitHub Desktop.
Save gregcaporaso/3804942 to your computer and use it in GitHub Desktop.
Functions for sending messages with gmail
import os.path
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
def mail(to, subject, text, mail_user, mail_password, attach=None):
msg = MIMEMultipart()
msg['From'] = mail_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(mail_user, mail_pwd)
mailServer.sendmail(mail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment