【问题标题】:Django - how to get email links to work on mobile?Django - 如何让电子邮件链接在移动设备上工作?
【发布时间】:2020-01-04 21:01:56
【问题描述】:

我的 Django 网站发送了一个电子邮件确认链接,在桌面上一切正常。然而,在移动设备上,链接文本以蓝色突出显示并带有下划线(即它看起来像一个链接),但当用户单击它时没有任何反应。它应该会打开一个浏览器选项卡并显示“您已确认您的电子邮件等”

感谢您的任何提示!

views.py:

def signup(request):
    if request.method == 'POST':
        #send signup form
        email_address = request.POST['email']
        if request.POST['password1'] == request.POST['password2']:
            try:
                user = User.objects.get(email=email_address)
                return render(request, 'accounts/signup.html', {'error': "Email already in use."})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['email'], password=request.POST['password1'])
                #auth.login(request, user)
                #send email confirmation link then redirect:
                #user = User.objects.get(email=email_address)
                current_site = get_current_site(request)
                mail_subject = 'Welcome to My Site'
                plain_msg = 'Thank you for signing up to My Site! Click this link to activate your account:\n\n'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/'
                msg = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>title</title></head><body>Confirm your email address to continue:<br/><a href="'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/">Confirm my email address</a></body></html>'
                print(msg)
                send_mail(mail_subject, plain_msg, 'my_email@gmail.com', [email_address], html_message=msg)
                return render(request, 'accounts/activation-link-sent.html', {'email': email_address})
    #truncated for Stack Overflow post

【问题讨论】:

  • 点击链接时什么都没有发生?这是在电子邮件应用程序中吗?
  • 尝试在链接中添加target="_blank"
  • @IainShelvington 是的,没有任何反应。有点奇怪。向我展示这个的两个用户都在使用电子邮件应用程序,是的。
  • 是不是每个用户都在使用一个应用程序,它是同一个应用程序吗?可能是应用程序阻止了链接。链接是否包含协议? (http/https)
  • 我会删除带有链接的评论,因为它包含您的域和验证令牌

标签: python django html-email


【解决方案1】:

您应该使用build_absolute_uri 创建包含当前域和协议的完全限定链接,然后在您的电子邮件中使用此链接

link = request.build_absolute_uri('/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/')

您有与此网址匹配的网址格式吗?您应该考虑使用 reverse 来构建 URL

path = reverse('activate', kwargs={
    'pk': user.pk,
    'token': account_activation_token.make_token(user)
})
link = request.build_absolute_uri(path)

【讨论】:

  • 谢谢 Iain - 我确实有一个 URL 模式,所以我暂时不用它了。我使用request.build_absolute_uri 并删除了一个用户帐户并让他们重新注册,并且电子邮件确认链接在他们的电子邮件应用程序中完美运行。
猜你喜欢
  • 1970-01-01
  • 2019-05-29
  • 2016-04-19
  • 1970-01-01
  • 2013-07-12
  • 2016-05-03
  • 1970-01-01
  • 2020-10-01
  • 2015-01-16
相关资源
最近更新 更多