当使用SMTP发送电子邮件时,我会遇到编码问题。我检查了许多不同的帖子和方法来解决这个问题,但是没有什么对我有用。
这是我的代码,删除了所有个人信息:
import requests
import pandas as pd
import smtplib
import datetime
STOCK = "AAPL"
COMPANY = 'Apple'
TODAY = datetime.date.today()
MY_EMAIL =
PASSWORD =
RECEIVER =
API_KEY =
parameters = {
'function': 'TIME_SERIES_DAILY',
'symbol': STOCK,
'interval': '60min',
'apikey': API_KEY,
}
response = requests.get(url='https://www.alphavantage.co/query', params=parameters)
response.raise_for_status()
data = response.json()
stock_data = data['Time Series (Daily)']
today = list(stock_data.values())[0]
yesterday = list(stock_data.values())[1]
prices = [float(today['4. close']), float(yesterday['4. close'])]
price_series = pd.Series(prices)
perc_change = price_series.pct_change()[1]
API_KEY2 =
parameters2 = {
'apiKey': API_KEY2,
'q': COMPANY,
'searchIn': 'title',
'from': TODAY_DATE,
'totalResults': 3,
'language': 'en',
'sortBy': 'popularity',
'pageSize': 3,
'page': 1,
}
response2 = requests.get(url='https://newsapi.org/v2/everything', params=parameters2)
response2.raise_for_status()
data = response2.json()
article_data = data['articles']
articles = [article_data[num] for num in range(3)]
if perc_change > 0.025 or perc_change < 0.025:
if perc_change >= 0:
symbol = '▲'
else:
symbol = '▼'
subject = f'{STOCK}: {symbol} {round(perc_change, 3)}'
message = f'''
\033[1mAuthor\033[0m: {list(articles[0].values())[0]['name']}
\033[1mBrief\033[0m: {list(articles[0].values())[3]}\n
\033[1mAuthor\033[0m: {list(articles[1].values())[0]['name']}
\033[1mBrief\033[0m: {list(articles[1].values())[3]}\n
\033[1mAuthor\033[0m: {list(articles[2].values())[0]['name']}
\033[1mBrief\033[0m: {list(articles[2].values())[3]}
'''
with smtplib.SMTP('smtp.gmail.com') as connection:
connection.starttls()
connection.login(user=MY_EMAIL, password=PASSWORD)
connection.sendmail(from_addr=MY_EMAIL, to_addrs=RECEIVER, msg=f"Subject:{subject.encode('utf-8')}\n\n{message.encode('utf-8')}")这给了我迄今为止最好的结果:
msg=f"Subject:{subject.encode('utf-8')}\n\n{message.encode('utf-8')}"这就是这封电子邮件最终的样子:
Subject: b'AAPL: \xe2\x96\xbc-0.021'
Body: b"\n \x1b[1mHeadline\x1b[0m: The Verge\n \x1b[1mBrief\x1b[0m: Samsung just announced the Galaxy Watch 5 Pro for outdoor athletes and Apple is also expected to release a rugged version of the Apple Watch this fall. But smartwatches can\xe2\x80\x99t rely too heavily on touchscreens to win over athletes.\n\n \x1b[1mHeadline\x1b[0m: Ars Technica\n \x1b[1mBrief\x1b[0m: Dealmaster also has the Xbox Series S, Apple Watch Series 7, and Nvidia Shield TV.\n\n \x1b[1mHeadline\x1b[0m: Boing Boing\n \x1b[1mBrief\x1b[0m: One Strange Thing is a podcast that investigates unexplainable news stories. I began listening to it last night on Apple Podcasts, and ended up playing 5 episodes. You can listen to a selection of free episodes on the podcast's website, too. \xe2\x80\x94 Read the rest\n " 我做错了什么?我试过使用EmailMessage,Header,MIMEText等,我也尝试过发送到多个不同的电子邮件提供商,以防万一,这并没有改变任何事情。
发布于 2022-08-14 07:38:57
您需要对整个消息体进行编码,而不是对部分进行编码,然后将它们插入到字符串中。
例如,此代码(仅使用部分数据):
with smtplib.SMTP('localhost', 1025) as connection:
connection.sendmail(
from_addr=MY_EMAIL,
to_addrs=RECEIVER,
msg=f"Subject:{subject}\n\n{message}".encode('utf-8'),
) 在aiosmtpd调试服务器中生成此输出
---------- MESSAGE FOLLOWS ----------
Subject:APPL: ▲ 1.234
X-Peer: ('::1', 40952, 0, 0)
Author: The Verge
Brief: Samsung just announced the Galaxy Watch 5 Pro for outdoor athletes and Apple is also expected to release a rugged version of the Apple Watch this fall. But smartwatches can’t rely too heavily on touchscreens to win over athletes.
Author: Ars Technica
Brief: Dealmaster also has the Xbox Series S, Apple Watch Series 7, and Nvidia Shield TV.
------------ END MESSAGE ------------在我的终端中,“作者”和“简短”是粗体,因为输出在终端中,您的消息包括ANSI转义。但是你的电子邮件会在终端机上阅读吗?如果要在电子邮件中使用粗体格式,通常发送HTML电子邮件,如下所示:
from email.message import EmailMessage
import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = MY_EMAIL
msg['To'] = RECEIVER
# Create a plain text message (no formatting)
msg.set_content(
f"""\
Author: {name1}
Brief: {brief1}\n
Author: {name2}
Brief: {brief2}\n
"""
)
# Create an HTML message.
msg.add_alternative(
f"""\
<html>
<head></head>
<body>
<p><b>Author</b>: {name1}</p>
<p><b>Brief</b>: {brief1}</p>
<p><b>Author</b>: {name2}</p>
<p><b>Brief</b>: {brief2}</p>
</body>
</html>
""",
subtype='html',
)
with smtplib.SMTP('localhost', 1025) as s:
s.send_message(msg)它生成以下消息:
---------- MESSAGE FOLLOWS ----------
Subject: APPL: =?utf-8?b?4pay?= 1.234
From: me@example.com
To: you@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============6181735321118528857=="
X-Peer: ('::1', 51216, 0, 0)
--===============6181735321118528857==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Author: The Verge
Brief: Samsung just announced the Galaxy Watch 5 Pro for outdoor athletes and=
Apple is also expected to release a rugged version of the Apple Watch this f=
all. But smartwatches can=E2=80=99t rely too heavily on touchscreens to win o=
ver athletes.
Author: Ars Technica
Brief: Dealmaster also has the Xbox Series S, Apple Watch Series 7, and Nvidi=
a Shield TV.
--===============6181735321118528857==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
MIME-Version: 1.0
<html>
<head></head>
<body>
<p><b>Author</b>: The Verge</p>
<p><b>Brief</b>: Samsung just announced the Galaxy Watch 5 Pro for outdoo=
r athletes and Apple is also expected to release a rugged version of the Appl=
e Watch this fall. But smartwatches can=E2=80=99t rely too heavily on touchsc=
reens to win over athletes.</p>
<p><b>Author</b>: Ars Technica</p>
<p><b>Brief</b>: Dealmaster also has the Xbox Series S, Apple Watch Serie=
s 7, and Nvidia Shield TV.</p>
</body>
</html>
--===============6181735321118528857==--
------------ END MESSAGE ------------https://stackoverflow.com/questions/73347774
复制相似问题