首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SMTP发送电子邮件时出现的编码问题

使用SMTP发送电子邮件时出现的编码问题
EN

Stack Overflow用户
提问于 2022-08-13 21:36:19
回答 1查看 148关注 0票数 0

当使用SMTP发送电子邮件时,我会遇到编码问题。我检查了许多不同的帖子和方法来解决这个问题,但是没有什么对我有用。

这是我的代码,删除了所有个人信息:

代码语言:javascript
复制
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')}")

这给了我迄今为止最好的结果:

代码语言:javascript
复制
msg=f"Subject:{subject.encode('utf-8')}\n\n{message.encode('utf-8')}"

这就是这封电子邮件最终的样子:

代码语言:javascript
复制
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 " 

我做错了什么?我试过使用EmailMessageHeaderMIMEText等,我也尝试过发送到多个不同的电子邮件提供商,以防万一,这并没有改变任何事情。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-14 07:38:57

您需要对整个消息体进行编码,而不是对部分进行编码,然后将它们插入到字符串中。

例如,此代码(仅使用部分数据):

代码语言:javascript
复制
 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调试服务器中生成此输出

代码语言:javascript
复制
---------- 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电子邮件,如下所示:

代码语言:javascript
复制
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)

它生成以下消息:

代码语言:javascript
复制
---------- 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 ------------
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73347774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档