python - 从 imaplib 获取的电子邮件没有换行符

标签 python django

我正在使用以下函数在我的 Django 应用程序中获取邮件:

def landing_page(request):
    mail.select('inbox')
    result, data = mail.uid('search', None, "ALL")
    i = len(data[0].split())
    for x in range(i, i-10, -1):
        status, data = mail.fetch(x, '(RFC822)')
        email_msg = email.message_from_string(data[0][1])
        if email_msg.is_multipart():
            for part in email_msg.walk():
                if part.get_content_type() == "text/plain":
                    body = part.get_payload(decode=True).decode("quoted-printable")

        else:
            body = email_msg.get_payload(decode=True).decode("quoted-printable")

        if body is None :
            body = "None"

        rec = MailTable(mid = x, subject = email_msg['subject'], sender = email_msg['from'], mail=body.decode('utf-8', 'ignore'))
        rec.save()
    return render(request, "landing_page.html", {})

我得到的结果是这样的:

Hi Mayur,I scored 93 percentile in GRE and 95 percentile in high school. I applied for MBA for Harvard University and got selected!. Looking forward for a great career.!Your Sincerely,Cristo

我想要的是:

Hi Mayur,
  I scored 93 percentile in GRE and 95 percentile in high school.
I applied for MBA for Harvard University and got selected!. Looking forward for a great career.!
Your Sincerely,
Cristo

编辑:

我将正文作为上下文传递,然后在 html 中显示如下:

<div class="bottom-box" id = "body-mail">
    {{ body_ }}
</div>

最佳答案

我怀疑你的问题不是换行,而是中断。尝试:

body = body.replace('\n', '<br />\n')

关于python - 从 imaplib 获取的电子邮件没有换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220385/

相关文章:

python - 如何将 Graphene GraphQL 框架与 Django REST 框架身份验证一起使用

php - National Instruments USB 6008 和 Linux

python - PyCharm 显示没有来自 pandas 的输出

asp.net - Python Django 与 ASP.NET MVC

django - 如何在基于函数的 View 而不是类中使用 Django Hitcount?

python - 将 CSS 类添加到 Django-Autocomplete-Light ModelSelect2 容器/选择

python - Django 模板上下文不适用于导入的类

python - 将 Shutil.make_archive 与 zipfile.ZIP_STORED 一起使用吗?

python sqlite将不同大小的库插入表中

带有 Heroku 错误 : R10 Boot Timeout 的 Python Twitter 机器人