Skip to content

Instantly share code, notes, and snippets.

@GochoMugo
Forked from tusharbabbar/gmailer.py
Created August 7, 2014 12:38
Show Gist options
  • Save GochoMugo/7038fc846dde14e8a04c to your computer and use it in GitHub Desktop.
Save GochoMugo/7038fc846dde14e8a04c to your computer and use it in GitHub Desktop.
import smtplib, os
from email import Encoders
from email.Utils import COMMASPACE, formatdate
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
import argparse
import sys
#INFO
#Can be used with gmail accounts only.
#Can send to multiple recievers at once.
#TODO
#1. Catch for wrong username and password
#2. Catch for invalid sender or reciever
#3. Catch for file size greater than 25 mb
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username', nargs='?', required=True)
parser.add_argument('-p', '--password', nargs='?', required=True)
parser.add_argument('-s', '--sender', nargs='?', required=True)
parser.add_argument('-r', '--recievers', nargs='+', required=True)
parser.add_argument('-a', '--attachments', nargs='+', default = [])
parser.add_argument('-m', '--message', nargs='+', required=True)
parser.add_argument('-S', '--subject', nargs='+', required=True)
args = parser.parse_args()
username = args.username
password = args.password
sender = args.sender
recievers = args.recievers
files = args.attachments
subject = ' '.join(args.subject)
message = ' '.join(args.message)
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
server.sendmail(send_from, send_to, msg.as_string())
server = smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login(username,password)
send_mail(sender, recievers, subject, message, files, server)
server.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment