Skip to content

Instantly share code, notes, and snippets.

@scottsweb
Last active August 29, 2015 14:04
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 scottsweb/79fc6433c3f308ce1cd5 to your computer and use it in GitHub Desktop.
Save scottsweb/79fc6433c3f308ce1cd5 to your computer and use it in GitHub Desktop.
Send Email via Gmail with Python
#!/usr/bin/python
import argparse
import os
import smtplib
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
parser = argparse.ArgumentParser(description='Script to send an email via Gmail.')
parser.add_argument('-t','--to', help='Send email to (e.g. test@example.com)',required=True)
parser.add_argument('-f','--fm',help='Email is from (e.g. test@example.com)', required=True)
parser.add_argument('-s','--subject',help='Email subject', required=True)
parser.add_argument('-b','--body',help='Email body', required=False)
parser.add_argument('-a','--attach',help='Path to attachment', required=False)
parser.add_argument('-u','--username',help='Gmail username', required=True)
parser.add_argument('-p','--password',help='Gmail password', required=True)
parser.add_argument('-d','--delete',help='Delete attachment after sending. Set to true to delete file', required=False)
args = parser.parse_args()
if (args.attach == ''):
attach = False
else:
attach = args.attach
if (args.delete == 'yes' and args.attach != False):
delete = True
else:
delete = False
def mail(to, frm, subject, body, attach, username, password, delete):
msg = MIMEMultipart()
msg['From'] = frm
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(body))
if (attach):
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
try:
server = SMTP_SSL("smtp.gmail.com", 465)
server.login(username, password)
server.sendmail(username, to, msg.as_string())
#server.quit()
server.close()
print("Email sent")
# delete photo? only if the email was sent
if (delete):
try:
os.remove(attach)
print("File deleted")
except OSError as e:
print("Failed with:", e.strerror)
print("Error code:", e.code)
except:
print("Email failed")
mail(args.to, args.fm, args.subject, args.body, attach, args.username, args.password, delete)
./gmail.py --help
./gmail.py --to test@example.com --fm test@example.com --subject "Hello World" --body "This is an email" --attach /path/to/file/test.jpg --username example@gmail.com --password mysecret --delete yes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment