How to add an attachment with smtplib module

Seo Sanghyeon tinuviel at sparcs.kaist.ac.kr
Thu Apr 29 01:12:13 EDT 2004


Sean Berry <sean at sands.beach.net> wrote:
> 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.



More information about the Python-list mailing list