我正在尝试在我的一个观看中发送电子邮件,并希望格式化邮件的正文,以便它以不同的行显示
这是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
How do I make it show like this:
Patient Name: Afrojack
Contact: 6567892
Doctor Requested: Dr. Irena
Preference: Afternoon
答案 0 :(得分:2)
你说得对,但你错过了一封信n
body = "Patient Name: " + patient_name + "\n"
+ "Contact: " + phone + "\n"
+ "Doctor Requested: Dr. " + doctor.name + "\n"
+ "Preference: " + preference
这将在每一行之后添加新行,并且最有可能解决您的问题。
答案 1 :(得分:1)
你应该为换行添加'\ n'。
或者你可以试试这个:
body = '''Patient Name: {}
Contact: {}
Doctor Requested: Dr. {}
Preference: {}'''.format(patient_name, phone, doctor.name, preference)
答案 2 :(得分:1)
这应该可以解决断裂问题:
\n
答案 3 :(得分:1)
我建议使用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'])
```
这非常强大,因为您可以按照自己的方式设置所有电子邮件的样式, 并且你反复使用相同的功能,只需要创建新的模板 并传递适当的背景/主题和收件人