Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Send email with attachment(s) in Python (See related posts)

Can't remember if I wrote this or found it on the Web or a combination, so I won't take credit per se -- I'm just posting it as reference.

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, files=[], server="localhost"):
  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:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(file,"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()

Comments on this post

geon posts on Oct 04, 2006 at 14:42
import os ... missing
geon posts on Oct 04, 2006 at 14:48
and: "file" should stay keyword
timmorgan posts on Oct 04, 2006 at 23:27
ok, fixed the missing import, but I don't know what you mean by your second comment.
mikepowers48 posts on Dec 04, 2006 at 16:13
I think geon was pointing out that the use of file in the for loop obscures the built-in file keyword.
jabapyth posts on Dec 28, 2006 at 01:13
do you need to import all those things? really. COMMASPACE???
timmorgan posts on Dec 28, 2006 at 03:43
I changed "file" to "f" so built-in "file" won't get stepped on.

I found this somewhere on the Web -- don't know if you could do it with less.
jeremymason posts on Apr 25, 2008 at 17:09
I found this useful, note the line:
    part.set_payload( open(file,"rb").read() )

should be:
    part.set_payload( open(f,"rb").read() )

(change file to f in the loop)

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts