Pages

Thursday, September 16, 2010

Sending E-Maill in Python with Attachments

How to Send E-Mail in Python with Attachments ??

I found this link to be very useful.


http://snippets.dzone.com/posts/show/2038&default=false&zid=159&browser=16&mid=0&refresh=0


Now the Code,


import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, f, server="x.x.x.x"):
#  assert type(send_to)==list
#  assert type(files)==list

  msg = MIMEMultipart()
  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject

  msg.attach( MIMEText(text) )

  #for f in files:
  file=f
  part = MIMEBase('application', "octet-stream")
  part.set_payload( open(f,"rb").read() )
  Encoders.encode_base64(part)
  part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
  msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()

f='/root/xen_interface.pdf' # - >File to be attached
s=['Recipients E- Mail ID]
send_mail('Sender E-Mail ID' , s, 'test' , 'test' , f)


With this code, you can automate , sending a folder of files to

your recipient(s).

No comments:

Post a Comment