473,406 Members | 2,710 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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('b********@hbu.edu', 'b********@hbu.edu',
message.getvalue())
smtp.quit()
__________________________________________________ ________________________
Jul 18 '05 #1
9 10937
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('b********@hbu.edu', 'b********@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()

Jul 18 '05 #2
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.*****@ipro.de

Jul 18 '05 #3
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'] = 'b********@hbu.edu'
msg['To'] = 'b********@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('b********@hbu.edu', 'b********@hbu.edu',
msg.as_string())
server.quit()
__________________________________________________ _________________________
Rudy Schockaert <ru*************@pandora.be> wrote in message news:<KI*********************@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('b********@hbu.edu', 'b********@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()

Jul 18 '05 #4

[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
ri****@entrian.com
Jul 18 '05 #5
Thanks Richie this corrected my error. I appreciate it.

Richie Hindle <ri****@entrian.com> wrote in message news:<ma**********************************@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"

Jul 18 '05 #6
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 = 'm*****@hotmail.com'
To = 'y*******@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()
bb*******@hotmail.com (Bill) wrote in message news:<4f*************************@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('b********@hbu.edu', 'b********@hbu.edu',
message.getvalue())
smtp.quit()
__________________________________________________ ________________________

Jul 18 '05 #7
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

Jul 18 '05 #8
Karl Scalet <ne**@yebu.de> wrote in message news:<bk************@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.
Jul 18 '05 #9
Bill wrote:
Karl Scalet <ne**@yebu.de> wrote in message news:<bk************@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.

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Bob-O | last post by:
Need your help in sending an email message with an attachment in my VB.Net program. Sending a body message is no problem. I don't know how to use the attachment property in an emai Following is...
5
by: Colin Anderson | last post by:
I discovered, with great excitement, this article http://www.davison.uk.net/vb2notes.asp when researching methods for emailing from Access via Notes. Unfortunatly, when I run this I get a...
4
by: Farooq Khan | last post by:
hi, i'm using CDONTS component for emailing through one of my web service like this // Start of code // 'email' is the CDONTS object name email.send(EmailFrom.ToString(), EmailTo.ToString(),...
4
by: MW de Jager | last post by:
I am sending an email with attachments from a dotnet ASP application. If I send an email it works fine if the attachment is located in a folder on my pc, which is open to all users on that PC, it...
1
by: Will | last post by:
Hey guys, i need a code that will allow users to email to multiple people as well as add as many attachments as user likes, and will work with outlook express/ or microsoft outlook (any version)...
3
by: Van_Gogh | last post by:
Hi, I am learning how to use the smtplib module, but am having some very early problems, maybe because I don't understand it. So, am I correct that by following the example in the Python: >>>...
1
by: mike11d11 | last post by:
I'm having a problem trying to add attachments to my email from my C:\ drive. What I'm trying to do here is have my database run a bunch of queries that gives me a report that I'm putting in the...
3
by: dee | last post by:
I need to send an email containing 2 reports. I have tried sending a 2 page snapshot report, but while it prints just fine before sending, email is only receiving 1 page. Is there a way to do...
1
by: =?Utf-8?B?U2FpIFZhamph?= | last post by:
Hi I am trying to send a .pdf document as an email attachment using net.mail. This email is being sent by a windows service application. After i receive the email, and when i try to open the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.