在 Django 中格式化电子邮件

Format email message in Django

我正在尝试在我的一个视图中发送电子邮件,并希望格式化邮件正文,使其显示在不同的行中。

这是views.py中的一段代码:

  body = "Patient Name: " +  patient_name + \
                   "Contact: " + phone + \
                   "Doctor Requested: Dr. " +  doctor.name + \
                   "Preference: " + preference

  email = EmailMessage('New Appointment Request', body, to=['ex@gmail.com'])
  email.send()

邮件显示如下:

Patient Name: AfrojackContact: 6567892Doctor Requested: Dr. IrenaPreference: Afternoon

如何让它显示成这样:

Patient Name: Afrojack

Contact: 6567892

Doctor Requested: Dr. Irena

Preference: Afternoon

你应该为换行添加'\n'。

或者你可以试试这个:

body = '''Patient Name: {}
Contact: {}
Doctor Requested: Dr. {}
Preference: {}'''.format(patient_name, phone, doctor.name, preference)

或者,如果您使用的是 python >= 3.6:

body = f'''Patient Name: {patient_name}
Contact: {phone}
Doctor Requested: Dr. {doctor.name}
Preference: {preference}'''

你走对了,但你错过了一封信n

body = "Patient Name: " +  patient_name + "\n"
                   + "Contact: " + phone + "\n"
                   + "Doctor Requested: Dr. " +  doctor.name + "\n"
                   + "Preference: " + preference

这将在每一行之后添加新行,很可能会解决您的问题。

这应该可以解决断线问题:

\n

我建议使用 django 模板系统来做到这一点。

你可以这样做:

```
from django.template import loader, Context

def send_templated_email(subject, email_template_name, context_dict, recipients):


    template = loader.get_template(email_template_name)

    context = Context(context_dict)

    email = EmailMessage(subject, body, to=recipients)
    email.send()

```

模板将如下所示:例如可以在文件 myapp/templates/myapp/email/doctor_appointment.email:

```

Patient Name: {{patient_name}}

Contact: {{contact_number}}

Doctor Requested: {{doctor_name}}

Preference: {{preference}}
```

你会像

一样使用它
```
context_email = {"patient_name" : patient_name,
    "contact_number" : phone,
    "doctor_name":  doctor.name,
    "preference" :  preference}

send_templated_email("New Appointment Request", 
                     "myapp/templates/myapp/email/doctor_appointment.email",
                     context_email, 
                     ['ex@gmail.com'])
```

这非常强大,因为您可以按照自己的方式设置所有电子邮件的样式, 并且您一遍又一遍地重复使用相同的功能,只需要创建新模板 并通过适当的 context/subject 和 recipietns