#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import smtplib
from email.Utils import make_msgid
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from time import gmtime, strftime
# direccion del correo de quien lo envia
me = "yo@dominio.com"
# lista de correos donde enviar el mensaje
mailsTo = ["destinatario1@dominio.com", "destinatario2@dominio.com"]
# Send the message via SMTP server
def connect(tls=False):
try:
s = smtplib.SMTP('mail.dominio.com')
if tls:
s.starttls()
s.login("usuarioCorreo","ContraseñaCorreo")
#s.set_debuglevel(1)
return s
except Exception,e:
print e
sys.exit()
s=connect(True)
# Create the body of the message (a plain-text and an HTML version).
text = """
Contenido en texto plano
\nEste contenido se mostrara en los programas de correo que no permitan la utilizacion de contenido html
\nTambien puede ser utilizado por algunos programas de correo en el momento de responder si respondemos en texto plano.
\n\nEs recomendable que haya el mismo contenido en texto plano que en html.
\n\nhttp://www.lawebdelprogramador.com
"""
html = """
<html>
<head>
<style type="text/css">
.link {text-decoration:underline;color:#00f;}
body {font-size:14;}
</style>
</head>
<body>
<b>Contenido en HTML</b>
<p>Este contenido es el que se mostrara en los navegadores que permitan la visualización de correos en formato HTML.</p>
<p>Es recomendable que haya el mismo contenido en texto plano que en html</p>
<p><a href='http://www.lawebdelprogramador.com' class='link'>http://www.lawebdelprogramador.com</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain', 'UTF-8')
part2 = MIMEText(html, 'html', 'UTF-8')
# Cogemos la imagen y la añadimos al correo
fp=open("logolwp.jpg", 'rb')
image1 = MIMEImage(_imagedata=fp.read(),_subtype="jpeg")
fp.close()
for mailTo in mailsTo:
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg.set_charset("UTF-8")
msg['Subject'] = "Envio de correo desde python en formato HTML y Text"
msg['From'] = me
msg['To'] = mailTo
msg['Date'] = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
msg['Message-ID'] = "<%s@%s>" % (make_msgid()[1:].split('@')[0],mailTo.split('@')[1])
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
msg.attach(image1)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
try:
s.sendmail(me, mailTo, msg.as_string())
except Exception,e:
print e
print mailTo
print "---------------------------------"
s=connect()
s.quit()