0

i am just reading some quotes from file and sending them on my email using python but i am constantly facing this (UnicodeEncodeError: 'ascii' codec can't encode character '\u201c' in position 37: ordinal not in range(128)) error how can i fix it.

Here is the code

now = dt.datetime.now()
weekdays = now.weekday()

if weekdays == 5:
    with open("quotes.txt","r", encoding="utf8") as quote_file:
        all_quotes = quote_file.readlines()
        quote = random.choice(all_quotes)

    print(quote)

    with smtplib.SMTP("smtp.mail.yahoo.com") as connection:
        connection.starttls()
        connection.login(user=my_email, password=my_password)
        connection.sendmail(from_addr=my_email,
                            to_addrs=my_email,
                            msg=f"Subject:Monday Motivational Quote\n\n{quote}")

Thanks in advance.

zik
  • 31
  • 5
  • msg=f"Subject:Monday Motivational Quote\n\n{quote}".encode("utf8") use .encode() method in the last line – SKJ Dec 31 '21 at 11:07

1 Answers1

1

I believe you're doing Angela Yu's course. The only way I was able to get this code to work is when I removed the "" and special characters from the "quotes.txt" file.

You can try it out by just removing it from the first sentence (or line), and then assign "quote" to all_quotes[0]. So this part of the code will look like this:

with open("quotes.txt") as quote_file:
    all_quotes = quote_file.readlines()
    quote = all_quotes[0]

Once you remove the special characters from every sentence, it will work with the random.choice too.

astqx
  • 2,058
  • 1
  • 10
  • 21