Dairon Medina

Dairon Medina (@codeadict)

software developer

Indian Rocks Beach, FL, Planet Earth (27.9284859,-82.755531,13 - UTC-05)

Send e-mails with attachment in Python

Now im working on a little application that have to send emails with attachments in python, I make that code that can be reusable to someone:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- 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.medina@gmail.com'
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())
Post by Avatar Dairon Medina on
comments powered by Disqus