0

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

这是一个片段代码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
4

4 回答 4

3

您应该为换行添加 '\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}'''
于 2015-08-03T09:56:03.497 回答
2

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

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

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

于 2015-08-03T09:56:41.663 回答
2

我建议使用 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'])
```

这是非常强大的,因为您可以按照自己想要的方式设置所有电子邮件的样式,并且一遍又一遍地重复使用相同的功能,只需要创建新模板并传递适当的上下文/主题和收件人

于 2015-08-03T10:16:13.480 回答
1

这应该可以解决断线:

\n
于 2015-08-03T09:57:49.917 回答