html内容不会通过电子邮件发送

时间:2017-03-20 03:11:59

标签: python django django-1.9

我想将链接发送到电子邮件,因此当用户点击该链接时,用户将被重定向到推荐页面并可以推荐其他朋友。我使用send_mail发送电子邮件。除了html消息之外,所有内容都会被发送。这就是我所做的

  if created:
     new_join_old.invite_code = get_invite_code()
     new_join_old.save()
     subject = "Thank you for your request to sign up our community"
     html_message = '<a href="http://localhost:8000/{% url "invitations:refer-invitation" invite_code %}">Click Here</a>'
     message = "Welcome! We will be in contact with you."
     from_email = None
     to_email = [email]
     send_mail(subject, message, from_email, to_email, fail_silently=True, html_message=html_message)
     messages.success(request, '{0} has been invited'.format(email))
   return HttpResponseRedirect("/invitations/refer-invitation/%s"%(new_join_old.invite_code))
context = {"form": form}
return render(request, 'home.html', context)

2 个答案:

答案 0 :(得分:0)

[更新] :为了让以下内容有效,您必须在settings.py文件中设置适当的email settings,如下所示:

# settings.py

#######################
#   EMAIL SETTINGS    #
#######################
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'email_username_here'
EMAIL_HOST_PASSWORD = 'email_password_here'

<a>链接未呈现,因为没有loader呈现它(未知{% url %}模板标记)。如果您希望保留此语法({% url ... %})并拥有一个单独的HTML文件,然后将HTML文件存储为单独的文件,例如html_email.html,然后使用render_to_string并执行以下内容:

<!-- html_email.html -->

<a href="http://localhost:8000/{% url 'invitations:refer-invitation' invite_code %}">Click Here</a>


# views.py

from django.template.loader import render_to_string

if created:
    # above code as is
    # in the context you can pass other context variables that will be available inside the html_email.html
    context = {'invite_code': new_join_old.invite_code,}
    html_message = render_to_string('path/to/html_email.html', context=context)
    # below code as is

或者你可以这样做:

#views.py

from django.core.mail import EmailMultiAlternatives
from django.urls import reverse

if created:
    # above code as is
    html_message = '<a href="http://localhost:8000{}">Click Here</a>'.format(reverse('invitations:refer-invitation', kwrags={'invite_code': invite_code}))
    msg = EmailMultiAlternatives(subject, message, from_email, to_email, fail_silently=True)
    msg.attach_alternative(html_message, 'text/html')
    msg.send()

答案 1 :(得分:0)

from django.template import Context, Template

email_data = open('email_templates/email.html', 'r').read()
html_data = Template(email_data)
html_content = html_data.render(Context({'invite_code': new_join_old.invite_code}))

您也可以在上下文中添加messagesubject等键值对

在email.html中

<!DOCTYPE html>
<html>

<head>
</head>
<body>
    <a href="http://localhost:8000/invitations/refer-invitation/{{ invite_code }}">Click Here</a>
</body>
</html>

您可以使用messagesubject

访问email.html中的{{ message }}{{ subject }}等上下文变量的值

https://docs.djangoproject.com/en/1.10/topics/email/#the-emailmessage-class