python 电子邮件换行

python email new line

我试图发送一封显示股票数据的电子邮件并通过电子邮件发送, 它转到雅虎并获取股票价格并与目标进行比较,然后将其与目标中的 % 一起呈现 不幸的是,这一切都没有在股票之间出现 space 我尝试了 \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("yourmail96@gmail.com", "yourpasssword")
    server.sendmail("asdasd", "jesus_acosta1996@hotmail.com", message.as_string())
    server.close()
except Exception:
    print("failed")

您可以使用 html 以您需要的方式自定义输出。

如果有效请告诉我