Reputation: 1153
I'm trying to send email message in one of my views and would like to format the body of the message, such that it shows in different lines.
This is a snippet code in views.py
:
body = "Patient Name: " + patient_name + \
"Contact: " + phone + \
"Doctor Requested: Dr. " + doctor.name + \
"Preference: " + preference
email = EmailMessage('New Appointment Request', body, to=['[email protected]'])
email.send()
The email is shown like this:
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
Upvotes: 0
Views: 2247
Reputation: 46921
you should add '\n' for newlines.
or you could try this:
body = '''Patient Name: {}
Contact: {}
Doctor Requested: Dr. {}
Preference: {}'''.format(patient_name, phone, doctor.name, preference)
or, if you are using python >= 3.6:
body = f'''Patient Name: {patient_name}
Contact: {phone}
Doctor Requested: Dr. {doctor.name}
Preference: {preference}'''
Upvotes: 3
Reputation: 312
I suggest to use the django template system to do that.
You could do:
```
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()
```
The template will look like: this could for example be in the file myapp/templates/myapp/email/doctor_appointment.email
:
```
Patient Name: {{patient_name}}
Contact: {{contact_number}}
Doctor Requested: {{doctor_name}}
Preference: {{preference}}
```
and you will use it like
```
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,
['[email protected]'])
```
This is very powerfull, because you can style all the email in the way you want, and you re-use the same function over and over, just need to create new template and pass appropriate context/subject and recipietns
Upvotes: 4
Reputation: 2254
You are going right but you just missed a letter n
body = "Patient Name: " + patient_name + "\n"
+ "Contact: " + phone + "\n"
+ "Doctor Requested: Dr. " + doctor.name + "\n"
+ "Preference: " + preference
This will add new line after each and every line and most probably solve your problem.
Upvotes: 2