Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   SMTPlib Emailing Attachments (http://www.velocityreviews.com/forums/t322603-smtplib-emailing-attachments.html)

Bill 09-17-2003 04:49 PM

SMTPlib Emailing Attachments
 
I am trying to have the capability to email attachments. Specifically
I want to be able to email a specific attachment that I name that may
be a PDF document, text doc, etc. I already have a working piece of
code that emails jpg attachments but does not work with any other
types of attachments. Could someone tell me how to modify this code to
send other types of attachments like the one's stated above(especially
PDF's)? Also how do I determine the name of the attachment? Right now
it defaults to Attach0. Here is the current code I have below:
_________________________________________________
import sys, smtplib, MimeWriter, base64, StringIO

message = StringIO.StringIO()
writer = MimeWriter.MimeWriter(message)
writer.addheader('Subject', 'The Text test')
writer.startmultipartbody('mixed')

# start off with a text/plain part
part = writer.nextpart()
body = part.startbody('text/plain')
body.write('This is a picture of chess, enjoy :)')

# now add an image part
part = writer.nextpart()
part.addheader('Content-Transfer-Encoding', 'base64')
body = part.startbody('image/jpeg')
#body = part.startbody('text/plain')
base64.encode(open('c:\email\chess01.jpg', 'rb'), body)

# finish off
writer.lastpart()

# send the mail
smtp = smtplib.SMTP('fc.hbu.edu')
smtp.sendmail('bblancett@hbu.edu', 'bblancett@hbu.edu',
message.getvalue())
smtp.quit()
__________________________________________________ ________________________

Rudy Schockaert 09-17-2003 06:27 PM

Re: SMTPlib Emailing Attachments
 
Bill wrote:
> I am trying to have the capability to email attachments. Specifically
> I want to be able to email a specific attachment that I name that may
> be a PDF document, text doc, etc. I already have a working piece of
> code that emails jpg attachments but does not work with any other
> types of attachments. Could someone tell me how to modify this code to
> send other types of attachments like the one's stated above(especially
> PDF's)? Also how do I determine the name of the attachment? Right now
> it defaults to Attach0. Here is the current code I have below:
> _________________________________________________
> import sys, smtplib, MimeWriter, base64, StringIO
>
> message = StringIO.StringIO()
> writer = MimeWriter.MimeWriter(message)
> writer.addheader('Subject', 'The Text test')
> writer.startmultipartbody('mixed')
>
> # start off with a text/plain part
> part = writer.nextpart()
> body = part.startbody('text/plain')
> body.write('This is a picture of chess, enjoy :)')
>
> # now add an image part
> part = writer.nextpart()
> part.addheader('Content-Transfer-Encoding', 'base64')
> body = part.startbody('image/jpeg')
> #body = part.startbody('text/plain')
> base64.encode(open('c:\email\chess01.jpg', 'rb'), body)
>
> # finish off
> writer.lastpart()
>
> # send the mail
> smtp = smtplib.SMTP('fc.hbu.edu')
> smtp.sendmail('bblancett@hbu.edu', 'bblancett@hbu.edu',
> message.getvalue())
> smtp.quit()
> __________________________________________________ ________________________


Wouldn't it be a lot easier to use the email module?

This is a snippet of how I send attachments (simply replace
TO,FROM,Subect, path (full pathname including filename) and filename
with relevant data):

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):
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(fp.read(),_subtype=subtype)
elif maintype == 'message':
attach = email.message_from_file(fp)
elif maintype == 'image':
attach = MIMEImage(fp.read(),_subtype=subtype)
elif maintype == 'audio':
attach = MIMEAudio(fp.read(),_subtype=subtype)
else:
print maintype, subtype
attach = MIMEBase(maintype, subtype)
attach.set_payload(fp.read())
encode_base64(attach)
fp.close
attach.add_header('Content-Disposition', 'attachment',
filename=filename)
return attach


msg = MIMEMultipart()
msg['From'] = FROM
msg['To'] = TO
msg['Subject'] = SUBJECT
attach = getAttachment(path, filename)
msg.attach(attach)

server = smtplib.SMTP(MAILSERVER)
server.sendmail(FROM, [TO], msg.as_string())
server.quit()


Jochen Knuth 09-17-2003 06:29 PM

Re: SMTPlib Emailing Attachments
 
Hi Bill,

Bill wrote:

> I am trying to have the capability to email attachments. Specifically
> I want to be able to email a specific attachment that I name that may
> be a PDF document, text doc, etc. I already have a working piece of
> code that emails jpg attachments but does not work with any other
> types of attachments. Could someone tell me how to modify this code to
> send other types of attachments like the one's stated above(especially
> PDF's)?



look at the email package (included since Python 2.2), documented at
http://www.python.org/doc/current/lib/module-email.html , specific to
MIME-Attachment is http://www.python.org/doc/current/lib/node501.html .

Ciao,
Jochen
--
--------------------------------------------------
Jochen Knuth WebMaster http://www.ipro.de
IPRO GmbH Phone ++49-7152-93330
Steinbeisstr. 6 Fax ++49-7152-933340
71229 Leonberg EMail: J.Knuth@ipro.de


Bill 09-18-2003 01:12 PM

Re: SMTPlib Emailing Attachments
 
Thanks for your response Rudy I think you put me on the right track.
But when I ran your script I still got the following errors:
______________Errors______________________________ ___________________________
Traceback (most recent call last):
File "C:\Program Files\Python22\ImgAndText.py", line 41, in ?
attach = getAttachment(path, filename)
File "C:\Program Files\Python22\ImgAndText.py", line 15, in
getAttachment
fp = open(path, 'rb')
IOError: [Errno 2] No such file or directory: 'C:\\Email\test.txt'
__________________________________________________ ___________________________

My question to you is what version of Python are you using (I am using
2.2.2.)?
Are you using the Windows version (I am using Windows)? If you are
using the Windows version where do you have your Python folder located
(Mine is c:\Program Files\Python22\) ? These are my system parameters.
And here is the code that I used. It is exactly like your code but I
changed the TO,FROM,Subect, path (full pathname including filename)
and also the SMTP server like you suggested. Here it is posted below:
______________Code Snippet___________________________________________ _____
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):
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(fp.read(),_subtype=subtype)
elif maintype == 'message':
attach = email.message_from_file(fp)
elif maintype == 'image':
attach = MIMEImage(fp.read(),_subtype=subtype)
elif maintype == 'audio':
attach = MIMEAudio(fp.read(),_subtype=subtype)
else:
print maintype, subtype
attach = MIMEBase(maintype, subtype)
attach.set_payload(fp.read())
encode_base64(attach)
fp.close
attach.add_header('Content-Disposition', 'attachment',
filename=filename)
return attach


msg = MIMEMultipart()
msg['From'] = 'bblancett@hbu.edu'
msg['To'] = 'bblancett@hbu.edu'
msg['Subject'] = 'here is your attachment'
path = 'C:\Email\test.txt'
filename = 'test.txt'
attach = getAttachment(path, filename)
msg.attach(attach)

server = smtplib.SMTP('fc.hbu.edu')
server.sendmail('bblancett@hbu.edu', 'bblancett@hbu.edu',
msg.as_string())
server.quit()
__________________________________________________ _________________________


Rudy Schockaert <rudy.schockaert@pandora.be> wrote in message news:<KI1ab.25228$dy5.1507439@phobos.telenet-ops.be>...
> Bill wrote:
> > I am trying to have the capability to email attachments. Specifically
> > I want to be able to email a specific attachment that I name that may
> > be a PDF document, text doc, etc. I already have a working piece of
> > code that emails jpg attachments but does not work with any other
> > types of attachments. Could someone tell me how to modify this code to
> > send other types of attachments like the one's stated above(especially
> > PDF's)? Also how do I determine the name of the attachment? Right now
> > it defaults to Attach0. Here is the current code I have below:
> > _________________________________________________
> > import sys, smtplib, MimeWriter, base64, StringIO
> >
> > message = StringIO.StringIO()
> > writer = MimeWriter.MimeWriter(message)
> > writer.addheader('Subject', 'The Text test')
> > writer.startmultipartbody('mixed')
> >
> > # start off with a text/plain part
> > part = writer.nextpart()
> > body = part.startbody('text/plain')
> > body.write('This is a picture of chess, enjoy :)')
> >
> > # now add an image part
> > part = writer.nextpart()
> > part.addheader('Content-Transfer-Encoding', 'base64')
> > body = part.startbody('image/jpeg')
> > #body = part.startbody('text/plain')
> > base64.encode(open('c:\email\chess01.jpg', 'rb'), body)
> >
> > # finish off
> > writer.lastpart()
> >
> > # send the mail
> > smtp = smtplib.SMTP('fc.hbu.edu')
> > smtp.sendmail('bblancett@hbu.edu', 'bblancett@hbu.edu',
> > message.getvalue())
> > smtp.quit()
> > __________________________________________________ ________________________

>
> Wouldn't it be a lot easier to use the email module?
>
> This is a snippet of how I send attachments (simply replace
> TO,FROM,Subect, path (full pathname including filename) and filename
> with relevant data):
>
> 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):
> 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(fp.read(),_subtype=subtype)
> elif maintype == 'message':
> attach = email.message_from_file(fp)
> elif maintype == 'image':
> attach = MIMEImage(fp.read(),_subtype=subtype)
> elif maintype == 'audio':
> attach = MIMEAudio(fp.read(),_subtype=subtype)
> else:
> print maintype, subtype
> attach = MIMEBase(maintype, subtype)
> attach.set_payload(fp.read())
> encode_base64(attach)
> fp.close
> attach.add_header('Content-Disposition', 'attachment',
> filename=filename)
> return attach
>
>
> msg = MIMEMultipart()
> msg['From'] = FROM
> msg['To'] = TO
> msg['Subject'] = SUBJECT
> attach = getAttachment(path, filename)
> msg.attach(attach)
>
> server = smtplib.SMTP(MAILSERVER)
> server.sendmail(FROM, [TO], msg.as_string())
> server.quit()


Richie Hindle 09-18-2003 01:30 PM

Re: SMTPlib Emailing Attachments
 

[Bill]
> IOError: [Errno 2] No such file or directory: 'C:\\Email\test.txt'

^^ ^

You've missed a backslash somewhere. Your filename looks like
C:\Email<tab>est.txt. You should always do one of the following:

o Remember to double your backslashes: "C:\\Email\\test.txt"
o Use raw strings for pathnames: r"C:\Email\test.txt"
o Use forward slashes (which are fine on Windows): "C:/Email/test.txt"

--
Richie Hindle
richie@entrian.com



Bill 09-19-2003 01:09 PM

Re: SMTPlib Emailing Attachments
 
Thanks Richie this corrected my error. I appreciate it.

Richie Hindle <richie@entrian.com> wrote in message news:<mailman.1063891936.20380.python-list@python.org>...
> [Bill]
> > IOError: [Errno 2] No such file or directory: 'C:\\Email\test.txt'

> ^^ ^
>
> You've missed a backslash somewhere. Your filename looks like
> C:\Email<tab>est.txt. You should always do one of the following:
>
> o Remember to double your backslashes: "C:\\Email\\test.txt"
> o Use raw strings for pathnames: r"C:\Email\test.txt"
> o Use forward slashes (which are fine on Windows): "C:/Email/test.txt"


Bill 09-19-2003 01:18 PM

Re: SMTPlib Emailing Attachments
 
Thanks to help of Rudy Shockaert I was able to solve my problem and I
also added the capability to add the email body if you are curious and
don't know how. I also commented the code as well. Here is the code
result:

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
#_________________________________________________ __________________________________________________ ___
#Requirements:At least Python 2.2.2
#getAttachment takes the directory path and the filename for ex:
'c:\\MyFolder\\test.txt'
#You must put double back slashes in your path.
#getAttachment returns email version of the type of file it takes in,
#For example if it is a text file, it will encode it as a text file, a
gif, it will encode it as a gif
#_________________________________________________ __________________________________________________ ____
def getAttachment(path, filename):
ctype, encoding = mimetypes.guess_type(path) #mimetypes guesses
the type of file and stores it in ctype
if ctype is None or encoding is not None: # example: ctype
can equal "application/pdf"
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1) #We do a split on "/"
to store "application" in maintype and "pdf" in subtype
fp = open(path, 'rb') #open the file
if maintype == 'text':
attach = MIMEText(fp.read(),_subtype=subtype) #check for
maintype value and encode and return according to
elif maintype == 'message': #the type of
file.
attach = email.message_from_file(fp)
elif maintype == 'image':
attach = MIMEImage(fp.read(),_subtype=subtype)
elif maintype == 'audio':
attach = MIMEAudio(fp.read(),_subtype=subtype)
else:
print maintype, subtype #if it does not equal any of the
above we print to screen and encode and return
attach = MIMEBase(maintype, subtype) #the encoded value
attach.set_payload(fp.read())
encode_base64(attach)
fp.close
attach.add_header('Content-Disposition', 'attachment',
filename=filename)
return attach

#_________________________________________________ ______________________________________________
#Here we set up our email
From = 'myname@hotmail.com'
To = 'yourname@hotmail.com'
msg = MIMEMultipart()
msg['From'] = From
msg['To'] = To
msg['Subject'] = 'here is your attachment'
body = MIMEText('This is the body of the email!') #Here is the body
path = 'C:\\YourPath\\YourFile.txt'
filename = 'gfe.pdf'
attach = getAttachment(path, filename) #We call our getAttachment()
function here
msg.attach(attach) #We create our message both attachment and the
body
msg.attach(body)

server = smtplib.SMTP('mySMTPServerName.com')
server.sendmail(From, To, msg.as_string()) #Send away
server.quit()


bblancett@hotmail.com (Bill) wrote in message news:<4fd6e92.0309170849.287e86b6@posting.google.c om>...
> I am trying to have the capability to email attachments. Specifically
> I want to be able to email a specific attachment that I name that may
> be a PDF document, text doc, etc. I already have a working piece of
> code that emails jpg attachments but does not work with any other
> types of attachments. Could someone tell me how to modify this code to
> send other types of attachments like the one's stated above(especially
> PDF's)? Also how do I determine the name of the attachment? Right now
> it defaults to Attach0. Here is the current code I have below:
> _________________________________________________
> import sys, smtplib, MimeWriter, base64, StringIO
>
> message = StringIO.StringIO()
> writer = MimeWriter.MimeWriter(message)
> writer.addheader('Subject', 'The Text test')
> writer.startmultipartbody('mixed')
>
> # start off with a text/plain part
> part = writer.nextpart()
> body = part.startbody('text/plain')
> body.write('This is a picture of chess, enjoy :)')
>
> # now add an image part
> part = writer.nextpart()
> part.addheader('Content-Transfer-Encoding', 'base64')
> body = part.startbody('image/jpeg')
> #body = part.startbody('text/plain')
> base64.encode(open('c:\email\chess01.jpg', 'rb'), body)
>
> # finish off
> writer.lastpart()
>
> # send the mail
> smtp = smtplib.SMTP('fc.hbu.edu')
> smtp.sendmail('bblancett@hbu.edu', 'bblancett@hbu.edu',
> message.getvalue())
> smtp.quit()
> __________________________________________________ ________________________


Karl Scalet 09-19-2003 01:35 PM

Re: SMTPlib Emailing Attachments
 
Bill wrote:

> [...]
> path = 'C:\\YourPath\\YourFile.txt'
> filename = 'gfe.pdf'


is this correct? Shouldn't path contain the directory only?
Otherwise what's the content of YourFile.txt then.

Karl


Bill 09-19-2003 09:33 PM

Re: SMTPlib Emailing Attachments
 
Karl Scalet <news@yebu.de> wrote in message news:<bkf0nd$10dm0$1@ID-141451.news.uni-berlin.de>...
> Bill wrote:
>
> > [...]
> > path = 'C:\\YourPath\\YourFile.txt'
> > filename = 'YourFile.txt'

>
> is this correct? Shouldn't path contain the directory only?
> Otherwise what's the content of YourFile.txt then.
>
> Karl


Well I believe you need the file as well b/c the mimetypes function
checks the extension to see what type of file it is. I am sure you can
modify it to be more efficient. But it works as is.

Rudy Schockaert 09-20-2003 10:26 AM

Re: SMTPlib Emailing Attachments
 
Bill wrote:
> Karl Scalet <news@yebu.de> wrote in message news:<bkf0nd$10dm0$1@ID-141451.news.uni-berlin.de>...
>
>>Bill wrote:
>>
>>
>>>[...]
>>>path = 'C:\\YourPath\\YourFile.txt'
>>>filename = 'YourFile.txt'

>>
>>is this correct? Shouldn't path contain the directory only?
>>Otherwise what's the content of YourFile.txt then.
>>
>>Karl

>
>
> Well I believe you need the file as well b/c the mimetypes function
> checks the extension to see what type of file it is. I am sure you can
> modify it to be more efficient. But it works as is.


Path and filename are two distinct items. The first points to the
physical file, the other is the name the attachment will get in the mail.
This way you also have the flexibility to name the file once attached
different than the version on disk.



All times are GMT. The time now is 07:36 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.