【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character ... when sending emailUnicodeEncodeError: 'ascii' codec can't encode character ... 发送电子邮件时
【发布时间】:2022-01-27 02:00:53
【问题描述】:

我正在构建土耳其 (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}"
        )

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

【问题讨论】:

  • 您的代码中没有任何内容调用_fix_eols,因此我们看不到哪个部分失败了。请edit 提供完整的回溯,最好还提供一些调试信息来识别有问题的字符串。正确的解决方案是使用EmailMessage 构造一个有效的MIME 消息;将随机字符串粘贴在一起仅适用于琐碎的 SMTP 消息。

标签: beautifulsoup smtp


【解决方案1】:

SMTP 要求输入消息是有效的 RFC5322(née RFC822)消息。您可以使用非常简单的 US-ASCII 字符串手动完成此操作,但正确的解决方案是使用email 模块为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 中标准示例的复制/粘贴。许多在线示例记录了一个较旧的email.Message API,它在 Python 3.6 之前是标准的,但现在应该避免用于任何新代码。

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 2018-08-14
    • 2014-05-09
    • 1970-01-01
    • 2022-01-20
    • 2019-07-18
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多