【发布时间】:2021-09-28 18:47:50
【问题描述】:
当我尝试将 Twitter 推文发送到电子邮件时,我收到一条错误消息。错误信息是:
UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 114: ordinal not in range(128)
我的代码如下:
# Python 3.9
import smtplib, requests
import datetime as datetime
# twitter api function (not shown) retrieves a series of tweets - these are added to a dictionary (below)
tweets = {'climate change': 'Eco1stArt - USATeam Animal rides to the rescue in nine-year-old Zac’s latest book about the climate change emergency #books - twitter short URL \ncaykahvekeyfi - istanbultwitter short URL\nMaura2e2_ - Killaloe Co. Clare????????Éire????????Politicians refusing to treat the #ClimateEmergency as an emergency are committing crimes against humanity.twitter short URL\n"}
# I cant show the actual twitter short URLs in teh tweet data -
# code to convert the dictionary into a formatted string
tweeter = ""
for k, v in tweets.items():
tweeter += f"\n{k}\n"
tweeter += f"{v}"
# code to build and send the email
subject = "Todays Tweets.."
email_address = "miles-s@hotmail.co.uk"
curr_date = get_date()
my_email = "email@email.com"
PW = "mypassword"
Gmail = "smtp.service.com"
with smtplib.SMTP("smtp.service.com", port=587) as connection:
connection.starttls() # decures the email message
connection.login(user=my_email, password = PW)
connection.sendmail(
from_addr=my_email,
to_addrs=email_address,
msg=f"Subject:{subject}\n\n{message}\n"
)
解决字符“\u2019”问题的任何建议。谢谢。
【问题讨论】:
-
您是否尝试在
sendmail的mail_options参数中使用SMTPUTF8? -
我也会试试这个选项。谢谢