Функция восстановления пароля по электронной почте работает только на локальном хостинге в django

У меня есть приведенный ниже код, который отвечает за отправку электронного письма для восстановления пароля пользователю, сделавшему запрос. Однако это работает только в том случае, если отправка электронного письма на локальный хост осуществляется только в том случае, если пользователь обращается к nginx, используя IP-адрес моей машины, или доступ к VPS при развертывании приложения не работает.

ссылка генерируется обычно независимо от URL, но электронное письмо генерируется только на локальном хостинге или если я удаляю ссылку для сброса пароля как из html, так и из python

Мне нужно, чтобы электронное письмо было отправлено независимо от хостинга, следуйте коду:

def password_reset_request(request):
    if request.method == "POST":
        form = PasswordResetRequestForm(request.POST)
        if form.is_valid():
            cpf = form.cleaned_data['cpf']
            # Get user by CPF
            user = CustomUser.objects.get(cpf=cpf)  # Adjust field as needed
            
            # Generate password reset token
            token = default_token_generator.make_token(user)
            uid = urlsafe_base64_encode(force_bytes(user.pk))
            
            # Create password reset link
            reset_link = request.build_absolute_uri(
                reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token})
            )

            
            # Prepare email
            theme = 'Reset Password'
            email_template = 'auth/recovery_email.html'
            email_context = {
                'user': user,
                'reset_link': reset_link,
                'valid_hours': 24  # Token validity in hours
            }
            email_content = render_to_string(email_template, email_context)


            try:
                # Send email
                send_mail(
                    theme,
                    '',  # Plain text version (empty as we're using HTML)
                    settings.DEFAULT_FROM_EMAIL,
                    [user.email],
                    html_message=email_content,
                    fail_silently=False,
                )

                print("Email sent successfully!")
            except Exception as e:
                print(f"Email sending failed: {e}")
                print(f"Email sending failed: {e}")  # Print to console for immediate feedback
            
            # Redirect to success page
            return redirect('password_reset_done')
    else:
        form = PasswordResetRequestForm()
    
    return render(request, 'auth/redirect.html', {'form': form})

recovery_email.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .header {
            text-align: center;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .content {
            padding: 20px 0;
        }
        .button {
            display: inline-block;
            padding: 10px 20px;
            background-color: #1c4d30;
            color: white !important;
            text-decoration: none;
            border-radius: 5px;
            margin: 20px 0;
        }
        .footer {
            padding-top: 20px;
            border-top: 1px solid #eee;
            text-align: center;
            font-size: 12px;
            color: #777;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>Password Reset</h2>
        </div>
        <div class="content">
            <p>Hello,</p>
            <p>We received a request to reset the password for your account. Click the button below to set a new password:</p>
            
            <p style="text-align: center;">
                <a href="{{ reset_link }}" class="button">Reset Password</a>
            </p>
            
            <p>This link is valid for {{ valid_hours }} hours.</p>
            
            <p>If you did not request a password reset, you can safely ignore this email.</p>
            
            <p>Best regards,<br>
            CIGMA Team</p>
        </div>
        <div class="footer">
            <p>This is an automated email. Please do not reply to this message.</p>
        </div>
    </div>
</body>
</html>

Вернуться на верх