Home > OS >  Set personalized body for sending mail in django
Set personalized body for sending mail in django

Time:07-12

I want to send a message with personalized SMTP mail-in Django. Where I want to send Name, email, and contact information with the dynamic text input value.

Here is my code

    if request.method == 'POST':
      name = request.POST.get('name')
      email = request.POST.get('email')
      contact = request.POST.get('contactnum')
      textmess = request.POST.get('textarea')
      allinfo = "Name : "   name, "E-Mail"   email, "Contact:"   contact, textmess
      print (allinfo)
      subject = 'From MBS Project(Contact Us)'
      email_from = settings.EMAIL_HOST_USER
      mailto:recipents_list=['[email protected]']
      if allinfo:
        sendMail = send_mail(subject, allinfo, email_from, recipents_list)
        messages.success(request, 'Message Send Successfully...')
        return HttpResponseRedirect('contactus', {'sendMail': sendMail})
      else:
        messages.error(request, 'error during send!!, Please Try Again..')
        return render(request, 'contactus.html', {})
   else:
      return render(request, 'contactus.html', {})

CodePudding user response:

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}"

CodePudding user response:

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.

  • Related