Skip to content

Instantly share code, notes, and snippets.

@philangist
Last active August 29, 2015 14:16
Show Gist options
  • Save philangist/909207db9b5438ec2dd8 to your computer and use it in GitHub Desktop.
Save philangist/909207db9b5438ec2dd8 to your computer and use it in GitHub Desktop.
Send email as a gmail user
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def send(recipient, subject, msg):
return GmailHandler().send(recipient)
class GmailHandler(object):
def __init__(self, email, password):
self.email = email
self.password = password
def _new_connection(self):
connection = smtplib.SMTP('smtp.gmail.com:587')
connection.starttls()
connection.login(self.email, self.password)
return connection
def _build_message(self, subject, content):
msg = MIMEMultipart()
msg['From'] = self.email
msg['Subject'] = subject
msg.attach(MIMEText(content, 'html'))
return msg
def send(self, recipient, subject='', content=''):
connection = self._new_connection()
msg = self._build_message(subject, content)
connection.sendmail(self.email, recipient, msg.as_string())
connection.quit()
if __name__ == '__main__':
handler = GmailHandler('[email protected]', 'password')
handler.send('[email protected]', 'FOOBAR', 'Click <a href="https://www.google.com">here</a> to <b>foo</b> the bar.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment