Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django中格式化电子邮件_Python_Django_Django Email - Fatal编程技术网

Python 在Django中格式化电子邮件

Python 在Django中格式化电子邮件,python,django,django-email,Python,Django,Django Email,我正试图在我的一个视图中发送电子邮件,并希望格式化邮件的正文,使其以不同的行显示 这是views.py中的代码片段: 电子邮件如下所示: Patient Name: AfrojackContact: 6567892Doctor Requested: Dr. IrenaPreference: Afternoon Patient Name: Afrojack Contact: 6567892 Doctor Requested: Dr. Irena Preference: Afternoon

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

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

电子邮件如下所示:

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

Contact: 6567892

Doctor Requested: Dr. Irena

Preference: Afternoon
我如何让它像这样展现:

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


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

这将为特征线提供技巧:

\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中:

你会像这样使用它

```
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_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'])
```