Send e-mails with attachment in Python

11 February 2010 at 2:11 PM | Posted in Programming, Python | 1 Comment
Tags: , ,

Now im working on a little applicatithat have to send emails with attachments in python, I make that code that can be reusable to someone:

# -*- coding: iso-8859-1 -*-
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP

msg = MIMEMultipart()
msg['Subject'] = 'Email From Python jajaja'
msg['From'] = 'dairon@ceac.cu'
msg['Reply-to'] = 'otroemail@dominio'
msg['To'] = 'rms@gnu.org'

# That is what u see if dont have an email reader:
msg.preamble = 'Multipart massage.\n'

# This is the textual part:
part = MIMEText("Hello im sending an email from a python program")
msg.attach(part)

# This is the binary part(The Attachment):
part = MIMEApplication(open("file.pdf","rb").read())
part.add_header('Content-Disposition', 'attachment', filename="file.pdf")
msg.attach(part)

# Create an instance in SMTP server
smtp = SMTP("smtp.domain.cu")
# Start the server:
smtp.ehlo()
smtp.login("yo@example.com", "mipassword")

# Send the email
smtp.sendmail(msg['From'], msg['To'], msg.as_string())

Advertisement

1 Comment »

RSS feed for comments on this post. TrackBack URI

  1. Great little bit of code. thanks


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.