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.
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(,_subtype=subtype)
elif maintype == ‘message’:
attach = email.message_from_file(fp)
elif maintype == ‘image’:
attach = MIMEImage(,_subtype=subtype)
elif maintype == ‘audio’:
attach = MIMEAudio(,_subtype=subtype)
print maintype, subtype
attach = MIMEBase(maintype, subtype)
attach.add_header(‘Content-Disposition’, ‘attachment’,
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
for path in attachmentFileNames:
filename = path.split(‘/’)[-1]
print ‘getAttachment’, path, filename
attach = getAttachment(path, filename)
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.login(username, password)
server.sendmail(fromAddr, toAddr, msg)

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 *