Skip to content

Instantly share code, notes, and snippets.

@thespacedoctor
Last active April 26, 2024 08:47
Show Gist options
  • 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>] [-a <attachment>] [-s <pathToSettingsFile>]
Options:
-h, --help show this help message
-v, --version show version
-a <attachment> path to attachment
-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="WARNING",
options_first=False,
projectName=False
)
arguments, settings, log, dbConn = su.setup()
# UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
# AUTOMATICALLY
a = {}
for arg, val in list(arguments.items()):
if arg[0] == "-":
varname = arg.replace("-", "") + "Flag"
else:
varname = arg.replace("<", "").replace(">", "")
a[varname] = val
if arg == "--dbConn":
dbConn = val
a["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=a["to"],
subject=a["subject"],
body=a["message"],
alias=a["alias"],
attachment=a["aFlag"])
return
def send_gmail(
log,
gmail_address,
password,
to,
subject,
body,
alias=False,
attachment=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*
- ``attachment`` -- send an attachment
**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')
import mimetypes
from email.message import EmailMessage
# START MESSAGE
message = EmailMessage()
# 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
message['To'] = to
message['Subject'] = subject
message.set_content(body)
if attachment:
mime_type, _ = mimetypes.guess_type(attachment)
mime_type, mime_subtype = mime_type.split('/')
filename = os.path.basename(attachment)
with open(attachment, 'rb') as file:
message.add_attachment(file.read(),
maintype=mime_type,
subtype=mime_subtype,
filename=filename)
# SEND MESSAGE
s.send_message(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