0

How can I make text bold in the email body in python? I am using the following code to send mail :

from django.core.mail import send_mail

send_mail(subject, message, sender, [email], fail_silently=False)

I want to make some important text bold. Using the following code I have received the whole string as a message.

message = " Hi Customer,<br> Your OTP is <b>****</b>"

But it works when I try \n as <br>. What can I do to make the text bold?

Manoj Kamble
  • 620
  • 1
  • 4
  • 21
  • It seems that send_mail has an html argument, see https://www.fullstackpython.com/django-core-mail-send-mail-examples.html – Stefan May 21 '22 at 07:31

2 Answers2

1

According to Django DOCS, html should be added as separate file, so it could be read with or without html (depending on what receiver is using, not everyone want html in emails). You need EmailMultiAlternatives with attach_alternative method:

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
NixonSparrow
  • 6,130
  • 1
  • 6
  • 18
0

All credits goes to this answer sending a html email in django

to make texts bold in email body you need to send a html body.

Try this:

from django.template import loader

html_message = loader.render_to_string(
            'path/to/your/htm_file.html',
            {
                'user_name': user.name,
                'subject':  'Thank you from' + dynymic_data,
                //...  
            }
        )
send_mail(subject,message,from_email,to_list,fail_silently=True,html_message=html_message)

And the html file should look similar to this

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h1>{{ user_name }}</h1>
        <h2>{{ subject }}</h2>
    </body>
</html>
Bruno
  • 655
  • 8
  • 18