0

I need help. I'm having problems to send emails using smtplib in python... it says "UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 21: ordinal not in range(128)"

There are old threads on similar topics but after several days I couldn't figure it out.

[EDIT: I tried using .encode("utf-8") for the message as in here and it gets sent, but the email is sent with strange symbols. So I dont count that as a solution]

I attach an image of the error as well as my code.

import datetime as dt
import smtplib
import pandas
import random


def send_email(recipient, message):
    my_email = "askirz.unsafe@gmail.com"
    with smtplib.SMTP("smtp.gmail.com") as connection:
        connection.starttls()
        connection.login(user=my_email, password="sbbmhzldpfjukuws")
        print(message)
        connection.sendmail(
            from_addr=my_email,
            to_addrs=recipient,
            msg=message
        )


birthdays_df = pandas.read_csv("birthdays.csv")
today = dt.datetime.now()

this_months_birthdays = birthdays_df[birthdays_df['month'] == today.month]
todays_birthdays = this_months_birthdays[this_months_birthdays["day"] == today.day]
for i in range(len(todays_birthdays.index)):
    with open(f"./letter_templates/letter_{random.randint(1,3)}.txt") as letter_file:
        letter_insert_name = letter_file.read().split("[NAME]")
        letter = letter_insert_name[0] + todays_birthdays.loc[i].at["name"] + letter_insert_name[1]
        letter_insert_gender = letter.split("[GENDER]")
        if len(letter_insert_gender) > 1:
            letter = letter_insert_gender[0] + todays_birthdays.loc[i].at["gender"] + letter_insert_gender[1]
        print(letter)
        message = f"Subject:Feliz cumpleaños!!\n\n {letter}"
        recipient = todays_birthdays.loc[i].at["email"]
        send_email(recipient=recipient, message=message)

capture of the error

Monero1ro
  • 1
  • 1
  • Does this answer your question? [Issue with smtplib sending mail with unicode characters in Python 3.1](https://stackoverflow.com/questions/8329741/issue-with-smtplib-sending-mail-with-unicode-characters-in-python-3-1) – chrslg Oct 11 '22 at 10:34
  • I tried using .encode("utf-8") for the message and it gets sent, but the email is sent with strange symbols. So I don't count that as a solution – Monero1ro Oct 11 '22 at 11:18
  • The argument to `sendmail` needs to be a properly formatted RFC5322 message, not a random string. – tripleee Oct 11 '22 at 11:25
  • I don't think it is an encoding problem. Well, it might be, depending on what is your message. But here your message is in the code. You seem to use python3, and unless you omitted some encoding declaration, python3 code is considered to be utf8. – chrslg Oct 11 '22 at 11:26
  • So the solution I've shown is not about encoding the text. It is about declaring its encoding in the email meta-data. Formatting the email content, with headers and text. – chrslg Oct 11 '22 at 11:27

0 Answers0