Home > Back-end >  How do I make text "bold" in email body in python?
How do I make text "bold" in email body in python?

Time:05-21

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?

CodePudding user response:

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', '[email protected]', '[email protected]'
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()

CodePudding user response:

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>
  • Related