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')
问题在于,文本内容没有显示在邮件中,代码中的动态链接也不起作用。任何帮助将不胜感激
答案 0 :(得分:2)
字符串连接在字符串内不起作用,您需要正确设置字符串。实际上,您实际上应该使用模板,而不是在视图中使用HTML。
为您的电子邮件创建模板,将其保存在templates
中的任何应用程序的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>
在您的观看代码中:
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
,这样可以提供更大的灵活性。