From c65e6b57be297460ac4e810654cf3912d47c64ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Ot=C3=A1vio?= Date: Thu, 29 Dec 2022 08:40:34 -0300 Subject: [PATCH] Enviando E-mails SMTP com Python --- .env-example | 3 +++ aula185.html | 24 ++++++++++++++++++++++++ aula185.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 aula185.html create mode 100644 aula185.py diff --git a/.env-example b/.env-example index 9831f04..6c88291 100644 --- a/.env-example +++ b/.env-example @@ -2,3 +2,6 @@ BD_USER="CHANGE-ME" BD_PASSWORD="CHANGE-ME" BD_PORT=CHANGE-ME BD_HOST="CHANGE-ME" + +FROM_EMAIL="CHANGE-ME" +EMAIL_PASSWORD="CHANGE-ME" \ No newline at end of file diff --git a/aula185.html b/aula185.html new file mode 100644 index 0000000..ea2d63b --- /dev/null +++ b/aula185.html @@ -0,0 +1,24 @@ + + + + + + + Arquivo para o e-mail + + + Olá ${nome}, +
+ Estou testando + este e-mail + em HTML. +
+
+ + + Atenciosamente, +
+ Luiz Otávio. +
+ + diff --git a/aula185.py b/aula185.py new file mode 100644 index 0000000..57e62d9 --- /dev/null +++ b/aula185.py @@ -0,0 +1,47 @@ +# Enviando E-mails SMTP com Python +import os +import pathlib +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from string import Template + +from dotenv import load_dotenv # type: ignore + +load_dotenv() + +# Caminho arquivo HTML +CAMINHO_HTML = pathlib.Path(__file__).parent / 'aula185.html' + +# Dados do remetente e destinatário +remetente = os.getenv('FROM_EMAIL', '') +destinatario = remetente + +# Configurações SMTP +smtp_server = 'smtp.gmail.com' +smtp_port = 587 +smtp_username = os.getenv('FROM_EMAIL', '') +smtp_password = os.getenv('EMAIL_PASSWORD', '') + +# Mensagem de texto +with open(CAMINHO_HTML, 'r') as arquivo: + texto_arquivo = arquivo.read() + template = Template(texto_arquivo) + texto_email = template.substitute(nome='Helena') + +# Transformar nossa mensagem em MIMEMultipart +mime_multipart = MIMEMultipart() +mime_multipart['from'] = remetente +mime_multipart['to'] = destinatario +mime_multipart['subject'] = 'Este é o assunto do e-mail' + +corpo_email = MIMEText(texto_email, 'html', 'utf-8') +mime_multipart.attach(corpo_email) + +# Envia o e-mail +with smtplib.SMTP(smtp_server, smtp_port) as server: + server.ehlo() + server.starttls() + server.login(smtp_username, smtp_password) + server.send_message(mime_multipart) + print('E-mail enviado com sucesso!')