UnicodeEncodeError: 'ascii' codec can't encode character ... when sending email

UnicodeEncodeError: 'ascii' codec can't encode character ... when sending email

我正在构建土耳其 (Hepsiburada) 价格跟踪器的电子商务网站之一。当价格低于您的买入价时,程序会发送一封电子邮件。

不幸的是,在执行程序时我遇到了这个错误。

msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 72: ordinal not in range(128)

这是我的全部代码。

import requests
import lxml
from bs4 import BeautifulSoup
import smtplib


# Hepsiburada Product URL (You can change the product which you want to buy.)
PRODUCT_URL = ""
BUY_PRICE = 3000  # Type buy price in Turkish Lira (TRY).

# Edit this section with your own information.

YOUR_SMTP_ADDRESS = ""
YOUR_EMAIL = ""
YOUR_PASSWORD = ""

# Head over to (http://myhttpheader.com) and replace your "User-Agent" and "Accept-Language".
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15",
    "Accept-Language": "en-GB,en;q=0.9"
}

response = requests.get(url=PRODUCT_URL, headers=headers)

soup = BeautifulSoup(response.content, "lxml")

price = soup.find(id="offering-price").get_text()
# price_without_currency = price.split(",")[0]
#
# price_as_float = float(price)

title = soup.find(class_="product-name").get_text().strip()

# When product goes on sale and the price below to your BUY_PRICE, it sends an E-Mail to you.

if price:
    message = f"{title} is now {price}"
    print(message)

    with smtplib.SMTP(YOUR_SMTP_ADDRESS, port=587) as connection:
        connection.starttls()
        result = connection.login(user=YOUR_EMAIL, password=YOUR_PASSWORD)
        connection.sendmail(
            from_addr=YOUR_EMAIL,
            to_addrs=YOUR_EMAIL,
            msg=f"Subject:Hepsiburada Price Alert!\n\n{message}\n{PRODUCT_URL}"
        )

你能帮帮我吗?我卡在哪里了?

SMTP 要求输入消息是有效的 RFC5322(née RFC822)消息。您可以使用非常简单的 US-ASCII 字符串手动执行此操作,但正确的解决方案是使用 email 模块来 assemble smtplib 的有效消息。这负责正确格式化和封装任何有问题的内容(包括但不限于旧的 7 位 US-ASCII 字符集之外的字符、长度超过大约 1000 个字符的行、二进制有效负载等)。

from email.message import EmailMessage

...
if price:
    email = EmailMessage()
    email['from'] = YOUR_EMAIL
    email['to'] = YOUR_EMAIL
    email['subject'] = 'Hepsiburada Price Alert!'
    email.set_content(f"{title} is now {price}\n{PRODUCT_URL}")

    with smtplib.SMTP(YOUR_SMTP_ADDRESS, port=587) as connection:
        # some servers require ehlo() here
        connection.starttls()
        # some servers even require a second ehlo() here
        connection.login(user=YOUR_EMAIL, password=YOUR_PASSWORD)
        connection.send_message(email)

您会注意到,这基本上是 email examples documentation 中标准示例的 copy/paste。许多在线示例记录了一个较旧的 email.Message API,它在 Python 3.6 之前是标准的,但现在应该避免用于任何新代码。