Skip to content

Instantly share code, notes, and snippets.

@rodrigocorreaecastro
Forked from audente/GMail.py
Created September 14, 2022 14:28
Show Gist options
  • Save rodrigocorreaecastro/5b6b078785d4f8130ccc10aa58963d59 to your computer and use it in GitHub Desktop.
Save rodrigocorreaecastro/5b6b078785d4f8130ccc10aa58963d59 to your computer and use it in GitHub Desktop.
Python functions to send mail using GMail. Usage: from GMail import GMailServer, SendMail with GMailServer('username', 'password') as server: SendMail(server, 'fromaddr', 'toaddrs', 'subject', 'body')
# --------------------------------------------------
import smtplib
class GMailServer:
def __init__(self, username, password):
self.server = smtplib.SMTP('smtp.gmail.com:587')
self.server.starttls()
self.server.login(username,password)
def __enter__(self):
return self.server
def __exit__(self, type, value, traceback):
self.server.quit()
# --------------------------------------------------
from email.mime.text import MIMEText
def SendMail(server, fromaddr, toaddr, subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddr
server.sendmail(fromaddr, [toaddr], msg.as_string())
# --------------------------------------------------
'''
fromaddr = '[email protected]'
toaddrs = '[email protected]'
subject = 'subject'
body = 'body text'
# Credentials
username = '[email protected]'
password = 'password'
with GMailServer(username, password) as server:
SendMail(server, fromaddr, toaddrs, subject, body)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment