Last active
August 29, 2015 14:16
-
-
Save philangist/909207db9b5438ec2dd8 to your computer and use it in GitHub Desktop.
Send email as a gmail user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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