Skip to content

Instantly share code, notes, and snippets.

@thespacedoctor
Last active May 5, 2021 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thespacedoctor/ac06d42d46db187f3c1d25f5011a5ee8 to your computer and use it in GitHub Desktop.
Save thespacedoctor/ac06d42d46db187f3c1d25f5011a5ee8 to your computer and use it in GitHub Desktop.
[Send Gmail from Python] #gmail #python
gmail:
username: "david.young@pessto.org"
password: "mypass"
#!/usr/local/bin/python
# encoding: utf-8
"""
*Send Email Messages from a Gmail Accounts*
:Author:
David Young
:Date Created:
March 21, 2019
Usage:
send_gmail <to> <subject> <message> [<alias>] [-s <pathToSettingsFile>]
Options:
-h, --help show this help message
-v, --version show version
-s <pathToSettingsFile>, --settings <pathToSettingsFile> the settings file
"""
################# GLOBAL IMPORTS ####################
import sys
import os
from fundamentals import tools
import smtplib
def main(arguments=None):
"""
*The main function used when ``send_gmail.py`` is run as a single script from the cl*
"""
# SETUP THE COMMAND-LINE UTIL SETTINGS
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="DEBUG",
options_first=False,
projectName=False
)
arguments, settings, log, dbConn = su.setup()
# UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
# AUTOMATICALLY
for arg, val in arguments.iteritems():
if arg[0] == "-":
varname = arg.replace("-", "") + "Flag"
else:
varname = arg.replace("<", "").replace(">", "")
if isinstance(val, str) or isinstance(val, unicode):
exec(varname + " = '%s'" % (val,))
else:
exec(varname + " = %s" % (val,))
if arg == "--dbConn":
dbConn = val
log.debug('%s = %s' % (varname, val,))
gmail_address = settings["gmail"]["username"]
password = settings["gmail"]["password"]
send_gmail(
log=log,
gmail_address=gmail_address,
password=password,
to=to,
subject=subject,
body=message,
alias=alias)
return
import smtplib
def send_gmail(
log,
gmail_address,
password,
to,
subject,
body,
alias=False):
"""*send an email from a gmail account*
**Key Arguments:**
- ``log`` -- logger
- ``gmail_address`` -- the primary gmail address of the account to send the email from
- ``password`` -- the password to sign into the account
- ``to`` -- email address(es) to send the email to. String or list
- ``subject`` -- email subject
- ``body`` -- the email body
- ``alias`` -- an alias address to send the email from. If false then use `gmail_address`. Default *False*
**Return:**
- None
**Usage:**
.. code-block:: python
send_gmail(
log=log,
gmail_address="my.address@gmail.com",
password="xgshsdus&8d(03",
to="alerts@some_domain.org",
subject="test alert",
body="test message",
alias="my.other.address@some_domain.org")
"""
log.debug('starting the ``send_gmail`` function')
# CREATE A GMAIL SMTP SESSION
s = smtplib.SMTP('smtp.gmail.com', 587)
# START TLS (TRANSPORT LAYER SECURITY) FOR SECURITY
s.ehlo()
s.starttls()
# AUTHENTICATE YOURSELF
s.login(gmail_address, password)
if isinstance(to, list):
to = (", ").join(to)
if not alias:
alias = gmail_address
# CREATE MESSAGE TO BE SENT
message = "From: %(alias)s\nTo: %(to)s\nSubject: %(subject)s\n\n%(body)s" % locals()
# SEND MESSAGE
s.sendmail(alias, to, message)
# TERMINATE SESSION
s.close()
log.debug('completed the ``send_gmail`` function')
return None
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment