def send_confirmation_email(request, user): current_site = get_current_site(request) uid = urlsafe_base64_encode(force_bytes(user.pk)) token = account_activation_token.make_token(user) html_message = loader.render_to_string( 'account_activation_email.html', { 'user': user, 'domain': request.META['HTTP_HOST'], 'uid': uid, 'token': token, 'referral_link': user.profile.referral.url }) message = 'http://' + request.META['HTTP_HOST'] + '/activate/' + str( uid) + '/' + str(token) subject = 'Thank you for signing up! ' from_email = 'Check My Keywords <*****@*****.**>' msg = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=[user.first_name + ' ' + user.last_name + '<' + user.email + '>'], reply_to=["Support <*****@*****.**>"]) # Include an inline image in the html: html = html_message msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.metadata = {"user_id": request.user.id} msg.tags = ["confirmation_email"] msg.track_clicks = True # Send it: msg.send()
def registration_user(request): '''Регистрация пользователя и отправка сообщения на почту с ссылкой активации ''' if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): #получаем "чистые" данные пользователя if form.cleaned_data['password1'] == form.cleaned_data[ 'password1']: user_name = form.cleaned_data['name'] e_mail = form.cleaned_data['e_mail'] password = form.cleaned_data['password1'] #создаём пользователя и сохраняем его как неактивного user = User.objects.create_user(user_name, e_mail, password) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account' #сообщение с закодированной ссылкой message = render_to_string( 'acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) to_email = e_mail email = EmailMessage(mail_subject, message, to=[to_email]) #отправляем сообщение для подтверждения почты email.send() return HttpResponse( 'Please confirm your email address to comlete the registration' ) else: form = RegisterForm() return render(request, 'auth/registration.html', {'form': form})
def register(request): if request.method == "POST": form = ClientForm(request.POST) if form.is_valid(): # is_active=False) # user.save() # client = Client(user=user, mail=user.email, first_name=data['first_name'], last_name=data['last_name'], # age=int(data['age']), gender=data['gender'], phone_number=data['phone_number']) client = form.save() user_client = client.user current_site = get_current_site(request) subject = 'Aceline Services : Confirmation du Compte' message = render_to_string( 'mail/mail_confirmation.html', { 'user': user_client, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user_client.pk)), 'token': account_activation_token.make_token(user_client), }) user_client.email_user(subject, message) return redirect('account_activation_sent') # login_func(request, client.user) # # return redirect('/') else: form = ClientForm() return render(request, 'client/login-register.html', {"form": form})
def send_user_activation_email(request, user, to_email_address): subject = 'Please activate your account at Piishi.com' message = render_to_string( 'registration/activation/user_activation_email.html', { 'user': user, 'domain': get_current_site(request).domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) EmailMessage(subject, message, to=[to_email_address]).send()
def send_reset_pass_email(request, user, to_email_address): subject = 'Password reset request at piishi.com' message = render_to_string( 'registration/reset_pass/reset_pass_email.html', { 'email': to_email_address, 'domain': get_current_site(request).domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) EmailMessage(subject, message, to=[to_email_address]).send()
def signup_save(request): ''' функция для регистрации нового пользователя в системе''' if request.method == 'POST': form = RegForm(request.POST) if form.is_valid(): user_name = form.cleaned_data["user_name"] email = form.cleaned_data["email"] password1 = form.cleaned_data["password1"] password2 = form.cleaned_data["password2"] if password1 == password2: #создаем пользователя в бд, делаем его неактивным person_id = new_person_id() try: user = MyUser.objects.create_user(username=user_name, email=email, password=password1, person_id=person_id) user.is_active = False path_to_avatar = os.path.join(settings.MEDIA_URL, 'logo-img.png') user.avatar = path_to_avatar user.save() except Exception as err: print(err) return HttpResponse("Пользователь уже зарегистрирован по данной почте.") #создаем письмо с активационной ссылкой current_site = get_current_site(request) mail_subject = 'Активируйте ваш аккаунт на сайте {0}'.format(current_site) message = render_to_string( 'activate_message.html', { 'user':user, 'domain':current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user) } ) to_email = email send_mail( mail_subject, message, '*****@*****.**', [to_email], html_message=message ) return HttpResponse("На указанный вами адрес электронной почты было отправлено письмо с сылкой для активации вашего аккаунта. Проверьте ваш почтовый ящик и подвердите его активность, перейдя по ссылке.") else: return render(request, 'signup.html', {'form':form})
def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string( 'registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form})
def userSignup(request): if request.user: logout(request) if request.method=='POST': form =UserForm(request.POST) if form.is_valid(): user=form.save(commit=False) user.is_active=False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('accountmanager/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = UserForm() return render(request,'accountmanager/signup.html',{'form':form})
def user_registration(request): if request.method == "POST": student_email = '' username = request.POST['username'] password = request.POST['password'] try: existing_user = User.objects.get(username=username, is_active=True) except ObjectDoesNotExist: existing_user = None if not existing_user: try: teacher_username = Teacher.objects.get(email=username) except ObjectDoesNotExist: teacher_username = None try: student_username = Student.objects.filter( Q(student_id=username) | Q(email=username)) except ObjectDoesNotExist: student_username = None if teacher_username is not None: user = User.objects.create_user(username=username, password=password, email=username) user.is_active = False user.save() group = Group.objects.get(name='Passenger') group.user_set.add(user) current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string( 'registration/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes( user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = username email = EmailMessage(mail_subject, message, from_email=settings.EMAIL_HOST_USER, to=[to_email]) email.send() return HttpResponse( 'Please confirm your email address to complete the registration' ) elif student_username is not None: try: query = Student.objects.raw( 'Select s.id, s.email from accounts_student s where s.student_id = %s ' 'OR s.email = %s', [username, username]) for student in query: student_email = student.email except ObjectDoesNotExist: student_email = None user = User.objects.create_user(username=username, password=password, email=student_email) user.is_active = False user.save() group = Group.objects.get(name='Passenger') group.user_set.add(user) current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string( 'registration/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = student_email email = EmailMessage(mail_subject, message, from_email=settings.EMAIL_HOST_USER, to=[to_email]) email.send() return HttpResponse( 'Please confirm your email address to complete the registration' ) else: messages.info(request, 'You are not registered, Talk to admin please') return render(request, 'registration/registration.html', {'title': 'UTMS Registration'}) else: messages.success( request, 'You are already Registered. Did you forget password?') return redirect('/') return render(request, 'registration/registration.html', {'title': 'UTMS Registration'})
def create_profile(request): """ :param request: :return: """ try: data = request.data post_data_list = [ 'fname', 'lname', 'email_id', 'designation', 'mobile_number', 'is_student', 'organization', ] for post_data in post_data_list: if post_data not in data: return Response(post_data + ' ' + 'information is missing', status=status.HTTP_406_NOT_ACCEPTABLE) record = dict() record['fname'] = data['fname'] record['lname'] = data['lname'] record['email_id'] = data['email_id'] record['designation'] = data['designation'] record['mobile_number'] = data['mobile_number'] record['is_student'] = data['is_student'] record['organization'] = data['organization'] code = account_activation_token.make_token(data['email_id']) record['verification_code'] = code check_email = RMSIndia2019.objects.filter(email_id=data['email_id']) if check_email.exists(): return Response( "This is email is already being used for another user," " please change your email ID", status=status.HTTP_406_NOT_ACCEPTABLE) serializer = RMSIndia2019Serializer(data=record) if serializer.is_valid(raise_exception=True): serializer.save() to_addr = data['email_id'] link = "http://localhost:9000/api/verify/" + code body = """ Greetings! You are receiving this email because you just registered for the RMS Tour of India 2019 Event. To complete this registration, please click on the link provided below: \n """ + link + """ Thank you! - Team Name P.S.: If you did not register for this event, please ignore this email. """ subject = "RMS tour of 2019 - Confirm your registration" send_email(config.username, config.password, to_addr, body, subject) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: print("exception", e) return Response("exception", status=status.HTTP_417_EXPECTATION_FAILED)