How to send body and attachements in an email message?

Aspersieman aspersieman at gmail.com
Wed Dec 3 05:53:27 EST 2008


On Wed, 03 Dec 2008 12:40:30 +0200, srinivasan srinivas  
<sri_annauni at yahoo.co.in> wrote:

> HI,
> I would like to send an email message with body-content 'test' and an  
> attachment.
> The snippet i used is:
> outer = email.mime.multipart.MIMEMultipart()
> msg1 = email.mime.text.MIMEText(<filename1>, _subtype = 'text')
> msg1.add_header('Content-Disposition', 'attachment')
> outer.attach(msg1)
>
> body = email.mime.text.MIMEText(<filename1>, _subtype = 'text')
> outer.attach(body)
>
> smtp_client = smtplib.SMTP()
> smtp_client.connect()
> smtp_client.sendmail(<sender>, <recipient>, outer.as_string())
> smtp_client.close()
>
> If i do like above, i am receiving the body also as an attachment. How  
> to set body to Multipart email message?
>
> Thanks,
> Srini
>
>
>       Add more friends to your messenger and enjoy! Go to  
> http://messenger.yahoo.com/invite/
> --
> http://mail.python.org/mailman/listinfo/python-list

Hi there

I have used this method for a while. Works pretty good. (Apologies if the  
formatting is a bit wonky - gmail reformats my stuff)

import mimetypes
import poplib
import email
import smtplib
import os
 from email import *
 from email.mime import *

def SendMail(self, send_from, send_to, subject, text, files=[],  
server="localhost", username = None, password = None):
     # {{{
     """
     Sends an email. With optional attachment files.
     """
     assert type(send_to)==list
     assert type(files)==list

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

     msg.attach(MIMEText.MIMEText(text))

     for f in files:
         part = MIMEBase.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, 25)
     smtp.sock.settimeout(120)
     try:
         if username and password:
             smtp.login(username, password)
             smtp.sendmail(send_from, send_to, msg.as_string())
         else:
             smtp.sendmail(send_from, send_to, msg.as_string())
     except Exception, err:
         print "Error sending to " + str(send_to) + " ERROR : " + str(err)
         if self.logger:
             self.logger.error("Email error - error sending message to : "  
+ str(send_to) + " Error : " + str(err))

     smtp.close()
     # }}}

HTH

Nicol
-- 
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo



More information about the Python-list mailing list