Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Last active August 29, 2015 14:14
Show Gist options
  • Save HakurouKen/4161594a60701ce7daf0 to your computer and use it in GitHub Desktop.
Save HakurouKen/4161594a60701ce7daf0 to your computer and use it in GitHub Desktop.
A simple python shell to send email (SMTP)
[global]
email = your_email@xxx.com
password = your_email_password
host = smtp.your_email_host.com
#coding: utf-8
import ConfigParser
import smtplib
import os
import sys
import argparse
import email
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class EmailSender():
def __init__(self,file):
config = ConfigParser.ConfigParser()
with open(file) as f:
config.readfp(f)
self.email = config.get("global","email")
userArr = self.email.split("@")
self.user = userArr[0]
self.site = userArr[1]
self.password = config.get("global","password")
self.host = config.get("global","host")
try:
self.name = config.get("global","name")
except:
self.name = ""
def __init_msg(self,subject,to=[],content='',files=[]):
self.me = self.name + "<" + self.email + ">"
msg = MIMEMultipart()
msg['From'] = self.me
msg['Subject'] = subject
if len(to) is 0:
to.append(self.email)
msg['To'] = ';'.join(to)
msg.attach(MIMEText(content))
for file in files:
attach = MIMEBase('application','octet-stream')
with open(file,'rb') as f:
attach.set_payload(f.read())
email.encoders.encode_base64(attach)
attach.add_header('Content-Disposition','attachment;filename=' + os.path.basename(file))
msg.attach(attach)
return msg
def send(self,subject,to=[],content='',files=[]):
msg = self.__init_msg(subject,to,content,files)
try:
server = smtplib.SMTP()
server.connect(self.host)
server.login(self.user,self.password)
server.sendmail(self.me,to,msg.as_string())
server.close()
print 'email sent successfully'
except Exception,e:
print str(e)
if __name__ == '__main__':
sender = EmailSender("config.ini")
parser = argparse.ArgumentParser()
parser.add_argument("-s","--subject", default="", help="Email Subject")
parser.add_argument("-t","--to", default=[], type=str, nargs='+', help="Send email to...")
parser.add_argument("-c","--content", default="", help="Email Content")
parser.add_argument("-f","--file", default=[], type=str, nargs='+', help="Attachment(s) of email")
args,remain = parser.parse_known_args()
sender.send(args.subject,args.to,args.content,args.file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment