How to add an attachment with smtplib module

S

Sean Berry

I have the sample script that uses the smtplib module
that is available at python.org.

How can I use this to send an attachment?

Help is greatly appreciated.

Thanks.

--
 
D

Dennis Lee Bieber

I have the sample script that uses the smtplib module
that is available at python.org.

How can I use this to send an attachment?
By brute force... You create the proper MIME headers to identify
the presence of an attachment; you use the proper module(s) to convert
the file of the attachment into an SMTP safe format (Base64?); you copy
the attachment, with proper MIME boundary markers, into the body of the
email.

No doubt there is a simpler, more automated method, but by
knowing what goes into the process, you can get more control over it.

smtplib is merely the low level interface between a sending
client and the receiving smtp daemon. The "msg" argument has to be a
fully formed message with all headers and body.

Check mimetools, mimify, and email modules.

--
 
S

Seo Sanghyeon

Sean Berry said:
I have the sample script that uses the smtplib module
that is available at python.org.

How can I use this to send an attachment?

You don't. smtplib is a transport for an already formatted email
message. You create a message with email package, like this:

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(file("text.txt").read())
msg.attach(MIMEImage(file("image.png").read())

And then send it:

import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

Read email package documentation for more details.
 
S

Steve Holden

Sean said:
I have the sample script that uses the smtplib module
that is available at python.org.

How can I use this to send an attachment?

Help is greatly appreciated.

Thanks.
Take a look at the "email" module, which is the usual way of generating
messages of complex structure. Then, specifically, look at "Creating
email and MIME objects from scratch" at (e.g.)
http://docs.python.org/lib/node501.html - you'll probably have the same
page in your local Python docs.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top