Here an example how to send a mail with attachement using built in smtp lib to multiple recipients. It’s really very simple in python.
Just take a look at the code bellow.
'simple smtp mailer with multiple recipients and file attachments'
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
import os
from smtplib import SMTP
class Mailer(object):
''' simple mailer '''
def __init__(self):
self.mail_to = ['rec3@example.com', 'rec2@example.com', 'rec3@example.com']
self.mail_from = 'mailer@python-blog.com'
msg_en = "This is an automated message from python-blog.com\r\n"
#path to file we want to attach
msg_file_attachment = '/home/marcink/Desktop/pydev_icons.zip'
#get the filename we need it for adding to mail header
msg_file_name = os.path.basename(msg_file_attachment)
smtp_serv = SMTP('mail.python-blog.com')
smtp_serv.ehlo("simpleMailerHello.python-blog.com")
#if server requires authorization you must provide login and password
smtp_serv.login('mylogin', 'mypassword')
date_ = formatdate(localtime = True)
msg = MIMEMultipart()
msg['From'] = self.mail_from
msg['To'] = COMMASPACE.join(self.mail_to)
msg['Date'] = date_
msg['Subject'] = "example subject"
#attach string message
msg.attach(MIMEText(msg_en))
#attach open encode the filename
file_part = MIMEBase('application', "octet-stream")
file_part.set_payload(open(msg_file_attachment, "rb").read())
encoders.encode_base64(file_part)
file_part.add_header('Content-Disposition', 'attachment; filename="%s"'
% msg_file_name)
msg.attach(file_part)
#sendmail and exit server
smtp_serv.sendmail(self.mail_from, self.mail_to, msg.as_string())
smtp_serv.quit()
if __name__ == "__main__":
Mailer()
print 'mail sent'