簡體   English   中英

通過django創建動態鏈接並將帶有文本的html內容發送到郵件

[英]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', 'manikandanv3131@gmail.com', 'mani@ithoughtz.com'
  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')

這里的問題是,文本內容沒有顯示在郵件中,代碼中的動態鏈接也不起作用。 任何幫助將不勝感激

字符串連接在字符串內不起作用,您需要正確設置字符串。 實際上,您實際上應該使用模板,而不是在視圖中使用HTML。

為您的電子郵件創建模板,將其保存在INSTALLED_APPS中任何應用程序的templates目錄下:

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

在您的視圖代碼中:

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

def send_email(id=None,
               subject='hello',
               from_email='manikandanv3131@gmail.com',
               to='mani@ithoughtz.com'):

    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()

請記住,如果郵件客戶端顯示HTML部分,它將不會顯示替代純文本部分。 您必須查看電子郵件的來源才能看到這兩個部分。

如果您經常這樣做,可以使用django-templated-email ,它提供了更大的靈活性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM