Skip to content

Instantly share code, notes, and snippets.

@gabriellopesdesouza2002
Last active January 20, 2023 01:11
Show Gist options
  • Save gabriellopesdesouza2002/aee524893ea910c2dfe62b5a082c11dc to your computer and use it in GitHub Desktop.
Save gabriellopesdesouza2002/aee524893ea910c2dfe62b5a082c11dc to your computer and use it in GitHub Desktop.
Função para enviar um e-mail no Google Gmail
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
import smtplib
def extrair_email(text: str) -> list:
"""### Retorna os e-mails recuperados
Validação / Busca de e-mails com o padrão RFC2822
https://regexr.com/2rhq7
Args:
text (str): Texto com o(s) email(s)
Returns:
list: email(s)
"""
email = re.findall("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", text, )
if not email or len(email) == 0:
email = []
return email
def envia_email_gmail(
email_app_google: str,
passwd_app_gmail: str,
emails_to: str|tuple|list,
assunto: str,
body_msg,
anexos: tuple|list|bool = False,
):
"""Função para enviar um e-mail completo no Google Gmail
### Primeiramente, verifique se o email que enviará está configurado.
Se não, siga o passo-a-passo abaixo para configurar o e-mail.
### Passo-a-passo para ativar envio de e-mails no Gmail
1- Ative a verificação por duas etapas no Gmail: https://myaccount.google.com/signinoptions/two-step-verification
2- Vá para esse link para criar uma senha de app: https://myaccount.google.com/apppasswords
2a - Selecione App, E-mail
2b - Selecione dispositivo, Outro (nome personalizado)
2c - Capture a senha para adicionar na função.
### Dica para utilização de um body:
Utilize template:
file: template.html:
<!DOCTYPE html>
<html>
<body>
<p>Olá <strong>$nome_placeholder</strong>, hoje é <strong>$data_placeholder</strong>.</p>
</body>
</html>
>>> from string import Template
>>> with open('template.html', 'r', encoding='utf-8') as html:
>>> template = Template(html.read())
>>> nome = 'Nome'
>>> data_atual = datetime.now().strftime('%d/%m/%Y')
>>> body_msg = template.substitute(nome_placeholder=nome, data_placeholder=data_atual)
Args:
email_app_google (str): E-mail que enviará para os destinatários, (emails_to)
passwd_app_gmail (str): Passwd do E-mail que enviará para os destinatários, (emails_to)
emails_to (str|tuple|list): Destinatário(s)
assunto (str): Assunto do E-mail
body_msg (str): Corpo do E-mail
anexos (tuple | list | bool): Anexos, optional, default = False
"""
msg = MIMEMultipart()
# para quem está indo a msg
if isinstance(emails_to, str):
emails_to = extrair_email(emails_to)
if len(emails_to) == 0:
print(f'Não foi possível compreender o e-mail enviado: {emails_to}')
return
emails_to = ';'.join(emails_to)
msg['to'] = emails_to
# assunto
msg['subject'] = assunto
# corpo
body = MIMEText(body_msg, 'html')
msg.attach(body)
# insere_os_anexos
if isinstance(anexos, (tuple, list)):
for anexo in anexos:
anexo_abspath = os.path.abspath(anexo)
part = MIMEBase('application', "octet-stream")
part.set_payload(open(anexo_abspath, "rb").read())
encoders.encode_base64(part)
file_name = anexo_abspath.split("\\")[-1]
print(f'Recuperando anexo: {file_name}')
part.add_header(f'Content-Disposition', f'attachment; filename={file_name}')
msg.attach(part)
elif isinstance(anexos, str):
anexo_abspath = os.path.abspath(anexos)
part = MIMEBase('application', "octet-stream")
part.set_payload(open(anexo_abspath, "rb").read())
encoders.encode_base64(part)
file_name = anexo_abspath.split("\\")[-1]
print(f'Recuperando anexo: {file_name}')
part.add_header('Content-Disposition', f'attachment; filename={file_name}')
msg.attach(part)
# abre conexao com smtp
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
smtp.ehlo()
smtp.starttls()
try:
smtp.login(email_app_google, passwd_app_gmail)
except smtplib.SMTPAuthenticationError as e:
print(f'E-mail não enviado:\n\tUsuário ou senha inválido!\n\n{e.smtp_error}')
return
smtp.send_message(msg)
print('E-mail enviado com sucesso!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment