Part 2: Python Emailer

Part 2: Python Emailer

If you want to send emails using python’s smtplib, this is a good example.
The method sendMail takes 8 arguments and is able to send attached emails to an address.
Currently, this is only tested using my gmail account as the sender, but it should work elsewhere.

#emailer.py
import os.path
import sys, smtplib, MimeWriter, base64, StringIO
import smtplib
import mimetypes
from email.Encoders import encode_base64
from email.MIMEAudio import MIMEAudio
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def getAttachment(path, filename):
“””Returns the attachment as a MIME formatted object”””
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
ctype = ‘application/octet-stream’
maintype, subtype = ctype.split(‘/’, 1)
fp = open(path, ‘rb’)
if maintype == ‘text’:
attach = MIMEText(fp.read(),_subtype=subtype)
elif maintype == ‘message’:
attach = email.message_from_file(fp)
elif maintype == ‘image’:
attach = MIMEImage(fp.read(),_subtype=subtype)
elif maintype == ‘audio’:
attach = MIMEAudio(fp.read(),_subtype=subtype)
else:
print maintype, subtype
attach = MIMEBase(maintype, subtype)
attach.set_payload(fp.read())
encode_base64(attach)
fp.close
attach.add_header(‘Content-Disposition’, ‘attachment’,
filename=filename)
return attach

def getTotalMessage(toAddr, fromAddr, subject, msg, attachmentFileNames):
“””given a to address, from address, subject, msg and any attachments, returns
a message ready to be sent”””
mymsg = MIMEMultipart()
mymsg[‘From’] = fromAddr
mymsg[‘To’] = toAddr
mymsg[‘Subject’] = subject
mymsg.attach(MIMEText(msg))
for path in attachmentFileNames:
filename = path.split(‘/’)[-1]
print ‘getAttachment’, path, filename
attach = getAttachment(path, filename)
mymsg.attach(attach)
return mymsg.as_string()

def sendEmail(toAddr, fromAddr, subject, msg, serverAddr,
username, password, attachmentFileNames=[]):
“””This is the function to run when sending an email: Designed for gmail,
may work elsewhere”””
msg = getTotalMessage(toAddr, fromAddr, subject, msg, attachmentFileNames)

server = smtplib.SMTP(serverAddr)
server.ehlo(”)
server.starttls()
server.ehlo(”)
server.login(username, password)
server.sendmail(fromAddr, toAddr, msg)
server.quit()

Part 1: Python Screen Capture
Part 3: Setting up the schedule

Leave a Reply

Your email address will not be published. Required fields are marked *