为什么我从Django邮件发送的HTML链接不可点击?

4 投票
2 回答
5585 浏览
提问于 2025-04-16 20:12

我通过Django发送了以下邮件

    subject, from_email, to = 'site Registration', 'support@site.com', self.second_email
    text_content = 'Click on link to finish registration'
    html_content = '<html><body><a href="site.com/accounts/user/' + self.slug +'">Click Here</a></body></html>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

当我查看这封邮件时(在谷歌和雅虎邮箱里),它们都把“点击这里”这段文字显示成蓝色的(我猜这表示它被识别为链接),但是这个链接是无法点击的,也没有指向site.com/acc...我哪里做错了呢?

谢谢!

2 个回答

1

我写了一个辅助函数来完成这个任务,并使用了 render_to_string 这个方法,利用一个HTML模板来发送内容,而不是在函数里一字一句地写出来。下面是我的函数:

def signup_email(username, email, signup_link):
    subject, from_email, to = 'Site Registration', settings.DEFAULT_FROM_EMAIL, email
    text_content = 'Click on link to finish registration'
    html_content = render_to_string('pet/html_email.html', {'username': username, 'signup_link':signup_link})
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    return msg 

然后在views.py文件里只需要调用这个函数就可以了:

class OwnerCreateAccount(FormView):
    # class based view  attributes

    def form_valid(self, form):
        # other form logic
        msg = signup_email(username=username, email=email, signup_link=owner.salt)
        msg.send()
        return super(OwnerCreateAccount, self).form_valid(form)
8

你可能需要把它变成一个有效的网址:(注意包含的协议)

<a href="http://site.com/accounts/user/' + self.slug +'">

撰写回答