V Manikandan
V Manikandan

Reputation: 370

creating dynamic link and sending html content with text to mail via django

from django.core.mail import EmailMultiAlternatives
def mail_fun(confirmation_id):

  subject, from_email, to = 'hello', '[email protected]', '[email protected]'
  text_content = 'This is an important message.'

  html_content = """<a style="display: block;position: relative;background-color:    
  #2B7ABD;width: 144px;height: 30px;text-align: center;text-decoration: none;color:   
  white;font-size: 14px;top: 49px;border-radius: 4px;margin-left: 178px;" 
  href="http://127.0.0.1:8000/confirm_mail/?confirmation_id=" + confirmation_id ><span 
  style="display:block;position: relative;top: 8px;">Confirm Email adress</span></a>
  """
  msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
  msg.attach_alternative(html_content, "text/html")
  msg.send()

mail_fun('1234567890')

Problem here is, text content not is not displaying in the mail and the dynamic link in the code is also not working. Any help will be appreciated

Upvotes: 0

Views: 1840

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174662

String concatenation will not work inside strings, you need to set up your strings correctly. In fact, you should actually be using templates for this, rather than having HTML inside your view.

Create a template for your email, save it under the templates directory of any application that is in INSTALLED_APPS:

<html>
<head>
<title>Email</title>
</head>
<style>
   div.link {
       display: 'block';
       position: 'relative';
       background-color: '#2B7ABD';
       width: 144px;
       height: 30px;
       text-align: center;
       text-decoration: none;
       color: white;
       font-size: 14px;
       margin-top: 49px;
       border-radius: 4px;
       margin-left: 178px;
   }
</style>
<body>
<div class="link"> 
  <a href="http://127.0.0.1:8000/confirm_mail/?confirmation_id={{ id }}">Confirm Email adress</a>
</div>
</body>
</html>

In your view code:

from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives

def send_email(id=None,
               subject='hello',
               from_email='[email protected]',
               to='[email protected]'):

    text_content = 'This is an important message.'
    html_content = render_to_string('html_email.html', {'id': id})
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

Keep in mind that if a mail client shows the HTML part, it will not show the alternative plain text part. You would have to view the source of the email to see both parts.

If this is something you will be doing often, you can use django-templated-email which offers more flexibility.

Upvotes: 2

Related Questions