Spanish (Español) translation by Luis Chiabrera (you can also view the original English article)
Este tutorial dará una introducción a SMTP, un módulo de Python utilizado para enviar correos. También demostrará cómo enviar diferentes tipos de correo electrónico, como mensajes de texto simples, correos electrónicos con archivos adjuntos y correos electrónicos con contenido HTML.
Importar a SMTP
El Protocolo simple de transferencia de correo (SMTP en inglés) maneja el envío y el correo electrónico de enrutamiento entre los servidores de correo.
En Python, el
módulo smtplib define un objeto de sesión de cliente SMTP que se puede
usar para enviar correo a cualquier máquina de Internet con un daemon de
escucha SMTP o ESMTP.
He aquí cómo crear un objeto SMTP.
1 |
import smtplib |
2 |
|
3 |
server = smtplib.SMTP(host='host_address',port=your_port) |
Crear y enviar un correo electrónico simple
La siguiente secuencia de comandos le permitirá enviar un correo electrónico a través del servidor SMTP de Gmail. Sin embargo, Google no permitirá el inicio de sesión a través de smtplib porque ha marcado este tipo de inicio de sesión como "menos seguro". Para solucionar
este problema, vaya a
https://www.google.com/settings/security/lesssecureapps mientras está
conectado a su cuenta de Google y a "Permitir aplicaciones menos
seguras". Vea la captura de pantalla a continuación.



Seguiremos los siguientes pasos para lograr este proceso:
- Crear un objeto SMTP para la conexión al servidor.
- Ingrese a su cuenta.
- Defina los encabezados de sus mensajes y las credenciales de inicio de sesión.
- Cree un objeto de mensaje
MIMEMultiparty adjunte los encabezados correspondientes, es decir, desde, hasta y Asunto. - Adjunte el mensaje al mensaje objeto
MIMEMultipart. - Finalmente, envíe el mensaje.
Este proceso es tan simple como se muestra a continuación.
1 |
# import necessary packages
|
2 |
|
3 |
from email.mime.multipart import MIMEMultipart |
4 |
from email.mime.text import MIMEText |
5 |
import smtplib |
6 |
|
7 |
# create message object instance
|
8 |
msg = MIMEMultipart() |
9 |
|
10 |
|
11 |
message = "Thank you" |
12 |
|
13 |
# setup the parameters of the message
|
14 |
password = "your_password" |
15 |
msg['From'] = "your_address" |
16 |
msg['To'] = "to_address" |
17 |
msg['Subject'] = "Subscription" |
18 |
|
19 |
# add in the message body
|
20 |
msg.attach(MIMEText(message, 'plain')) |
21 |
|
22 |
#create server
|
23 |
server = smtplib.SMTP('smtp.gmail.com: 587') |
24 |
|
25 |
server.starttls() |
26 |
|
27 |
# Login Credentials for sending the mail
|
28 |
server.login(msg['From'], password) |
29 |
|
30 |
|
31 |
# send the message via the server.
|
32 |
server.sendmail(msg['From'], msg['To'], msg.as_string()) |
33 |
|
34 |
server.quit() |
35 |
|
36 |
print "successfully sent email to %s:" % (msg['To']) |
Tenga en cuenta que las direcciones 'Para' y 'De' deben incluirse explícitamente en los encabezados de los mensajes.
Crear y enviar un correo electrónico con un archivo adjunto
En este ejemplo, vamos a enviar un correo electrónico con un archivo adjunto de imagen. El proceso es similar al envío de un correo electrónico de texto sin formato.
- Crea un objeto SMTP para la conexión al servidor.
- Ingrese a su cuenta.
- Defina los encabezados de sus mensajes y las credenciales de inicio de sesión.
- Cree un objeto de mensaje
MIMEMultiparty adjunte los encabezados correspondientes, es decir, desde, hasta y Asunto. - Lea y adjunte la imagen al mensaje objeto
MIMEMultipart. - Finalmente, envíe el mensaje.
1 |
# send_attachment.py
|
2 |
# import necessary packages
|
3 |
from email.mime.multipart import MIMEMultipart |
4 |
from email.MIMEImage import MIMEImage |
5 |
from email.mime.text import MIMEText |
6 |
import smtplib |
7 |
|
8 |
# create message object instance
|
9 |
msg = MIMEMultipart() |
10 |
|
11 |
|
12 |
# setup the parameters of the message
|
13 |
password = "your_password" |
14 |
msg['From'] = "your_address" |
15 |
msg['To'] = "to_address" |
16 |
msg['Subject'] = "Photos" |
17 |
|
18 |
# attach image to message body
|
19 |
msg.attach(MIMEImage(file("google.jpg").read())) |
20 |
|
21 |
|
22 |
# create server
|
23 |
server = smtplib.SMTP('smtp.gmail.com: 587') |
24 |
|
25 |
server.starttls() |
26 |
|
27 |
# Login Credentials for sending the mail
|
28 |
server.login(msg['From'], password) |
29 |
|
30 |
|
31 |
# send the message via the server.
|
32 |
server.sendmail(msg['From'], msg['To'], msg.as_string()) |
33 |
|
34 |
server.quit() |
35 |
|
36 |
print "successfully sent email to %s:" % (msg['To']) |
37 |
La clase MIMEImage es una subclase de MIMENonMultipart que se utiliza para crear objetos de mensaje MIME de tipos de imagen. Otras clases disponibles incluyen MIMEMessage y MIMEAudio.
Crear y enviar correos electrónicos HTML
Lo primero que vamos a hacer es crear una plantilla de correo electrónico HTML.
Crear una plantilla HTML
Aquí está el código HTML para la plantilla, y contiene dos columnas de tabla, cada una con una imagen y contenido de vista previa. Si prefiere una solución profesional ya preparada, obtenga nuestras mejores plantillas de correo electrónico. Tenemos una serie de opciones receptivas con características fáciles de personalizar para comenzar.
1 |
<html>
|
2 |
<head>
|
3 |
|
4 |
<title>Tutsplus Email Newsletter</title> |
5 |
<style type="text/css"> |
6 |
a {color: #d80a3e;} |
7 |
body, #header h1, #header h2, p {margin: 0; padding: 0;} |
8 |
#main {border: 1px solid #cfcece;} |
9 |
img {display: block;} |
10 |
#top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; } |
11 |
#header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; } |
12 |
#header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px; } |
13 |
h5 {margin: 0 0 0.8em 0;} |
14 |
h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; } |
15 |
p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;} |
16 |
</style>
|
17 |
</head>
|
18 |
<body>
|
19 |
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td> |
20 |
<table id="top-message" cellpadding="20" cellspacing="0" width="600" align="center"> |
21 |
<tr>
|
22 |
<td align="center"> |
23 |
<p><a href="#">View in Browser</a></p> |
24 |
</td>
|
25 |
</tr>
|
26 |
</table>
|
27 |
|
28 |
<table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff"> |
29 |
<tr>
|
30 |
<td>
|
31 |
<table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9"> |
32 |
<tr>
|
33 |
<td width="570" align="center" bgcolor="#d80a3e"><h1>Evanto Limited</h1></td> |
34 |
</tr>
|
35 |
<tr>
|
36 |
<td width="570" align="right" bgcolor="#d80a3e"><p>November 2017</p></td> |
37 |
</tr>
|
38 |
</table>
|
39 |
</td>
|
40 |
</tr>
|
41 |
|
42 |
<tr>
|
43 |
<td>
|
44 |
<table id="content-3" cellpadding="0" cellspacing="0" align="center"> |
45 |
<tr>
|
46 |
<td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;"> |
47 |
<img src="https://thumbsplus.tutsplus.com/uploads/users/30/posts/29520/preview_image/pre.png" width="250" height="150" /> |
48 |
</td>
|
49 |
<td width="15"></td> |
50 |
<td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;"> |
51 |
<img src="https://cms-assets.tutsplus.com/uploads/users/30/posts/29642/preview_image/vue-2.png" width ="250" height="150" /> |
52 |
</td>
|
53 |
</tr>
|
54 |
</table>
|
55 |
</td>
|
56 |
</tr>
|
57 |
<tr>
|
58 |
<td>
|
59 |
<table id="content-4" cellpadding="0" cellspacing="0" align="center"> |
60 |
<tr>
|
61 |
<td width="200" valign="top"> |
62 |
<h5>How to Get Up and Running With Vue</h5> |
63 |
<p>In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we’ll learn how to get Vue up..</p> |
64 |
</td>
|
65 |
<td width="15"></td> |
66 |
<td width="200" valign="top"> |
67 |
<h5>Introducing Haiku: Design and Create Motion</h5> |
68 |
<p>With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..</p> |
69 |
</td>
|
70 |
</tr>
|
71 |
</table>
|
72 |
</td>
|
73 |
</tr>
|
74 |
</table>
|
75 |
<table id="bottom" cellpadding="20" cellspacing="0" width="600" align="center"> |
76 |
<tr>
|
77 |
<td align="center"> |
78 |
<p>Design better experiences for web & mobile</p> |
79 |
<p><a href="#">Unsubscribe</a> | <a href="#">Tweet</a> | <a href="#">View in Browser</a></p> |
80 |
</td>
|
81 |
</tr>
|
82 |
</table><!-- top message --> |
83 |
</td></tr></table><!-- wrapper --> |
84 |
|
85 |
</body>
|
86 |
</html>
|
La plantilla finalmente se verá así cuando se complete:



A continuación se muestra la secuencia de comandos para enviar un correo electrónico con contenido HTML. El contenido de la plantilla será nuestro mensaje de correo electrónico.
1 |
import smtplib |
2 |
import email.message |
3 |
server = smtplib.SMTP('smtp.gmail.com:587') |
4 |
|
5 |
email_content = """ |
6 |
<html>
|
7 |
|
8 |
<head>
|
9 |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
10 |
|
11 |
<title>Tutsplus Email Newsletter</title>
|
12 |
<style type="text/css">
|
13 |
a {color: #d80a3e;}
|
14 |
body, #header h1, #header h2, p {margin: 0; padding: 0;}
|
15 |
#main {border: 1px solid #cfcece;}
|
16 |
img {display: block;}
|
17 |
#top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; }
|
18 |
#header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; }
|
19 |
#header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px; }
|
20 |
h5 {margin: 0 0 0.8em 0;}
|
21 |
h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; }
|
22 |
p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;}
|
23 |
</style>
|
24 |
</head>
|
25 |
|
26 |
<body>
|
27 |
|
28 |
|
29 |
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td>
|
30 |
<table id="top-message" cellpadding="20" cellspacing="0" width="600" align="center">
|
31 |
<tr>
|
32 |
<td align="center">
|
33 |
<p><a href="#">View in Browser</a></p>
|
34 |
</td>
|
35 |
</tr>
|
36 |
</table>
|
37 |
|
38 |
<table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff">
|
39 |
<tr>
|
40 |
<td>
|
41 |
<table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9">
|
42 |
<tr>
|
43 |
<td width="570" align="center" bgcolor="#d80a3e"><h1>Evanto Limited</h1></td>
|
44 |
</tr>
|
45 |
<tr>
|
46 |
<td width="570" align="right" bgcolor="#d80a3e"><p>November 2017</p></td>
|
47 |
</tr>
|
48 |
</table>
|
49 |
</td>
|
50 |
</tr>
|
51 |
|
52 |
<tr>
|
53 |
<td>
|
54 |
<table id="content-3" cellpadding="0" cellspacing="0" align="center">
|
55 |
<tr>
|
56 |
<td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;">
|
57 |
<img src="https://thumbsplus.tutsplus.com/uploads/users/30/posts/29520/preview_image/pre.png" width="250" height="150" />
|
58 |
</td>
|
59 |
<td width="15"></td>
|
60 |
<td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;">
|
61 |
<img src="https://cms-assets.tutsplus.com/uploads/users/30/posts/29642/preview_image/vue-2.png" width ="250" height="150" />
|
62 |
</td>
|
63 |
</tr>
|
64 |
</table>
|
65 |
</td>
|
66 |
</tr>
|
67 |
<tr>
|
68 |
<td>
|
69 |
<table id="content-4" cellpadding="0" cellspacing="0" align="center">
|
70 |
<tr>
|
71 |
<td width="200" valign="top">
|
72 |
<h5>How to Get Up and Running With Vue</h5>
|
73 |
<p>In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we will learn how to get Vue up..</p>
|
74 |
</td>
|
75 |
<td width="15"></td>
|
76 |
<td width="200" valign="top">
|
77 |
<h5>Introducing Haiku: Design and Create Motion</h5>
|
78 |
<p>With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..</p>
|
79 |
</td>
|
80 |
</tr>
|
81 |
</table>
|
82 |
</td>
|
83 |
</tr>
|
84 |
|
85 |
|
86 |
</table>
|
87 |
<table id="bottom" cellpadding="20" cellspacing="0" width="600" align="center">
|
88 |
<tr>
|
89 |
<td align="center">
|
90 |
<p>Design better experiences for web & mobile</p>
|
91 |
<p><a href="#">Unsubscribe</a> | <a href="#">Tweet</a> | <a href="#">View in Browser</a></p>
|
92 |
</td>
|
93 |
</tr>
|
94 |
</table><!-- top message -->
|
95 |
</td></tr></table><!-- wrapper -->
|
96 |
|
97 |
</body>
|
98 |
</html>
|
99 |
|
100 |
|
101 |
"""
|
102 |
|
103 |
msg = email.message.Message() |
104 |
msg['Subject'] = 'Tutsplus Newsletter' |
105 |
|
106 |
|
107 |
msg['From'] = 'youraddress' |
108 |
msg['To'] = 'to_address' |
109 |
password = "yourpassword" |
110 |
msg.add_header('Content-Type', 'text/html') |
111 |
msg.set_payload(email_content) |
112 |
|
113 |
s = smtplib.SMTP('smtp.gmail.com: 587') |
114 |
s.starttls() |
115 |
|
116 |
# Login Credentials for sending the mail
|
117 |
s.login(msg['From'], password) |
118 |
|
119 |
s.sendmail(msg['From'], [msg['To']], msg.as_string()) |
Ejecute su código, y si no ocurre ningún error, entonces el correo electrónico fue exitoso. Ahora vaya a su bandeja de entrada y debería ver su correo electrónico como contenido HTML muy bien formateado.



Conclusión
Este tutorial ha cubierto la mayor parte de lo que se necesita para enviar correos electrónicos para su aplicación. Hay varias API disponibles para enviar correos electrónicos, por lo que no tiene que empezar desde cero, p.e. SendGrid, pero también es importante entender lo básico. Para obtener más información, visite los documentos de Python.
Además, no dude
en ver lo que tenemos disponible para la venta y para el estudio en
Envato Market, y por favor haga todas las preguntas y brinde sus
valiosos comentarios utilizando el feed mostrado anteriormente.



