Python Forum

Full Version: Sending Emails in Portuguese
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've been having problems with the body of my Email, when I write something in portuguese with special characters like : "ç" , my code returns an error .
import openpyxl
import smtplib

# Read Excel file
arquivo = openpyxl.load_workbook('C:\\Users\\-\\Documents\\PlanilhasExcel\\AutomatizandoPagamento.xlsx')
planilha = arquivo['Planilha1']
ultima_col = planilha.max_column
ultimo_mes = planilha.cell(row=1, column=ultima_col).value

# Check the status of the payment
sem_pagar = {}
for r in range(2, planilha.max_row + 1):
    pagamento = planilha.cell(row=r, column=ultima_col).value
    if pagamento != 'pago':
        nome = planilha.cell(row=r, column=1).value
        email = planilha.cell(row=r, column=2).value
        sem_pagar[nome] = email

# Sending Emails
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
print('What's your password ?')
smtpObj.login('MY_email', password=input())

# Body of the email
for nome, email in sem_pagar.items():
    body = "Subject: %s due unpaid.\nDear %s,\nRecords show that you have not paid dues for %s. Please make this payment as soon as possible. Thank you!" % (ultimo_mes, nome, ultimo_mes)
    print('Enviando para %s...' % email)

    enviarmail_status = smtpObj.sendmail('My_Email', email, body)
    if enviarmail_status != {}:
        print('Teve um problema em enviar o email para %s: %s' % (email, enviarmail_status))
smtpObj.quit()
Error:
msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character '\xe3' in position 16: ordinal not in range(128)
How Can I change my code for UTF-8 ?
I stole the example from here: https://docs.python.org/3/library/email.examples.html
Looks like it will base64 encode the message if it needs to, so that it's just sending ascii. Hopefully this helps.

>>> import smtplib
>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg.set_content("ç - testing - ç")
>>> msg["Subject"] = "email test"
>>> msg['From'] = "[email protected]"
>>> msg['To'] = "[email protected]"
>>> msg.as_string()
'Content-Type: text/plain; charset="utf-8"\nContent-Transfer-Encoding: base64\nMIME-Version: 1.0\nSubject: email test\nFrom: [email protected]\nTo: [email protected]\n\nw6cgLSB0ZXN0aW5nIC0gw6cK\n'
>>> s = smtplib.SMTP('localhost') #or wherever
>>> s.send_message(msg)
>>> s.quit()