如何在python电子邮件中的列表中换行

问题描述

我正在尝试从 Flask 数据库查询一个列表,然后将其作为 html 电子邮件发送出去。但是,我无法将它们分成不同的行。

例如,代替:

一个

b

c

我目前在电子邮件中收到了 abc。我试过在循环中添加 "\n" 但它似乎不起作用。有谁知道我怎么把它分成不同的行?

def mail():
  sender_email = "xx@gmail.com"
  message = MIMEMultipart("alternative")
  message["Subject"] = "xx"
  message["From"] = sender_email
  message["To"] = user_mail
  add = '\n'
  
  list = Lines.query.all()
  for s in list:
    add += str(s.title) + '\r\n'

  print(add)

  # Write the plain text part
  text = "Thank you for submitting a xx! Here are the lines submitted: " + add

# write the HTML part
  html = """\
    <html>
    <head><head style="margin:0;padding:0;">
    <table role="presentation" style="width:100%;border-collapse:collapse;border:20;border-spacing:20;background:#cc0000;">
        <tr>
            <td align="center" style="padding:20;color:#ffffff;">
                Your xxxxx was submitted!
            </td>
        </tr>
    </table>
</head>
    
        <p>Thank you for submitting a xx! Here are the lines submitted for your reference:<br><br>
        """ + add + """
            <br></br>
        </p>

    </html>
    """
    # convert both parts to MIMEText objects and add them to the MIMEMultipart message
  part1 = MIMEText(text,"plain")
  part2 = MIMEText(html,"html")
  message.attach(part1)
  message.attach(part2)
... 

  server.sendmail("xx@gmail.com",user_mail,message.as_string())
  return redirect(url_for('complete')) 

解决方法

我相信您正在寻找的是:

list = Lines.query.all()
for s in list:
    add += str(s.title) + '<br>'

或(使用格式与字符串连接):

list = Lines.query.all()
for s in list:
    add += '{}<br>'.format(str(s.title))

或(python 3.6+ f 字符串):

list = Lines.query.all()
for s in list:
     add += f"{s.title}<br>"

\n 不适用于 HTML,但 <br> 是。

,

您可以使用空字符串并继续添加到循环中。

str = ""
for s in list:
     str += f"{s.title}\n"