() translation by (you can also view the original English article)
Este tutorial vai te dar uma introdução sobre o SMTP, um módulo Python utilizado para enviar email. Também será demonstrado como enviar diferentes tipos de e-mails, como e-mails simples de texto, e-mails com anexo, e e-mails com conteúdo HTML.
Introdução ao SMTP
O "Simple Mail Transfer Protocol (SMTP) - ou, em tradução livre: Protocolo Simples de Transferência de Correspondência" - lida com o envio e direcionamento de e-mails entre servidores.
Em Python, o módulo smtplib
define um objeto de sessão de cliente SMTP que pode ser utilizado para enviar e-mail para toda máquina conectada à Internet que possua um serviço de processamento SMTP ou ESMTP.
Aqui está como criar um objeto SMTP
1 |
import smtplib |
2 |
|
3 |
server = smtplib.SMTP(host='host_address',port=your_port) |
Criar e enviar um E-mail Simples
O código a seguir vai te permitir enviar um e-mail via o servidor SMTP do Gmail. Entretanto, o Google, à princípio, não vai te permitir realizar o login via smtplib
porque ele considera esse tipo de conexão "menos segura". Para resolver isso, vá em https://www.google.com/settings/security/lesssecureapps enquanto estiver logado na sua conta Google, e mude para "ON" a oção de "Allow less secure apps". Veja a imagem abaixo.



Nós vamos seguir os próximas passos a fim realizar essa tarefa:
- Criar um objeto SMTP para conexão com o servidor.
- Realizar o login na sua conta.
- Definir o cabeçalho da sua mensagem e as suas credenciais para a realização do login.
- Criar um objeto
MIMEMultipart
e associar a ele o cabeçalho relevante - exemplo: De:, Para:, e Assunto. - Associar uma mensagem ao objeto de mensagem
MIMEMultipart
. - Finalmente, enviar a mensagem.
O processo é tão simples como é mostrado abaixo.
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']) |
Note que os endereços de 'To' ('Para:') e 'From' ('De:') devem ser incluídos explicitamente no cabeçalho da mensagem.
Criar e Enviar um E-mail com Anexo
Nesse exemplo, nós vamos enviar um e-mail com uma imagem em anexo. O processo é similar ao envio de e-mail simples.
- Criar um objeto SMTP para conexão com o servidor.
- Realizar o login na sua conta.
- Definir o cabeçalho da sua mensagem e as suas credenciais para a realização do login.
- Criar um objeto
MIMEMultipart
e associar a ele o cabeçalho relevante - exemplo: De:, Para:, e Assunto. - Ler e anexar a imagem à mensagem através do objeto
MIMEMultipart
. - Finalmente, enviar a mensagem.
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 |
A classe MIMEImage
é uma subclasse de MIMENonMultipart
que é utilizada para criar objetos MIME do tipo imagem. Outras classes disponíveis incluem MIMEMessage
e MIMEAudio
.
Criar e Enviar E-mails HTML
A primeira coisa que nós vamos fazer é criar um template HTML.
Criar um Template HTML
Aqui está um código HTML para um template, e ele contem uma tabela de duas colunas com uma imagem e prévia do conteúdo em cada uma delas. Se você preferir um template profissional já pronto, escolha um dos nossos melhores templates de e-mail. Nós temos várias opções com design responsivo e de fácil customização para você começar a utilizar.
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>
|
O template vai parecer com algo assim quando estiver pronto:



Abaixo está o código para enviar um e-mail com conteúdo HTML. O conteúdo do template vai estar na nossa mensagem do e-mail.
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()) |
Execute o seu código, e se não houver erros, então o e-mail terá sido enviado com sucesso. Agora vá para a sua caixa de entrada e você deve vê-lo lá, com o conteúdo HTML bem formatado.



Conclusão
Esse tutorial cobriu a maior parte do que é preciso saber para enviar e-mails nas suas aplicações. Existem várias APIs disponíveis para enviar e-mail, por isso, você não precisa começar do zero - exemplo: SendGrid, mas também é importante conhecer a base. Para mais informações, visite a Documentação do Python.
Por último, não exite em conferir o que nós temos disponível para venda e para estudo na Envato Market, e por favor, envie qualquer dúvida e dê seu feedback utilizando a seção abaixo.