【问题标题】:How do you insert a new line into a message using EmailMessage (Django)如何使用 EmailMessage (Django) 在消息中插入新行
【发布时间】:2023-03-31 23:00:05
【问题描述】:

我正在使用 EmailMessage 通过 Django 中的 Amazon SES 发送电子邮件。我目前无法在消息中插入新行。 "\n" 似乎不起作用

我该怎么做?

例如,这是我尝试过的:

subject= "Test email with newline" 
message = "%s %s is testing an email with a newline.  \nCheck out this link too: http://www.example.com" % (user.first_name, user.last_name)
from_string = "<support@example.com>"
email_message = EmailMessage(subject, message, from_string, [user.email])
email_message.send() 

当我发送这封电子邮件时,我收到:

 Michael Smith is testing an email with a newline. Check out this link too: 
 http://www.example.com

但是,我希望电子邮件的格式如下:

Michael Smith is testing an email with a newline. 
Check out this link too: http://www.example.com

【问题讨论】:

  • 这只是一个猜测,但您是否尝试过将其设为原始字符串? message = r"%s %s is testing an email with a newline. \nCheck out this link too: http://www.example.com" % (user.first_name, user.last_name)
  • 试试this
  • 可能还需要两个换行符,因为 HTML。

标签: python django


【解决方案1】:

您可以使用 attach_alternative() 并提供 html - 在您的情况下,&lt;p&gt;&lt;br&gt; 可以解决问题。

from django.core.mail import EmailMessage

subject= "Test email with newline"
html_context = "%s %s is testing an email with a newline.  <br>Check out this link too: http://www.example.com" % (user.first_name, user.last_name)
from_string = "<support@example.com>"
msg = EmailMessage(subject,
                   html_context,
                   from_string,
                   [user.email])
msg.content_subtype = "html"
msg.send()

【讨论】:

    【解决方案2】:

    更好的用途是尝试发送 html 消息,您可以将电子邮件作为 html 发送。在那里你可以随意格式化你的味精

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 1970-01-01
      • 2020-04-05
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      相关资源
      最近更新 更多