在 smtplib 电子邮件中使用消息函数



我正在尝试向自己发送一封电子邮件,其中包含我所做的一些网络抓取的结果。所有抓取都发生在一个函数中。所以我尝试将该功能设置为我的电子邮件的消息,但它不起作用。

这是我的代码(仍然相当新,所以请不要过多地抨击代码,我知道我仍然可以重构它(

from bs4 import BeautifulSoup
from email.mime.text import MIMEText
import requests
import smtplib
page = requests.get("https://www.sportsinteraction.com/soccer/england/premier-league-betting/")
soup = BeautifulSoup(page.content, 'html.parser')
matches = soup.find_all(class_="game")
def betting_odds(data):
for games in data:
teams = games.find_all(class_="name")
odds = games.find_all(class_="price wide")
if len(games.find_all(class_="date")) > 0:
print(games.find(class_="date").get_text())
team1 = teams[0].get_text()
draw = teams[1].get_text()
team2 = teams[2].get_text()
odds1 = odds[0].get_text()
odds_draw = odds[1].get_text()
odds2 = odds[2].get_text()
print("{}  {} n{}  {} n{}  {} n".format(team1, odds1, draw, odds_draw, team2, odds2))    
fromx = 'email@email.com'
to = 'email@emai.com'
msg = MIMEText('Here are the odds for the upcoming premier league gamesnn{}'.format(betting_odds(matches)))
msg['Subject'] = 'Premier League Odds'
msg['From'] = fromx
msg['To'] = to
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('Email@email.com', 'password')
smtpObj.sendmail(fromx, to, msg.as_string()) 
smtpObj.quit()

当我运行它时,所有结果都完全按照我希望它们的外观显示在 Shell 中,然后发送电子邮件。一旦我收到电子邮件,它就有主题,消息的第一行是正确的,但随后它说没有。

任何帮助将不胜感激!

此问题已解决。我通过创建一个变量来保存字符串并继续通过循环将它们连接在一起来完成它。然后我在最后返回了变量。

干杯!

最新更新