我试图发送一封显示库存数据的电子邮件,并通过电子邮件发送,然后转到Yahoo,获取股票价格并与目标进行比较,并用目标中的%
进行展示不幸的是,这一切在股票之间都没有空格我尝试了\n
和\r\n
,但没有成功这是我尝试编写的代码,
import smtplib
import sys
import os
import re
import bs4
import requests
import pprint
import math #ciel for round
# list of data
stock={'MMM':145,'WM':95,'JNJ':130,'KMB':123,'PEP':117}
def get_stock(st):
b=None
lc=[]
ab=re.sub(r'GNC', st, "https://finance.yahoo.com/quote/GNC?p=GNC&.tsrc=fin-srch")
res=requests.get(ab)
soup=bs4.BeautifulSoup(res.text)
b=soup.find('div',{'class':'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
c=soup.find('h1').text
pprint.pprint(f'for company {c} in symbol {st} the price is {b} target {stock[st]} {(float(b)/float(stock[st])-1)*100:.2f}% from target\n')
#message='for company'+c+"in symbol"+st+' '+" the price is"+b
message1='For company'+' '+c+' '+'in symbol'+' '+st+' '+'the price is'+' '+str(b)+' '+'target'+' '+str(stock[st])+" "+str(math.ceil((float(b)/float(stock[st])-1)*100))+'% '+'from target'+'\r\r\n'
message1=message1+os.linesep
lc=message1
return message1
for symbol,price in stock.items():
i=get_stock(symbol)
import smtplib
from email.mime.text import MIMEText
def send_email(body,user="myemail", pwd="mypassword", recipient="xxxx", subject="Reprort from Python"):
ld=[]
for symbol,price in stock.items():
i=get_stock(symbol)
ld.append(i)
body=ld
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (user, ", ".join(recipient), subject, body)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print ('successfully sent the mail')
except:
print ("failed to send mail")
send_email(body=lc)
您可以尝试使用html格式:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
message = MIMEMultipart('alternative')
message['subject'] = 'my subject'
message['from'] = 'from'
lb = ""
for symbol,price in stock.items():
lb += """<p>
{0}
</p>""".format(get_stock(symbol))
body = """<html>
<head></head>
<body>
{0}
</body>
</html>
""".format(lb)
message.attach(MIMEText(body, 'html'))
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login("[email protected]", "yourpasssword")
server.sendmail("asdasd", "[email protected]", message.as_string())
server.close()
except Exception:
print("failed")
您可以使用html以所需的方式定制输出。
让我知道是否可行