0

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
Reinaldo Chaves
  • 965
  • 4
  • 16
  • 43

1 Answers1

3

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!

DavidDr90
  • 559
  • 5
  • 20
  • Thanks @DavidDR . Now the e-mail has been sent, but the problem is that the Subject is gone, left blank. And all the accents of the text are also gone – Reinaldo Chaves Mar 10 '20 at 18:41
  • @ReinaldoChaves I just edit my answer... there is other method on fixing the ascii problem, please look at the link I add and see if some other method is good for you... – DavidDr90 Mar 10 '20 at 18:42
  • @ReinaldoChaves BTW the `encode` function is not the problem. Try and remove all non-ascii characters from the subject and body and send the mail and see that the subject is empty. You have something else in your code that not working right... – DavidDr90 Mar 10 '20 at 18:54
  • 2
    @ReinaldoChaves I edit my answer with more information about how to send email using python. Enjoy! – DavidDr90 Mar 10 '20 at 19:13
  • Thanks @DavidDR But encoding is really a problem, do not send (TypeError: 'utf8' is an invalid keyword argument for Compat32). I'll try to use the unidecode to remove the accents – Reinaldo Chaves Mar 10 '20 at 19:25
  • body_0 = "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)+ "\nPara mais detalhes consulte meu mestre: reinaldo@abraji.org.br" -> body = unidecode.unidecode(body_0) – Reinaldo Chaves Mar 10 '20 at 19:29
  • Hi @DavidDR I did this above to remove the accents. But when I send the email it appears: TypeError: 'utf8' is an invalid keyword argument for Compat32 – Reinaldo Chaves Mar 10 '20 at 19:30
  • 1
    @ReinaldoChaves did you use the method I add on the `edit` section? – DavidDr90 Mar 10 '20 at 20:26
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209399/discussion-between-daviddr-and-reinaldo-chaves). – DavidDr90 Mar 10 '20 at 20:27