Search code examples
pythonlistemailsmtplib

How to automate the sending of e-mail by Python, with content that contains list?


In Python3 I want to automate the sending of emails, such as using smtplib

I did so:

import smtplib
from datetime import datetime

now = datetime.now()
dia_hoje = now.strftime("%d")
mes_hoje = now.strftime("%m")
ano_hoje = now.strftime("%Y")

gmail_user = 'user'
gmail_password = 'password'

sent_from = gmail_user
to = ['address1', 'address2']

# Example of list text I will send
lista = ['SENADO: PLS 00205/2015, de autoria de Paulo Paim, fala sobre jornalistas e sofreu alterações em sua tramitação. Tramitação: Comissão de Assuntos Sociais. Situação: AGUARDANDO DESIGNAÇÃO DO RELATOR. http://legis.senado.leg.br/sdleg-getter/documento?dm=584243']

# I create the subject from today's date
subject = str(dia_hoje) + "/" + str(mes_hoje) + "/" + str(ano_hoje) + " Tramitações de interesse do jornalismo no Congresso"

# Creates the message body, with standard text and list content
body = "Olá seres humanos!\nEu sou um robô que vasculha a API da Câmara e do Senado em busca de proosicoes de interesse dos jornalistas.\nVeja as que tiveram alguma tramitação hoje.\n" + '\n'.join(lista)+ "\n Para mais detalhes consulte meu mestre: XXX"

email_text = """\
  From: %s
  To: %s
  Subject: %s

  %s
  """ % (sent_from, ", ".join(to), subject, body)  

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print ('Email sent!')
except:
    print ('Something went wrong...')

But this code does not send the email. I have the message "Something went wrong ..."

With a normal message, only text without lists, it works. But when I put a list on the body, the error appears

Please, does anyone know a better strategy I could use to solve this?

Here a body print:

print(body)        

Olá seres humanos!                                                              
Eu sou um robô que vasculha a API da Câmara e do Senado em busca de proosicoes de interesse dos jornalistas.
Veja as que tiveram alguma tramitação hoje.
SENADO: PLS 00205/2015, de autoria de Paulo Paim, fala sobre jornalistas e sofreu alterações em sua tramitação. Tramitação: Comissão de Assuntos Sociais. Situação: AGUARDANDO DESIGNAÇÃO DO RELATOR. http://legis.senado.leg.br/sdleg-getter/documento?dm=584243
 Para mais detalhes consulte meu mestre: XXX

Here a email_text:

From: XXX@gmail.com                                                
  To: XXX@gmail.com, XXX@abraji.org.br
  Subject: 10/03/2020 Tramitações de interesse do jornalismo no Congresso

  Olá seres humanos!
Eu sou um robô que vasculha a API da Câmara e do Senado em busca de proosicoes de interesse dos jornalistas.
Veja as que tiveram alguma tramitação hoje.
SENADO: PLS 00205/2015, de autoria de Paulo Paim, fala sobre jornalistas e sofreu alterações em sua tramitação. Tramitação: Comissão de Assuntos Sociais. Situação: AGUARDANDO DESIGNAÇÃO DO RELATOR. http://legis.senado.leg.br/sdleg-getter/documento?dm=584243
 Para mais detalhes consulte meu mestre: XXX

Solution

  • If you remove the try-except you will get this error:

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 69-70: ordinal not in range(128)
    

    To solve this issue use the following command to fix your email_text:

    email_text = email_text.encode('ascii', 'ignore').decode('ascii')
    

    I guse this will remove some non-ascii characters from your text. For attidional methods you can look in this quastion.

    Edit: The first section is answering the OP quastion, but for sack of compliation here is a better way on sending emails using python script:

    recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
    msg = MIMEMultipart()
    msg['From'] = "Can be any string you want, use ASCII chars only " # sender name
    msg['To'] = ", ".join(recipients) # for one recipient just enter a valid email address
    msg['Subject'] = "Subject"
    body = "message body"
    msg.attach(MIMEText(body, 'plain'))
    
    server = smtplib.SMTP('smtp.gmail.com', 587)  # put your relevant SMTP here
    
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('jhon@gmail.com', '1234567890')  # use your real gmail account user name and password
    server.send_message(msg)
    server.quit()
    

    Hope this is helpfull!