【问题标题】:how to break line in list in python email如何在python电子邮件中的列表中换行
【发布时间】:2021-09-02 14:52:56
【问题描述】:

我正在尝试从我的 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')) 

【问题讨论】:

  • 使用这个"\n".join(list)
  • 谢谢!我尝试使用它,但也许要澄清一下,我只打算提取整个列表表的一列(“标题”)(因此我使用了for s in list: str(s.title))。但是当我使用"\n".join(s.title) 时,发生的只是最后一个表的值已打印。:/
  • \n 不起作用,因为它不是正确的 html 语法

标签: python html email flask gmail


【解决方案1】:

我相信您正在寻找的是:

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,但 &lt;br&gt; 是。

【讨论】:

  • 这就像一个魅力!太感谢了!!!!!我整天都在尝试-谢谢谢谢谢谢!!!
【解决方案2】:

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

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

【讨论】:

  • 谢谢!我试过这个并在终端打印它,是的,它出现在终端的单独行中!但是,它仍然存在于整个文本中,电子邮件中没有换行符。我想知道是不是因为电子邮件是自动格式化的还是什么? ://
猜你喜欢
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 2022-01-10
  • 2018-04-09
相关资源
最近更新 更多