def send_mail(subject, message, recipient_list, from_email=None, attach: iter = None): """ отправка письма """ models.sendmail(subject, message, recipient_list, from_email, attach)
def post(self, request): """ для отзывов """ if not models.Account.objects.filter(user=self.request.user).exists(): return HttpResponseRedirect('/') form = forms.Review(request.POST, files=request.FILES) if form.is_valid(): photo = form.cleaned_data.get("photo") review = form.cleaned_data["review"] kind = models.ReviewKind.objects.filter(pk=1).first() account = self.request.user.account account.photo = photo account.save() img = Image.open(account.photo.path) # exif = dict(pilImage._getexif().items()) orientation = 0 for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = img._getexif() if exif and orientation in exif: if exif[orientation] == 3: img = img.rotate(180, expand=True) elif exif[orientation] == 6: img = img.rotate(270, expand=True) elif exif[orientation] == 8: img = img.rotate(90, expand=True) if img.width > img.height: delta_crop = (img.width - img.height) / 2 img = img.crop( (delta_crop, 0, img.width - delta_crop, img.height)) elif img.height > img.width: delta_crop = (img.height - img.width) / 2 img = img.crop( (0, delta_crop, img.width, img.height - delta_crop)) if img.width > 300 or img.height > 300: img = img.resize((300, 300)) img.save(account.photo.path, quality=80) review_obj = models.Feedback.objects.create(account=account, feedback=review, kind=kind) settings = models.Setting.objects.filter().first() subject = 'НОВЫЙ ОТЗЫВ О МАРАФОНЕ' message = f'<p>Пользователь: {account.user.get_username} - {account.user.email} </p>' \ f'<p>Текст отзыва: "{review_obj.feedback}" </p>' \ f'<a style="font-size: 24px; font-weight: bold;" href="{settings.website}/api/accept_review/{account.pk}-{review_obj.pk}">Опубликовать отзыв</a>' mail_context = {"settings": settings, "message": message} html_message = render_to_string('mail/news.html', mail_context) models.sendmail(subject, html_message, settings.contact_mail, attach=review_obj.account.photo.path) return HttpResponseRedirect('/me')
def check_registry_sent(): """ периодическая проверка неотправленных писем о регистрации """ sett = models.Setting.objects.filter().first() accounts = models.Account.objects.exclude(registry_sent=True) for a in accounts: new_password = functions.generate_code(length=8) a.user.set_password(new_password) a.user.save() subject = 'Регистрация на платформе марафона "Движение Вверх"' mail_context = { "login": a.user.username, "password": new_password, "settings": sett, "account": a } html_message = render_to_string('mail/registration.html', mail_context) # plain_message = strip_tags(html_message) send_email = models.sendmail(subject=subject, message=html_message, recipient_list=[a.user.email]) if not send_email: a.registry_sent = False a.save() else: a.registry_sent = True a.save()
def post(self, request): form = forms.Feedback(request.POST) if form.is_valid(): fields = { 'firstname': 'Имя', 'contact': 'Контакты', 'message': 'Сообщение' } message = '' for k, v in form.cleaned_data.items(): if k != 'captcha': message += f'{fields.get(k)}: "{v}"\n' subject = 'Новое сообщение по обратной связи марафона "Движение Вверх"' settings = models.Setting.objects.filter().first() if not settings: form.errors[ 'custom'] = f"При отправке сообщения произошла ошибка. Повторите попытку позднее." return self.base(request, form) email = settings.contact_mail send_email = models.sendmail( subject=subject, message=message, recipient_list=[email], ) if not send_email: form.errors[ 'custom'] = f"При отправке сообщения произошла ошибка. Повторите попытку позднее." else: request.session['feedback'] = True return HttpResponseRedirect('/#feedback-label') return self.base(request, form)
def post(self, request): form = forms.RegisterAccount(request.POST) if form.is_valid(): firstname = form.cleaned_data.get("firstname") lastname = form.cleaned_data.get("lastname") phone = form.cleaned_data.get("phone") email = (form.cleaned_data.get("email")).strip().lower() ageconfirm = form.cleaned_data.get("ageconfirm") if not ageconfirm: form.errors[ 'ageconfirm'] = "Этот флажок должен быть установлен" else: # user, new = models.User.objects.get_or_create(username__iexact=email) user_exists = models.User.objects.filter( username__iexact=email).exists() if user_exists: form.errors[ 'custom'] = f"Пользователь с почтой {email} уже зарегистрирован" else: user = models.User.objects.create(username=email, first_name=firstname, last_name=lastname, email=email) password = functions.generate_code(length=8) user.set_password(password) user.save() account = models.Account.objects.create(user=user, phone=phone) created = models.Account.objects.filter( user=user, phone=phone).exists() if created: subject = 'Регистрация на платформе марафона "Движение Вверх"' settings = models.Setting.objects.filter().first() mail_context = { "login": email, "password": password, "settings": settings, "account": account } html_message = render_to_string( 'mail/registration.html', mail_context) # plain_message = strip_tags(html_message) send_email = models.sendmail(subject=subject, message=html_message, recipient_list=[email]) if not send_email: account.registry_sent = False account.save() else: account.registry_sent = True account.save() request.session[ 'registry'] = f'Данные для входа в личный кабинет отправлены на <span class="text-primary">{email}</span>' return HttpResponseRedirect('/login') else: user.delete() return self.base(request, form=form)
def form_mail(lessons, text, subject, add_time=False, only_not_paid=False): for lesson in lessons: accounts = models.Account.objects.prefetch_related( 'payment_set', 'payment_set__marathon__lesson_set').all() lesson.marathon.payment_set.all().values('account', 'status', 'date_approve') accounts_payd = [] accounts_other = [] for account in accounts: if account.payment_set.filter(marathon__lesson=lesson, status="succeeded", date_approve__gte=timezone.now() - timedelta(days=62)).exists(): accounts_payd.append(account.user.email) else: accounts_other.append(account.user.email) # mail1 = f'<p>Не пропустите тему №{lesson.number} <b>"{lesson.title}"</b>!</p>' \ # f'<p>В личном кабинете <b>{lesson.date_publish.strftime("%d.%m.%Y")} в {lesson.date_publish.strftime("%H:%M")} МСК</b>!</p>' # mail2 = f'<p>Не пропустите новую тему №{lesson.number} <b>"{lesson.title}"</b>!</p>' \ # f'<p>В личном кабинете <b>{lesson.date_publish.strftime("%d.%m.%Y")} в {lesson.date_publish.strftime("%H:%M")} МСК</b>!</p>' \ # '<p>Вы ещё успеваете приобрести подписку на все темы марафона на сайте!</p>' # if add_time: # text += f'<b>Завтра в {timezone.localtime(lesson.date_publish).strftime("%H:%M")} по моск. времени</b>' mail_context = {"settings": sett, "message": text} html_message = render_to_string('mail/new_lesson_notify.html', mail_context) for email in accounts_other: send_email = models.sendmail(subject=subject, message=html_message, recipient_list=[email]) if not only_not_paid: for email in accounts_payd: send_email = models.sendmail(subject=subject, message=html_message, recipient_list=[email])
def handle(self, *args, **options): emails = list(models.Account.objects.all().exclude( user__username='******').values_list('user__email', flat=True)) subject = 'Новости марафона "Движение Вверх"' msg_safe = '<p>На сайте стартовала возможность приобрести подписку на марафон.</p>' \ '<p>А также, в личном кабинете уже доступен для просмотра базовый бесплатный урок!</p>' sett = models.Setting.objects.filter().first() mail_context = {"settings": sett, "message": msg_safe} html_message = render_to_string('mail/news.html', mail_context) for email in emails: try: send_email = models.sendmail(subject=subject, message=html_message, recipient_list=[email]) except: pass
def post(self, request): if request.user.is_authenticated: return HttpResponseRedirect('/me') form = forms.ResetPWD(request.POST) if form.is_valid(): email = (form.cleaned_data['email']).strip().lower() account = models.Account.objects.filter( user__email__iexact=email).first() if not account: form.errors['custom'] = "Пользователь с таким email не найден." else: account.reset_pwd_uuid = uuid.uuid4() try: account.save() account.user.save() except: form.errors[ 'custom'] = "Ошибка при сбросе пароля. Повторите попытку позднее." else: subject = 'Сброс пароля в личном кабинете марафона "Движение Вверх"' settings = models.Setting.objects.filter().first() reset_url = f'{settings.website}/reset_confirmation/{account.reset_pwd_uuid}' mail_context = { "login": email, "reset_url": reset_url, "settings": settings } html_message = render_to_string('mail/reset.html', mail_context) send_email = models.sendmail(subject=subject, message=html_message, recipient_list=email) if not send_email: form.errors[ 'custom'] = "Ошибка при сбросе пароля. Повторите попытку позднее." else: form_html = get_template( 'includes/reset_redirect.html').render( context={'email': email}, request=request) context = self.make_context(form_html=form_html, title='Сброс пароля') return render(request, "auth.html", context) return self.base(request, form=form)
def mass_notify_for_not_paid(): """ периодическая отправка напоминаний о покупке марафона, зарегистрировавшимся """ subject = 'Напоминание о новом уроке' text = f'<p>Вы прошли удачно регистрацию на марафон успеха. ' \ f'Урок уже ждёт вас в вашем личном кабинете ' \ f'<a href="{sett.website}" target="_blank" style="font-weight: bold; color: #000">{sett.website}</a></p>' \ f'<p>Не останавливайтесь!</p>' emails = models.Account.objects.exclude( payment__status="succeeded").values_list('user__email', flat=True).distinct() mail_context = {"settings": sett, "message": text} html_message = render_to_string('mail/new_lesson_notify.html', mail_context) for email in emails: send_email = models.sendmail(subject=subject, message=html_message, recipient_list=email)
def get(self, request, uid): if request.user.is_authenticated: return HttpResponseRedirect('/me') context = self.make_context() account = models.Account.objects.filter(reset_pwd_uuid=uid).first() if not account or not account.reset_pwd_uuid: context[ 'content'] = 'Ссылка на сброс пароля недействительна или устарела.' return render(request, 'general.html', context) password = functions.generate_code(length=8) account.user.set_password(password) account.reset_pwd_uuid = None try: account.save() account.user.save() except: context[ 'content'] = "Ошибка при сбросе пароля. Повторите попытку позднее." return render(request, 'general.html', context) else: subject = 'Новый пароль в личном кабинете марафона "Движение Вверх"' settings = models.Setting.objects.filter().first() mail_context = { "login": account.user.email, "password": password, "settings": settings } html_message = render_to_string('mail/reset_confirmation.html', mail_context) send_email = models.sendmail(subject=subject, message=html_message, recipient_list=account.user.email) form_html = get_template('includes/pwd_show.html').render( context={'pwd': password}, request=request) context = self.make_context(form_html=form_html, title='Сброс пароля') return render(request, "auth.html", context)
def post(self, request): if models.Account.objects.filter(user=self.request.user).exists(): if request.POST.get( 'method' ) == "check" and self.request.user.account.payment_set.exists(): return JsonResponse({"payments": True}) subject = 'Удаление профиля на платформе марафона "Движение Вверх"' settings = models.Setting.objects.filter().first() mail_context = { "login": self.request.user.email, "settings": settings } html_message = render_to_string('mail/remove.html', mail_context) # plain_message = strip_tags(html_message) send_email = models.sendmail( subject=subject, message=html_message, recipient_list=[self.request.user.email]) if not send_email: return JsonResponse({'sendmail': send_email}) else: self.request.user.delete() return JsonResponse({'sendmail': send_email, "deleted": True}) return HttpResponseRedirect('/')