[Answered ]-Set personalized body for sending mail in django

0👍

The commas in this line don’t look right:

allinfo = "Name : " + name, "E-Mail" + email, "Contact:" + contact, textmess

You might want:

allinfo = "Name: " + name + " E-Mail: " + email + "Contact: " + contact + textmess

Or better, use f-strings: https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings

allinfo = f"Name: {name} E-Mail: {email} Contact: {contact} {textmess}"

1👍

You can also use templates to configure mail information.

For example, here is my contact form mail template:

{% autoescape off %}
Message from <my project> contact form:

From: {{ name }} ({{ email }})
{% if user.email %}
User: {{ user.display_name }} ({{ user.email }})
{% endif %}

{{ body }}
{% endautoescape %}

I then use this when sending a mail as follows:

    send_mail(
        subject=f"CONTACT FORM: {subject}",
        message=render_to_string(
            template_name="project/email/contact_us_body.html",
            context={
                "name": from_name,
                "email": from_email,
                "user": user,
                "body": body,
            },
        ),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[
            contact_tuple[1] for contact_tuple in settings.ADMINS if contact_tuple[1] is not None
        ],
        fail_silently=False,
    )

You can use this templating for mail bodies, subjects, or basically any text at all, just by calling render_to_string.

Leave a comment