Skip to content

Instantly share code, notes, and snippets.

@dustindorroh
Created September 16, 2012 01:00
Show Gist options
  • Save dustindorroh/3730641 to your computer and use it in GitHub Desktop.
Save dustindorroh/3730641 to your computer and use it in GitHub Desktop.
Command line python program that sends an email with an attachment from your account to someone else.
#!/usr/bin/python
# -*-coding:utf-8-*-
#
# mail.py
#
# Copyright 2012 Dustin Dorroh <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
import sys
import getpass
import readline
def save_message(messagefile):
readline.write_history_file(messagefile)
def mail(username,password,to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
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)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(username, password)
mailServer.sendmail(username, to, msg.as_string())
mailServer.close()
def main():
if not sys.argv[1:]:
print "Usage: %s [file path]" % sys.argv[0]
return
print sys.argv[1:]
username = raw_input("Email: ")
password = getpass.getpass(prompt='Password for '+ username + ': ')
mailto = raw_input("To: ")
subject = raw_input("Subject: ")
messagefile = os.path.join(os.path.expanduser("~"), mailto)
print "Message: send EOF when done (crtl-D)."
while True:
try:
message = raw_input('> ')
except EOFError:
print "Sending Email"
break;
save_message(messagefile)
fd = open(messagefile,"r")
mail(username,password,mailto,subject,fd.read(),sys.argv[1])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment