我正在编写一个使用 NewsAPI 并将新闻发送到我的邮件的程序。一切都很好,但是当我收到邮件时,它在一行中向我提供了所有新闻,我希望它使用一些断行。这就是我得到的结果。
这是我写的代码。
import requests
from send_email import send_email
api_key = "xxxxx"
url = ("xxxxx")
# Make a request
request = requests.get(url)
# Get a dictionary with data
content = request.json()
body = ''
# Access the article title and description
for article in content["articles"]:
if article["title"] is not None:
body = body + article["title"] + "\n" + article["description"] + 2*"\n"
# Sending article titles and description via email
body = body.encode("utf-8")
message = f"""\
Subject: Python API News
{body}
"""
send_email(message)
我使用的发送电子邮件的代码工作正常。我已经在我的其他程序中使用了它。
这就是我想要的结果,请帮忙。
我没有尝试做任何事情来解决它,因为我不知道是什么原因造成的。
编辑:好吧,我意识到我没有指定几件事。首先是我在哪里使用了 smtplib。我将在此处附上代码。
import smtplib, ssl
import os
def send_email(message):
host = "smtp.gmail.com"
port = 465
username = "[email protected]"
password = os.getenv("GMAIL_APP_PASS")
receiver = "[email protected]"
context = ssl.create_default_context()
with smtplib.SMTP_SSL(host, port, context=context) as server:
server.login(username, password)
server.sendmail(username, receiver, message)
这是使用 smtplib 的 send_email 的代码。
第二什么是newsapi?
这是我能提供的最好的文档:Newsapi.org/docs
这足够了还是我还遗漏了什么? 请告诉我,谢谢。
您的问题可能导致此行:
body = body.encode("utf-8")
因此删除编码可能会对您有帮助