def editprofile(request):
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        email = request.POST['email']
        try:
            existent_email = User.objects.get(email=email)
        except:
            existent_email = None

        if existent_email:
            return render(request, 'fhs/editprofile.html',{"existent": True})

        form = EmailForm(data=request.POST, instance=request.user)
        picform = UserProfileForm(data=request.POST, instance=request.user)
        try:
            up = UserProfile.objects.get(user=request.user)
        except:
            up = None
        if form.is_valid() and picform.is_valid():
            if email:
                user = form.save(commit=False)
                user.save()
            if 'picture' in request.FILES:
                up.picture = request.FILES['picture']
                up.save()
            return HttpResponseRedirect('/fhs/profile/'+user.username)
    else:
        return render(request, 'fhs/editprofile.html',{})
Exemple #2
0
def edit_details(request):
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        email = request.POST['email']
        try:
            existent_email = User.objects.get(email=email)
        except:
            existent_email = None

        if existent_email:
            return render(request, 'ArtVillage/edit_details.html', {"existent": True})

        form = EmailForm(data=request.POST, instance=request.user)
        try:
            up = UserProfile.objects.get(user=request.user)
        except:
            up = None
        if form.is_valid():
            if email:
                user = form.save(commit=False)
                user.save()
            return HttpResponseRedirect('/profile/' + user.username)
        else:
            return render(request, 'ArtVillage/edit_details.html', {})
    else:
        return render(request, 'ArtVillage/edit_details.html', {})
Exemple #3
0
def edit_details(request):
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        email = request.POST['email']
        try:
            existent_email = User.objects.get(email=email)
        except:
            existent_email = None

        if existent_email:
            return render(request, 'ArtVillage/edit_details.html',
                          {"existent": True})

        form = EmailForm(data=request.POST, instance=request.user)
        try:
            up = UserProfile.objects.get(user=request.user)
        except:
            up = None
        if form.is_valid():
            if email:
                user = form.save(commit=False)
                user.save()
            return HttpResponseRedirect('/profile/' + user.username)
        else:
            return render(request, 'ArtVillage/edit_details.html', {})
    else:
        return render(request, 'ArtVillage/edit_details.html', {})
Exemple #4
0
def send_email(request):

    if request.method != 'POST':
        form = EmailForm()
        return render(request, 'submit_event.html', {'email_form': form})

    form = EmailForm(request.POST, request.FILES)

    if form.is_valid():
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        email = form.cleaned_data['email']
        attach = request.FILES['attach']
        try:
            mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
            mail.attach(attach.name, attach.read(), attach.content_type)
            response = mail.send()
            return render(request, 'submit_event.html', {'message': 'Sent email to %s' % (email)})
        except Exception as e:
            return render(request, 'submit_event.html', {'message': e.message})
    else:
        try:
            return render(request, 'submit_event.html', {'message': form.message})

        except AttributeError:
            return render(request, 'submit_event.html', {'message': "Please fill out all fields on the form.", "email_form":form})
Exemple #5
0
def TmcData5(request):
    """
    if CheckAccess(request,'2') != 'OK':
	return render_to_response("tmc/notaccess/tmc.html")
    """

    ## --- Номер заявки ---
    try:
        tmc_id = request.GET['tmc_id']
        request.session['tmc_id'] = tmc_id
    except:
        pass

    try:
        tmc_id = request.session['tmc_id']
    except:
        return HttpResponseRedirect("/tmc")

    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            Email2Ruk(email, tmc_id)

    d = GetTmcData(tmc_id)

    form = EmailForm(None)

    s = GetLastStatus(tmc_id)

    c = RequestContext(request, {'d': d, 'form': form, 's': s})
    c.update(csrf(request))
    return render_to_response("tmc/tmcdata5.html", c)
Exemple #6
0
def forgot_password(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        login_form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            user = get_object_or_404(CustomUser, email=email)
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            user.activation_key = hashlib.sha1(salt+user.email).hexdigest()
            #user.key_expires = timezone.now() + timezone.timedelta(100)
            user.save()
            plaintext = get_template('email/password_reset.txt')
            htmly = get_template('email/password_reset.html')
            d = Context({'user': user, 'site_url': site_url})


            subject, from_email, to = 'Восстановление пароля', '*****@*****.**', user.email
            text_content = plaintext.render(d)
            html_content = htmly.render(d)
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            return HttpResponseRedirect(reverse('success_reset'))
    else:
        form = EmailForm()
        login_form = LoginForm()
    context = {'form': form, 'login_form': login_form}
    return render(request, "forgot_password.html", context)
Exemple #7
0
def forgot_password(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        login_form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            user = get_object_or_404(CustomUser, email=email)
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            user.activation_key = hashlib.sha1(salt + user.email).hexdigest()
            #user.key_expires = timezone.now() + timezone.timedelta(100)
            user.save()
            plaintext = get_template('email/password_reset.txt')
            htmly = get_template('email/password_reset.html')
            d = Context({'user': user, 'site_url': site_url})

            subject, from_email, to = 'Восстановление пароля', '*****@*****.**', user.email
            text_content = plaintext.render(d)
            html_content = htmly.render(d)
            msg = EmailMultiAlternatives(subject, text_content, from_email,
                                         [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            return HttpResponseRedirect(reverse('success_reset'))
    else:
        form = EmailForm()
        login_form = LoginForm()
    context = {'form': form, 'login_form': login_form}
    return render(request, "forgot_password.html", context)
Exemple #8
0
def remind_user(request):
    """
        **Descripción**: Resetea la contraseña de usuario
	"""
    from forms import EmailForm
    if request.method == 'POST':
        f = EmailForm(request.POST, prefix='pass_remind')
        if f.is_valid():
            from models import User
            user = User.objects.get_by_email(f.cleaned_data['email'])
            if user is None:
                fail = _(u"El correo no existe")
                f._errors['email'] = f.error_class([fail])
            else:
                user.send_remind_code()
                msg = _(
                    u"Se ha enviado un correo de confirmación a %s. Por favor revisa tu correo"
                ) % user.email
                return render_to_response(
                    'mainApp/user_pass.html',
                    dict(msg=msg),
                    context_instance=RequestContext(request))
    else:
        f = EmailForm(prefix='pass_remind')
    return render_to_response('mainApp/user_pass.html', {'form': f},
                              context_instance=RequestContext(request))
def editprofile(request):
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        email = request.POST['email']
        try:
            existent_email = User.objects.get(email=email)
        except:
            existent_email = None

        if existent_email:
            return render(request, 'fhs/editprofile.html', {"existent": True})

        form = EmailForm(data=request.POST, instance=request.user)
        picform = UserProfileForm(data=request.POST, instance=request.user)
        try:
            up = UserProfile.objects.get(user=request.user)
        except:
            up = None
        if form.is_valid() and picform.is_valid():
            if email:
                user = form.save(commit=False)
                user.save()
            if 'picture' in request.FILES:
                up.picture = request.FILES['picture']
                up.save()
            return HttpResponseRedirect('/fhs/profile/' + user.username)
    else:
        return render(request, 'fhs/editprofile.html', {})
Exemple #10
0
def test_email(request):
    if request.method == 'GET':
        form = EmailForm()
    else:
        form = EmailForm(data=request.POST) 
        if form.is_valid():
            form.save()
    return render_to_response('mail.html', {'form': form})
Exemple #11
0
def add_email_activation(request):
    form = EmailForm(request.POST)
    if not form.is_valid():
        raise _Error.invalid_email(request.POST['email'])
    email = form.cleaned_data['email']
    token = create_token(email)
    mailing.verify_email(email, token)
    return {'email': email}
Exemple #12
0
def email(request, conn=None, **kwargs):
    """
    View to gather recipients, subject and message for sending email
    announcements
    """

    # Check that the appropriate web settings are available
    if (not request.session.get('server_settings', False)
                           .get('email', False)):
        return {'template': 'webadmin/noemail.html'}
    context = {'template': 'webadmin/email.html'}

    # Get experimenters and groups.
    experimenter_list = list(conn.getObjects("Experimenter"))
    group_list = list(conn.getObjects("ExperimenterGroup"))

    # Sort experimenters and groups
    experimenter_list.sort(key=lambda x: x.getFirstName().lower())
    group_list.sort(key=lambda x: x.getName().lower())

    if request.method == 'POST':  # If the form has been submitted...
        # ContactForm was defined in the the previous section
        form = EmailForm(experimenter_list, group_list, conn, request,
                         data=request.POST.copy())
        if form.is_valid():  # All validation rules pass
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            experimenters = form.cleaned_data['experimenters']
            groups = form.cleaned_data['groups']
            everyone = form.cleaned_data['everyone']
            inactive = form.cleaned_data['inactive']

            req = omero.cmd.SendEmailRequest(subject=subject, body=message,
                                             groupIds=groups,
                                             userIds=experimenters,
                                             everyone=everyone,
                                             inactive=inactive)
            handle = conn.c.sf.submit(req)
            if handle is not None:
                request.session.modified = True
                request.session['callback'][str(handle)] = {
                    'job_type': 'send_email',
                    'status': 'in progress', 'error': 0,
                    'start_time': datetime.datetime.now()}
            form = EmailForm(experimenter_list, group_list, conn, request)
            context['non_field_errors'] = ("Email sent."
                                           "Check status in activities.")
        else:
            context['non_field_errors'] = "Email wasn't sent."

    else:
        form = EmailForm(experimenter_list, group_list, conn, request)

    context['form'] = form

    return context
Exemple #13
0
def email(request, conn=None, **kwargs):
    """
    View to gather recipients, subject and message for sending email
    announcements
    """

    # Check that the appropriate web settings are available
    if (not request.session.get('server_settings', False)
                           .get('email', False)):
        return {'template': 'webadmin/noemail.html'}
    context = {'template': 'webadmin/email.html'}

    # Get experimenters and groups.
    experimenter_list = list(conn.getObjects("Experimenter"))
    group_list = list(conn.getObjects("ExperimenterGroup"))

    # Sort experimenters and groups
    experimenter_list.sort(key=lambda x: x.getFirstName().lower())
    group_list.sort(key=lambda x: x.getName().lower())

    if request.method == 'POST':  # If the form has been submitted...
        # ContactForm was defined in the the previous section
        form = EmailForm(experimenter_list, group_list, conn, request,
                         data=request.POST.copy())
        if form.is_valid():  # All validation rules pass
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            experimenters = form.cleaned_data['experimenters']
            groups = form.cleaned_data['groups']
            everyone = form.cleaned_data['everyone']
            inactive = form.cleaned_data['inactive']

            req = omero.cmd.SendEmailRequest(subject=subject, body=message,
                                             groupIds=groups,
                                             userIds=experimenters,
                                             everyone=everyone,
                                             inactive=inactive)
            handle = conn.c.sf.submit(req)
            if handle is not None:
                request.session.modified = True
                request.session['callback'][str(handle)] = {
                    'job_type': 'send_email',
                    'status': 'in progress', 'error': 0,
                    'start_time': datetime.datetime.now()}
            form = EmailForm(experimenter_list, group_list, conn, request)
            context['non_field_errors'] = ("Email sent."
                                           " Check status in activities.")
        else:
            context['non_field_errors'] = "Email wasn't sent."

    else:
        form = EmailForm(experimenter_list, group_list, conn, request)

    context['form'] = form

    return context
Exemple #14
0
    def patch(self, request, **kwargs):
        doctor = get_object_or_404(User, pk=kwargs['pk']).doctor
        data = QueryDict(request.body)
        form = EmailForm(data, instance=doctor)
        if form.is_valid():
            form.save()
            doctorJSON = serializers.serialize("json", [doctor])
            return HttpResponse(doctorJSON, content_type='application/json')

        return HttpResponse(status=500)
Exemple #15
0
def send_email(request, sent=None):
    """ Send an email to all club members. """

    form = EmailForm()
    template='send_email.html'
    users = []
    send_errors = []

    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            form = form.cleaned_data
            subject = form['subject']
            message = form['message']

            try:
                users = User.objects.filter(
                        is_active=True,
                        userprofile__want_email=True,
                        )
            except ObjectDoesNotExist:
                error = "Can't pull up the user list!"
                return error_404(request, error)

            for user in users:
                try:
                    user_email = user.email
                    send_mail(subject, 
                              message, 
                              SERVER_EMAIL,
                              [user_email],
                              fail_silently=False,
                              )
                except SMTPException:
                    # Need to grab Exception and pass it to template
                    error = "There was an error sending mail!"
                    return error_404(request, error)

                except:
                    error = "There was an error sending mail!"
                    return error_404(request, error)

            return HttpResponseRedirect(reverse(sent_email))

        else:
            form = EmailForm(request.POST)
            
    ctxt = { 
        'request' : request, 
        'form' : form, 
        'users' : users,
        'page_name' : 'Email All Members',
        'media_url' : MEDIA_URL,
        }
    return render_to_response(template, ctxt)
Exemple #16
0
    def post(self, request, *args, **kwargs):
        """Handles the POST request to the 'account_forgot_password' named route.
        Args: request.
        Returns: A HttpResponse with a forgot_password_recovery_status template
                 otherwise, return forgot_password template.
        """
        email_form = EmailForm(request.POST, auto_id=True)
        if email_form.is_valid():
            try:
                # get the account for that email if it exists:
                input_email = email_form.cleaned_data.get('email')
                registered_user = User.objects.get(email__exact=input_email)

                # generate a recovery hash url for that account:
                recovery_hash = Hasher.gen_hash(registered_user)
                url_str = str(
                    reverse_lazy('account_reset_password',
                                 kwargs={'recovery_hash': recovery_hash}))
                recovery_hash_url = request.build_absolute_uri(url_str)

                # compose the email:
                recovery_email_context = RequestContext(
                    request, {'recovery_hash_url': recovery_hash_url})
                subject, from_email, to = 'TheEventDiary: Password Recovery', 'Theeventdiary <*****@*****.**>', registered_user.email
                html = loader.get_template(
                    'forgot_password_recovery_email.html').render(
                        recovery_email_context)
                text = loader.get_template('forgot_password_recovery_email.txt'
                                           ).render(recovery_email_context)

                msg = EmailMultiAlternatives(subject, text, from_email, [to])
                msg.attach_alternative(html, "text/html")
                email_status = msg.send()

                # inform the user of the status of the recovery mail:
                context = {
                    'page_title': 'Forgot Password',
                    'registered_user': registered_user,
                    'recovery_mail_status': email_status,
                }
                return render(request, 'forgot_password_recovery_status.html',
                              context)

            except ObjectDoesNotExist:
                # set an error message:
                messages.add_message(
                    request, messages.ERROR, 'The email you entered does not \
                    belong to a registered user!')

        context = {
            'page_title': 'Forgot Password',
            'email_form': email_form,
        }
        return render(request, 'forgot_password.html', context)
Exemple #17
0
def connect(request):
    if request.method == 'POST':
        email_form = EmailForm(request.POST)
        search_form = UserSearchForm(request.POST)
        email_form.is_valid()
        search_form.is_valid()
        address = email_form.cleaned_data['email']
        searched_user = search_form.cleaned_data['lastName']
        if address:
            data = getoutput('echo "{}" >> emails && echo "Complete!"'.format(
                address)).split('\n')
            return render(
                request, 'connect.html', {
                    'email_form': email_form,
                    'email': True,
                    'data': data,
                    'search_form': search_form
                })
            pass
        elif searched_user:
            regUsers = User.objects.raw(
                'SELECT * from auth_user where last_name like "%%{}%%";'.
                format(searched_user))
            return render(
                request, 'connect.html', {
                    'email_form': email_form,
                    'regUsers': regUsers,
                    'search_form': search_form
                })
        else:
            return render(request, 'connect.html', {
                'email_form': email_form,
                'search_form': search_form
            })
    else:
        email_form = EmailForm()
        search_form = UserSearchForm()
    return render(request, 'connect.html', {
        'email_form': email_form,
        'search_form': search_form
    })
Exemple #18
0
def email(request):
    # 管理者グループの指定(ネルフ)
    admin_group = Group.objects.get(name='nerv')
    admin_list = admin_group.user_set.filter(is_active=True).exclude(profile__nickname=None)
    if request.method == 'POST':
        form = EmailForm(request.POST)
        try:
            form.is_valid()
            site = Site.objects.get_current()
            ctx_dict = {
                'site': site,
                'sender': form.cleaned_data['sender'],
                'subject': form.cleaned_data['subject'],
                'body': form.cleaned_data['body']
            }
            subject = render_to_string('contact/email_subject.txt', ctx_dict)
            subject = ''.join(subject.splitlines())
            body = render_to_string('contact/email.txt', ctx_dict)
            recivers = admin_list.exclude(email='')
            for reciver in recivers:
                reciver.email_user(subject, body, from_email=form.cleaned_data['sender'])
            message = u"メールを送信しました"
            messages.success(request, message, fail_silently=True)
        except ValidationError as e:
            message = u"日本語が含まれていない文章は送信できません"
            messages.error(request, message)
        except:
            message = u"エラーが発生しました"
            messages.error(request, message)

    else:
        form = EmailForm()
    kwargs = {
        'template': r'contact/email_form.html',
        'extra_context': {
            'form': form,
            'admin_group': admin_group,
            'admin_list': admin_list,
        },
    }
    return simple.direct_to_template(request, **kwargs)
Exemple #19
0
def email(request):
   if request.method == 'POST': 
      form = EmailForm(request.POST, error_class=AlertErrorList)
      if form.is_valid():
         result = EmailSender().send(form.cleaned_data["email"], form.cleaned_data['message'])
         return HttpResponseRedirect('/') 
   else:
      form = EmailForm(error_class=AlertErrorList) 

   return render_to_response('email/email.html',
                             {'form': form },
                             context_instance=RequestContext(request))
Exemple #20
0
def new_automation(request, alert_type):
    alert_type = get_object_or_404(AlertType,
                                   slug=alert_type,
                                   unit__in=request.units)

    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            if AlertEmailTemplate.objects.filter(
                    alerttype=alert_type,
                    hidden=False,
                    threshold=form.cleaned_data['threshold']).count() > 0:
                errors = form._errors.setdefault("threshold", ErrorList())
                errors.append(u'An e-mail with this threshold already exists.')
            else:
                f = form.save(commit=False)
                f.alerttype = alert_type
                f.created_by = request.user.username
                f.save()
                messages.success(
                    request,
                    "Created new automated email for %s." % alert_type.code)
                l = LogEntry(userid=request.user.username,
                             description="Created new automated email %s." %
                             alert_type.code,
                             related_object=form.instance)
                l.save()
                return HttpResponseRedirect(
                    reverse('alerts.views.view_automation',
                            kwargs={'alert_type': alert_type.slug}))
    else:
        form = EmailForm()

    sample_alert = Alert.objects.filter(alerttype=alert_type, hidden=False)[0]

    email_tags = [("person.name",
                   "The name of the student that has triggered the alert"),
                  ("person.first_name", "The first name of the student."),
                  ("person.last_name", "The last name of the student."),
                  ("person.middle_name", "The middle name of the student."),
                  ("person.emplid", "The student's emplid."),
                  ("person.email", "The student's email."),
                  ("person.title", "The student's title."),
                  ("description", "The description of the alert.")]

    for k, v in sample_alert.details.iteritems():
        email_tags.append(("details." + k, "For example, (" + str(v) + ")"))

    return render(request, 'alerts/new_automation.html', {
        'alert_type': alert_type,
        'form': form,
        'email_tags': email_tags
    })
Exemple #21
0
def connect(request):
    if request.method == 'POST':
        email_form = EmailForm(request.POST)
        search_form = UserSearchForm(request.POST)
        email_form.is_valid()
        search_form.is_valid()
        address = email_form.cleaned_data['email']
        searched_user = search_form.cleaned_data['lastName']
        if address:
            data = getoutput('echo "{}" >> emails && echo "Complete!"'.format(address)).split('\n')
            return render(request, 'connect.html', {'email_form':email_form, 'email':True , 'data':data, 'search_form':search_form})
            pass
        elif searched_user:
            regUsers = User.objects.raw('SELECT * from auth_user where last_name like "%%{}%%";'.format(searched_user))
            return render(request, 'connect.html', {'email_form':email_form, 'regUsers':regUsers, 'search_form':search_form})
        else:
            return render(request, 'connect.html', {'email_form':email_form, 'search_form':search_form})
    else:
        email_form = EmailForm()
        search_form = UserSearchForm()
    return render(request, 'connect.html', {'email_form':email_form, 'search_form':search_form})
Exemple #22
0
def commit(request):
    if request.method == "POST":
        ef = EmailForm(request.POST)
        if ef.is_valid():
            s = Signup(email=ef.cleaned_data["email"])
            s.save()
        cats = ["volunteer", "outdoors", "food", "drink", "entertain", "winter", "rents"]
        resp_dict = models.get_acts_from_cats(cats)
        return render_to_response("home.html", resp_dict, RequestContext(request))
    else:
        ef = EmailForm()
        return render_to_response("commit.html", {"form": ef}, RequestContext(request))
Exemple #23
0
def index(request):
    if request.method == 'GET':
        form = EmailForm()
        return render(request, 'index.html', {'form': form})
    elif request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            r = requests.post('https://slack.com/api/users.admin.invite',
                              data={
                                  'token': settings.SLACK_TOKEN,
                                  'email': email,
                              })
            if not r.status_code == 200:
                print r.content

            errors = []
            invites_list = []
            data = json.loads(r.content)
            if 'ok' in data and not data['ok']:
                errors.append('Slack: {}'.format(data['error']))
            else:
                invites_list.append('Slack')

            mailchimp_api = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY)
            try:
                mailchimp_api.lists.subscribe('29b5ace6f2', {'email': email})
                invites_list.append('Newsletter')
            except mailchimp.ListAlreadySubscribedError:
                errors.append('Already subscribed to newsletter')

            r = requests.get(
                'https://civictools.appspot-preview.com/api/v1/invite',
                params={
                    'teamId': '-Kd27R2-vkjuWxHEQ23A',
                    'secret': settings.AMPLIFY_SECRET,
                    'email': email
                })
            if not r.status_code == 200:
                errors.append('Failed to send Amplify invite')
            else:
                invites_list.append('Amplify')
            msg = ''
            if errors:
                msg += '{}</br>'.format(', '.join(errors))
            if invites_list:
                msg += 'Invite(s) sent for: {}'.format(', '.join(invites_list))

            form = EmailForm
            return render(request, 'index.html', {'form': form, 'msg': msg})
    else:
        raise Http404('method not allowed')
Exemple #24
0
def email(request):
	if request.method == "POST":
		form = EmailForm(request.POST)
		if form.is_valid():
			send_a_letter.delay(form.cleaned_data["sender"],form.cleaned_data["recipient"],
				form.cleaned_data["subject"],form.cleaned_data["message"])
			return HttpResponse("all sent. thanks.")
	else:
		form = EmailForm()
	
	return render(request, 'examples/email.html', {
		'form' : form
	})
Exemple #25
0
def frontend_change(request):

	uform = EmailForm(request.POST or None)

	if uform.is_valid():
		# form.save()
		messages.info(request, 'An email has been sent, Please check')
		return redirect('.')


	return render_to_response('notification.html',
	                          locals(),
	                          RequestContext(request))
Exemple #26
0
def adminemail(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            user = User.objects.get(id=request.user.id)
            user.email = form.cleaned_data['email']
            user.save()
            return redirect('/account/profile/' + str(request.user.id))
    else:
        user = User.objects.get(id=request.user.id)
        form = EmailForm(instance=user)

    return render(request, 'form.html', {'form': form})
Exemple #27
0
    def post(self, request):
        form = EmailForm(request.POST)
        if form.is_valid():

            worksheet_guid = form.cleaned_data["id"]
            worksheet = Worksheet.objects.get(guid=worksheet_guid)
            recipient = form.cleaned_data["email"]
            subject = "Your Personalized College Financial Aid Information"
            body_template = get_template("email_body.txt")
            body = body_template.render(RequestContext(request, dict(guid=worksheet.guid)))

            send_mail(subject, body, "*****@*****.**", [recipient], fail_silently=False)
        document = {"status": "ok"}
        return HttpResponse(json.dumps(document), content_type="application/json")
Exemple #28
0
def send_email(request):
    """ Send a new email. """
    email_form = EmailForm(user=request.user)

    if request.method == "POST":
        email_form = EmailForm(request.POST,user=request.user)
        if email_form.is_valid():
            print email_form.cleaned_data['required_fields']
            from_account = email_form.cleaned_data['from_account']

            send_templated_email(request.user, email_form.contacts, from_account, email_form.cleaned_data['subject'], email_form.cleaned_data['html'], email_form.cleaned_data['text'])
            messages.success(request, "%s sent" % email_form.cleaned_data['subject'])
            # return redirect("index")
    return render(request, "emails/send.html", {"form": email_form})
Exemple #29
0
def index(request):
    if request.method == "POST":
        form = EmailForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.signup_date = timezone.now()
            post.email_confirmed = True
            post.save()
            return redirect('/emailupdate/thanks/')
    else:
        form_class = EmailForm
        return render(request, 'emailupdate/emailupdate.html', {
            'form': form_class,
        })
Exemple #30
0
def email(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        
        if form.is_valid():
            email1 = form.cleaned_data['email']
            content1 = form.cleaned_data['content']
            
            send_mail('Subject here', 'Here is the message.', '*****@*****.**', ['*****@*****.**'], fail_silently=False)
    
            HttpResponse('<script>alert("Send Succeed");history.back();</script>')
            return HttpResponseRedirect('/home/')
    else:
        form = EmailForm()
    return render(request, 'useradd.html', {'form': form})
def if_email_add(request):
    email = request.COOKIES.get('email', 'noemailset')
    if email != 'noemailset':
        # print email
        email = urllib.unquote(email)
        # print email
        form = EmailForm({'email': email, })
        cd = ''
        if form.is_valid():
            cd = form.cleaned_data
            # print "cleaned data"
            # print cd["email"]
            if not EmailCollect.objects.filter(email=cd["email"]):
                e = EmailCollect(email=cd["email"])
                e.save()
Exemple #32
0
    def post(self, request, *args, **kwargs):
        """Handles the POST request to the 'account_forgot_password' named route.
        Args: request.
        Returns: A HttpResponse with a forgot_password_recovery_status template
                 otherwise, return forgot_password template.
        """
        email_form = EmailForm(request.POST, auto_id=True)
        if email_form.is_valid():
            try:
                # get the account for that email if it exists:
                input_email = email_form.cleaned_data.get('email')
                registered_user = User.objects.get(email__exact=input_email)

                # generate a recovery hash url for that account:
                recovery_hash = Hasher.gen_hash(registered_user)
                url_str = str(reverse_lazy('account_reset_password',kwargs={'recovery_hash': recovery_hash}))
                recovery_hash_url = request.build_absolute_uri(url_str)

                # compose the email:
                recovery_email_context = RequestContext(request, {'recovery_hash_url': recovery_hash_url})
                subject, from_email, to = 'TheEventDiary: Password Recovery', 'Theeventdiary <*****@*****.**>', registered_user.email
                html=loader.get_template('forgot_password_recovery_email.html').render(recovery_email_context)
                text=loader.get_template('forgot_password_recovery_email.txt').render(recovery_email_context)

                msg = EmailMultiAlternatives(subject, text, from_email, [to])
                msg.attach_alternative(html, "text/html")
                email_status = msg.send()

                # inform the user of the status of the recovery mail:
                context = {
                    'page_title': 'Forgot Password',
                    'registered_user': registered_user,
                    'recovery_mail_status': email_status,
                }
                return render(request, 'forgot_password_recovery_status.html', context)

            except ObjectDoesNotExist:
                # set an error message:
                messages.add_message(
                    request, messages.ERROR,
                    'The email you entered does not \
                    belong to a registered user!')

        context = {
            'page_title': 'Forgot Password',
            'email_form': email_form,
        }
        return render(request, 'forgot_password.html', context)
Exemple #33
0
def adminemail(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            user = User.objects.get(id=user_id)
            user.email =form.cleaned_data['email']
            user.save()
            # 記錄系統事件
            if is_event_open(request) :               
                log = Log(user_id=request.user.id, event=u'修改信箱<'+user.first_name+'>')
                log.save()                
            return redirect('/account/profile/'+str(request.user.id))
    else:
        user = User.objects.get(id=request.user.id)
        form = EmailForm(instance=user)

    return render_to_response('account/email.html',{'form': form}, context_instance=RequestContext(request))    
Exemple #34
0
    def post(self, request):
        form = EmailForm(request.POST)
        if form.is_valid():

            worksheet_guid = form.cleaned_data['id']
            worksheet = Worksheet.objects.get(guid=worksheet_guid)
            recipient = form.cleaned_data['email']
            subject = "Your Personalized College Financial Aid Information"
            body_template = get_template('email_body.txt')
            body = body_template.render(RequestContext(request,
                                        dict(guid=worksheet.guid)))

            send_mail(subject, body, '*****@*****.**', [recipient],
                      fail_silently=False)
        document = {'status': 'ok'}
        return HttpResponse(json.dumps(document),
                            content_type='application/json')
Exemple #35
0
def remember_password(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            hash = uuid.uuid4().hex
            password_remember = PasswordRemember(hash=hash, email=form.cleaned_data['email'])
            password_remember.save()
            message = u'Вы запросили восстановление пароля на сайте %s. Для продолжения перейдите по ссылке %s' % \
                (settings.SITE_URL ,settings.SITE_URL + "/accounts/reset/" + hash)

            send_mail(u'Восстановление пароля ' + settings.SITE_URL, message, '*****@*****.**',
                      [form.cleaned_data['email']])
            return HttpResponse(u'Ссылка на страницу восстановления пароля была отправлена на адрес, указанный в форме.')

    else:
        form = EmailForm()

    return direct_to_template(request, 'registration/email_form.html', {'form': form})
Exemple #36
0
def awt_frontpage(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            try:
                subscribe_email(form.cleaned_data)
                messages.success(request, 'Successfully subscribed.')
                redirect_to = 'awt_frontpage'
            except mailchimp.ListAlreadySubscribedError:
                messages.error(request, 'Already subscribed.')
                redirect_to = 'awt_frontpage'
            except mailchimp.ValidationError, e:
                messages.error(request, 'ERROR: %s' % e.args[0])
                redirect_to = 'awt_frontpage'
            except Exception, e:
                messages.error(request, 'ERROR: %s' % e.args[0])
                redirect_to = 'awt_frontpage'
            return redirect(redirect_to)
Exemple #37
0
def email_draft_edit_view(request, pk, email_pk):
    issue = _get_issue_for_emails(request, pk)
    email = _get_email_for_issue(issue, email_pk)
    if not email.state in DRAFT_EMAIL_STATES:
        return redirect("case-email-list", issue.pk)

    case_email_address = build_clerk_address(issue, email_only=True)
    case_emails = get_case_emails(issue)
    if request.method == "POST":
        default_data = {
            "from_address": case_email_address,
            "state": EmailState.DRAFT,
            "issue": issue,
            "sender": request.user,
        }
        data = merge_form_data(request.POST, default_data)
        form = EmailForm(data, instance=email, files=request.FILES)
        if form.is_valid():
            messages.success(request, "Draft saved.")
            email = form.save()
    elif request.method == "DELETE":
        email.delete()
        messages.success(request, "Draft deleted")
        return HttpResponse(
            headers={"HX-Redirect": reverse("case-email-list", args=(pk, ))})
    else:
        form = EmailForm(instance=email)

    api = MSGraphAPI()
    sharepoint_docs = api.folder.get_all_files(f"cases/{issue.id}")
    sharepoint_options = [{
        "name": doc["name"],
        "value": doc["id"]
    } for doc in sharepoint_docs]
    context = {
        "issue": issue,
        "form": form,
        "case_emails": case_emails,
        "email": email,
        "case_email_address": case_email_address,
        "is_disabled": email.state != EmailState.DRAFT,
        "sharepoint_options": sharepoint_options,
    }
    return render(request, "case/case/email/draft_edit.html", context)
Exemple #38
0
def send_email(request):
    """ Send a new email. """
    email_form = EmailForm(user=request.user)

    if request.method == "POST":
        email_form = EmailForm(request.POST, user=request.user)
        if email_form.is_valid():
            print email_form.cleaned_data['required_fields']
            from_account = email_form.cleaned_data['from_account']

            send_templated_email(request.user, email_form.contacts,
                                 from_account,
                                 email_form.cleaned_data['subject'],
                                 email_form.cleaned_data['html'],
                                 email_form.cleaned_data['text'])
            messages.success(request,
                             "%s sent" % email_form.cleaned_data['subject'])
            # return redirect("index")
    return render(request, "emails/send.html", {"form": email_form})
Exemple #39
0
def email(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)

        if form.is_valid():
            email1 = form.cleaned_data['email']
            content1 = form.cleaned_data['content']

            send_mail('Subject here',
                      'Here is the message.',
                      '*****@*****.**', ['*****@*****.**'],
                      fail_silently=False)

            HttpResponse(
                '<script>alert("Send Succeed");history.back();</script>')
            return HttpResponseRedirect('/home/')
    else:
        form = EmailForm()
    return render(request, 'useradd.html', {'form': form})
Exemple #40
0
def remind_user(request):
    """
        **Descripción**: Resetea la contraseña de usuario
	"""
    from forms import EmailForm
    if request.method == 'POST':
        f = EmailForm(request.POST, prefix='pass_remind')
        if f.is_valid():
            from models import User
            user = User.objects.get_by_email(f.cleaned_data['email'])
            if user is None:
                fail = _(u"El correo no existe")
                f._errors['email'] = f.error_class([fail])
            else:
                user.send_remind_code()
                msg = _(u"Se ha enviado un correo de confirmación a %s. Por favor revisa tu correo") % user.email
                return render_to_response('mainApp/user_pass.html', dict(msg=msg), context_instance=RequestContext(request))
    else:
        f = EmailForm(prefix='pass_remind')
    return render_to_response('mainApp/user_pass.html', {'form': f}, context_instance=RequestContext(request))
Exemple #41
0
def send_email(request):

    if request.POST:
        form = EmailForm(request.POST)
        if form.is_valid():

            name = form.cleaned_data['name']
            org = form.cleaned_data['org']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']

            send_mail(subject=subject,
                      message=message,
                      from_email=email,
                      auth_user='******',
                      auth_password='******',
                      recipient_list=['*****@*****.**'])

    return HttpResponseRedirect('/')
Exemple #42
0
def new_automation(request, alert_type):
    alert_type = get_object_or_404(AlertType, slug=alert_type, unit__in=request.units)

    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            if AlertEmailTemplate.objects.filter(alerttype=alert_type, hidden=False, threshold=form.cleaned_data['threshold']).count() > 0:
                errors = form._errors.setdefault("threshold", ErrorList())
                errors.append(u'An e-mail with this threshold already exists.' )
            else:
                f = form.save(commit=False)
                f.alerttype = alert_type
                f.created_by = request.user.username            
                f.save()
                messages.success(request, "Created new automated email for %s." % alert_type.code)
                l = LogEntry(userid=request.user.username,
                      description="Created new automated email %s." % alert_type.code,
                      related_object=form.instance)
                l.save()            
                return HttpResponseRedirect(reverse('alerts.views.view_automation', kwargs={'alert_type':alert_type.slug}))
    else:
        form = EmailForm()

    sample_alert = Alert.objects.filter(alerttype=alert_type, hidden=False)[0]

    email_tags = [
        ("person.name","The name of the student that has triggered the alert"),
        ("person.first_name", "The first name of the student."),
        ("person.last_name", "The last name of the student."),
        ("person.middle_name", "The middle name of the student."),
        ("person.emplid", "The student's emplid."),
        ("person.email", "The student's email."),
        ("person.title", "The student's title."),
        ("description","The description of the alert.")
    ]
    
    for k, v in sample_alert.details.iteritems():
        email_tags.append( ("details."+k, "For example, (" + str(v) + ")") )
    
    return render(request, 'alerts/new_automation.html', { 'alert_type':alert_type, 'form': form, 'email_tags':email_tags })
Exemple #43
0
def register(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = EmailForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return HttpResponseRedirect('/fb/login/')
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = EmailForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'fb/register.html', {'form': form})
Exemple #44
0
def sendmail(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            firstname = form.cleaned_data['firstname']
            lastname = form.cleaned_data['lastname']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            botcheck = form.cleaned_data['botcheck'].lower()
            message = form.cleaned_data['message']

            if botcheck == 'yes':
                try:
                    fullemail = firstname + " " + lastname + " " + "<" + email + ">" + " "
                    send_mail(subject, message, fullemail,
                              ['*****@*****.**'])
                    return HttpResponseRedirect('/email/thankyou/')
                except:
                    return HttpResponseRedirect('/email/')
        else:
            return HttpResponseRedirect('/email/')
    else:
        return HttpResponseRedirect('/email/')
Exemple #45
0
def register(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = EmailForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return HttpResponseRedirect('/fb/login/')
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = EmailForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'fb/register.html', {'form': form})
Exemple #46
0
def	Page6(request):


    if CheckAccess(request,'5') != 'OK':
	return render_to_response("notaccess.html")

    try:
	contract_id = request.session['contract_id']
    except:
	return HttpResponseRedirect('/contract')


    ### --- Проверка доступа именно к этой заявке ---
    if CheckAccess(request,'4') != 'OK' and CheckDAccess(GetUserKod(request),contract_id) != 'OK':
	return HttpResponseRedirect('/contract')


    if request.method == 'POST':
	form = EmailForm(request.POST)
	if form.is_valid():
	    email = form.cleaned_data['email']
	    ### --- Доступно только для автора заявки ---
	    if GetUserKod(request) == request.session['author_kod']:
		Email2Ruk(email,contract_id)


    ### --- Получение данных заявки ---
    data = GetDData(contract_id)
    author_kod = data[9]
    request.session['author_kod'] = author_kod

    form = EmailForm()


    c = RequestContext(request,{'data':data,'form':form})
    c.update(csrf(request))
    return render_to_response("contract/page6.html",c)
Exemple #47
0
def	TmcData5(request):


    if CheckAccess(request,'2') != 'OK':
	return render_to_response("tmc/notaccess/tmc.html")


    ## --- Номер заявки ---
    try:
	tmc_id = request.GET['tmc_id']
	request.session['tmc_id'] = tmc_id
    except:
	pass

    try:
	tmc_id = request.session['tmc_id']
    except:
	return HttpResponseRedirect("/tmc")


    if request.method == 'POST':
	form = EmailForm(request.POST)
	if form.is_valid():
	    email = form.cleaned_data['email']
	    Email2Ruk(email,tmc_id)



    d = GetTmcData(tmc_id)

    form = EmailForm(None)

    s = GetLastStatus(tmc_id)

    c = RequestContext(request,{'d':d,'form':form,'s':s})
    c.update(csrf(request))
    return render_to_response("tmc/tmcdata5.html",c)
def send_email(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            try:
                send_mail(
                    data['subject'],
                    data['content'],
                    '*****@*****.**',
                    ['*****@*****.**'],
                    fail_silently=False,
                )
            except:
                template_form = TemplateForm(request.POST)
                return render(
                    request, 'email.html', {
                        'form': form,
                        'template_form': template_form,
                        'message': 'Failed to Send to the Recipient!'
                    })
            return render(request, 'email_success.html',
                          {'email': data['email']})
        raise Http404
Exemple #49
0
def email_draft_create_view(request, pk):
    issue = _get_issue_for_emails(request, pk)
    case_email_address = build_clerk_address(issue, email_only=True)
    case_emails = get_case_emails(issue)
    templates = EmailTemplate.objects.filter(
        Q(topic=issue.topic) | Q(topic="GENERAL")).order_by("-created_at")
    for template in templates:
        # Annotate with url
        qs = request.GET.copy()
        qs["template"] = template.pk
        template.url = "?" + qs.urlencode()

    parent_email = None
    if request.method == "POST":
        default_data = {
            "from_address": case_email_address,
            "state": EmailState.DRAFT,
            "issue": issue,
            "sender": request.user,
        }
        data = merge_form_data(request.POST, default_data)
        form = EmailForm(data, files=request.FILES)
        if form.is_valid():
            email = form.save()
            messages.success(request, "Draft created")
            return redirect("case-email-edit", issue.pk, email.pk)
    else:
        # It's a GET request.
        parent_id = request.GET.get("parent")
        template_id = request.GET.get("template")
        initial = {}
        if parent_id:
            try:
                parent_email = Email.objects.get(id=parent_id)
                _process_email_for_display(parent_email)
                initial["subject"] = parent_email.subject
                if parent_email.state == EmailState.INGESTED:
                    initial["to_address"] = parent_email.from_address
                else:
                    initial["to_address"] = parent_email.to_address
            except Email.DoesNotExist:
                raise Http404()
        if template_id:
            try:
                template = EmailTemplate.objects.get(id=template_id)
                initial["text"] = template.text
                initial["subject"] = template.subject
            except EmailTemplate.DoesNotExist:
                raise Http404()

        form = EmailForm(initial=initial)

    context = {
        "issue": issue,
        "parent_email": parent_email,
        "form": form,
        "case_emails": case_emails,
        "case_email_address": case_email_address,
        "templates": templates,
        "is_disabled": False,
    }
    return render(request, "case/case/email/draft_create.html", context)
def email_changeform(request, id=None):
    if request.method == 'POST':
        # Submitting the form
        form = EmailForm(request.POST)
        change = False
        if form.is_valid():
            f = form.cleaned_data
            server = xmlrpclib.Server('https://api.webfaction.com/')
            session_id, account = server.login(settings.WEBFACTION_USERNAME, settings.WEBFACTION_PASSWORD)
            if id == None:
                # Creating a new email
                if f['create_mailbox']:
                    mailbox_name = generate_mailbox_name(f['email_address'])
                    password = server.create_mailbox(session_id, mailbox_name, f['enable_spam_protection'])['password']
                    targets = generate_targets(mailbox_name, f['redirect'])
                else:
                    targets = generate_targets(None, f['redirect'])
                server.create_email(session_id, f['email_address'], targets, f['autoresponder_on'], f['autoresponder_subject'], f['autoresponder_message'])
                email_msg = "Created email address %s" % f['email_address']
                l = Log(user=request.user, action=email_msg)
                l.save()
                messages.add_message(request, messages.INFO, email_msg)
                if f['create_mailbox']:
                    mailbox_msg = "Created mailbox %s" % mailbox_name
                    password_msg = mailbox_msg +" with password %s" % password
                    if settings.WEBFACTION_LOG_PASSWORD:
                        l = Log(user=request.user, action=password_msg)
                    else:
                        l = Log(user=request.user, action=mailbox_msg)
                    l.save()
                    messages.add_message(request, messages.INFO, password_msg)
            else:
                # Editing an existing email
                change = True
                message_list = []
                update_email = False
                if f['autoresponder_on']!=f['autoresponder_on_prev']:
                    message_list.append("Autoresponder Status for %s changed to %s" % (f['email_address'], f['autoresponder_on']))
                    update_email = True
                if f['autoresponder_subject']!=f['autoresponder_subject_prev']:
                    message_list.append("Autoresponder Subject for %s changed from '%s' to '%s'" % (f['email_address'], f['autoresponder_subject_prev'], f['autoresponder_subject']))
                    update_email = True
                if f['autoresponder_message']!=f['autoresponder_message_prev']:
                    message_list.append("Autoresponder Message for %s changed from '%s' to '%s'" % (f['email_address'], f['autoresponder_message_prev'], f['autoresponder_message']))
                    update_email = True
                if f['redirect']!=f['redirect_prev']:
                    message_list.append("Redirect Address for %s changed from '%s' to '%s'" % (f['email_address'], f['redirect_prev'], f['redirect']))
                    update_email = True
                if update_email:
                    mailbox_name = f.get('mailbox_prev', None)
                    targets = generate_targets(mailbox_name, f['redirect'])
                    server.update_email(session_id, f['email_address'], targets, f['autoresponder_on'], f['autoresponder_subject'], f['autoresponder_message'], f['email_address'])
                if f['enable_spam_protection']!=f['enable_spam_protection_prev']:
                    try:
                        server.update_mailbox(session_id, mailbox_name, f['enable_spam_protection'])
                        message_list.append("Spam Protection Status for %s changed to %s" % (f['enable_spam_protection'], f['email_address']))
                    except xmlrpclib.Fault: #Probably means this is a redirect only address
                        message_list.append("Error. Can only change spam protection status on addresses with their own mailbox")
                for msg in message_list:
                    messages.add_message(request, messages.INFO, msg)
                    l = Log(user=request.user, action=msg)
                    l.save()
            return HttpResponseRedirect('..')
    else:
        # Blank form
        if id==None: # We are creating
            change = False
            form = EmailForm()
        else: # We are updating
            change = True
            email_accounts = get_email_accounts()
            email_account = [x for x in email_accounts if x['id']==int(id)][0] # Assume only one match
            if email_account.get('mailbox', None):
                # Has a mailbox
                enable_spam_protection = email_account['mailbox']['enable_spam_protection']
            else:
                # Is just a redirect
                enable_spam_protection = False
            if email_account.get('mailbox', False):
                mailbox_name = email_account['mailbox']['mailbox']
            else:
                mailbox_name = ''
            form = EmailForm({
                'email_address': email_account['email_address'],
                'email_address_prev': email_account['email_address'],
                'autoresponder_on': email_account['autoresponder_on'],
                'autoresponder_on_prev': email_account['autoresponder_on'],
                'autoresponder_subject': email_account['autoresponder_subject'],
                'autoresponder_subject_prev': email_account['autoresponder_subject'],
                'autoresponder_message': email_account['autoresponder_message'],
                'autoresponder_message_prev': email_account['autoresponder_message'],
                'enable_spam_protection': enable_spam_protection,
                'enable_spam_protection_prev': enable_spam_protection ,
                'create_mailbox': email_account.get('mailbox', False),
                'mailbox_prev' : mailbox_name,
                'redirect': email_account.get('redirect', ''),
                'redirect_prev': email_account.get('redirect', ''),
            })
            del form.fields['create_mailbox']
    return render_to_response('email_changeform.html', {
        'change': change,
        'form': form,
        },
        RequestContext(request),
    )
Exemple #51
0
def email_changeform(request, id=None):
    if request.method == 'POST':
        # Submitting the form
        form = EmailForm(request.POST)
        change = False
        if form.is_valid():
            f = form.cleaned_data
            server = xmlrpclib.Server('https://api.webfaction.com/')
            session_id, account = server.login(settings.WEBFACTION_USERNAME,
                                               settings.WEBFACTION_PASSWORD)
            if id == None:
                # Creating a new email
                if f['create_mailbox']:
                    mailbox_name = generate_mailbox_name(f['email_address'])
                    password = server.create_mailbox(
                        session_id, mailbox_name,
                        f['enable_spam_protection'])['password']
                    targets = generate_targets(mailbox_name, f['redirect'])
                else:
                    targets = generate_targets(None, f['redirect'])
                server.create_email(session_id, f['email_address'], targets,
                                    f['autoresponder_on'],
                                    f['autoresponder_subject'],
                                    f['autoresponder_message'])
                email_msg = "Created email address %s" % f['email_address']
                l = Log(user=request.user, action=email_msg)
                l.save()
                request.user.message_set.create(message=email_msg)
                if f['create_mailbox']:
                    mailbox_msg = "Created mailbox %s" % mailbox_name
                    password_msg = mailbox_msg + " with password %s" % password
                    if settings.WEBFACTION_LOG_PASSWORD:
                        l = Log(user=request.user, action=password_msg)
                    else:
                        l = Log(user=request.user, action=mailbox_msg)
                    l.save()
                    request.user.message_set.create(message=password_msg)
            else:
                # Editing an existing email
                change = True
                msgs = []
                update_email = False
                if f['autoresponder_on'] != f['autoresponder_on_prev']:
                    msgs.append("Autoresponder Status for %s changed to %s" %
                                (f['email_address'], f['autoresponder_on']))
                    update_email = True
                if f['autoresponder_subject'] != f[
                        'autoresponder_subject_prev']:
                    msgs.append(
                        "Autoresponder Subject for %s changed from '%s' to '%s'"
                        % (f['email_address'], f['autoresponder_subject_prev'],
                           f['autoresponder_subject']))
                    update_email = True
                if f['autoresponder_message'] != f[
                        'autoresponder_message_prev']:
                    msgs.append(
                        "Autoresponder Message for %s changed from '%s' to '%s'"
                        % (f['email_address'], f['autoresponder_message_prev'],
                           f['autoresponder_message']))
                    update_email = True
                if f['redirect'] != f['redirect_prev']:
                    msgs.append(
                        "Redirect Address for %s changed from '%s' to '%s'" %
                        (f['email_address'], f['redirect_prev'],
                         f['redirect']))
                    update_email = True
                if update_email:
                    mailbox_name = f.get('mailbox_prev', None)
                    targets = generate_targets(mailbox_name, f['redirect'])
                    server.update_email(session_id, f['email_address'],
                                        targets, f['autoresponder_on'],
                                        f['autoresponder_subject'],
                                        f['autoresponder_message'],
                                        f['email_address'])
                if f['enable_spam_protection'] != f[
                        'enable_spam_protection_prev']:
                    try:
                        server.update_mailbox(session_id, mailbox_name,
                                              f['enable_spam_protection'])
                        msgs.append(
                            "Spam Protection Status for %s changed to %s" %
                            (f['enable_spam_protection'], f['email_address']))
                    except xmlrpclib.Fault:  #Probably means this is a redirect only address
                        msgs.append(
                            "Error. Can only change spam protection status on addresses with their own mailbox"
                        )
                for msg in msgs:
                    messages.info(request, msg)
                    l = Log(user=request.user, action=msg)
                    l.save()
            return HttpResponseRedirect('..')
    else:
        # Blank form
        if id == None:  # We are creating
            change = False
            form = EmailForm()
        else:  # We are updating
            change = True
            email_accounts = get_email_accounts()
            email_account = [x for x in email_accounts
                             if x['id'] == int(id)][0]  # Assume only one match
            if email_account.get('mailbox', None):
                # Has a mailbox
                enable_spam_protection = email_account['mailbox'][
                    'enable_spam_protection']
            else:
                # Is just a redirect
                enable_spam_protection = False
            if email_account.get('mailbox', False):
                mailbox_name = email_account['mailbox']['mailbox']
            else:
                mailbox_name = ''
            form = EmailForm({
                'email_address':
                email_account['email_address'],
                'email_address_prev':
                email_account['email_address'],
                'autoresponder_on':
                email_account['autoresponder_on'],
                'autoresponder_on_prev':
                email_account['autoresponder_on'],
                'autoresponder_subject':
                email_account['autoresponder_subject'],
                'autoresponder_subject_prev':
                email_account['autoresponder_subject'],
                'autoresponder_message':
                email_account['autoresponder_message'],
                'autoresponder_message_prev':
                email_account['autoresponder_message'],
                'enable_spam_protection':
                enable_spam_protection,
                'enable_spam_protection_prev':
                enable_spam_protection,
                'create_mailbox':
                email_account.get('mailbox', False),
                'mailbox_prev':
                mailbox_name,
                'redirect':
                email_account.get('redirect', ''),
                'redirect_prev':
                email_account.get('redirect', ''),
            })
            del form.fields['create_mailbox']
    return render_to_response(
        'email_changeform.html',
        {
            'change': change,
            'form': form,
        },
        RequestContext(request),
    )
Exemple #52
0
def index(request):
    email = ''
    groups = models.Group.objects.all()
    user = None
    if request.user.is_authenticated():
        email = request.user.email
        user = request.user
    # subscribes = Subscribe.objects.filter(is_active=True)
    if request.method == 'POST':
        email_form = EmailForm(request.POST)
        forms = []
        for group in groups:
            SubscriberForm = get_subscriber_form(models.Subscribe.objects.filter(group=group, is_active=True))
            forms.append({
                'group': group,
                'form': SubscriberForm(request.POST, prefix=group.id)
            })
        subscribes = []
        is_valid = True
        for form in forms:
            subscriber_form = form['form']
            if not subscriber_form.is_valid():
                is_valid = False
            else:
                subscribes += subscriber_form.cleaned_data['subscribes']

        if not email_form.is_valid():
            is_valid = False

        if is_valid:
            subscribes = set(subscribes)
            try:
                subscriber = models.Subscriber.objects.get(email=email_form.cleaned_data['email'])
                exists_subscribes = list(subscriber.subscribe.all())
                for subscribe in subscribes:
                    if subscribe not in exists_subscribes:
                        subscriber.subscribe.add(subscribe)

                for exists_subscribe in exists_subscribes:
                    if exists_subscribe not in subscribes:
                        subscriber.subscribe.remove(exists_subscribe)

            except models.Subscriber.DoesNotExist:
                subscriber = models.Subscriber(user=user, email=email)
                subscriber.save()
                for subscribe in set(subscribes):
                    subscriber.subscribe.add(subscribe)
            return redirect('subscribe:frontend:index')
    else:
        email_form = EmailForm(initial={
            'email': email
        })
        forms = []
        for group in groups:
            initial_subscribes = []
            if email:
                try:
                    subscriber = models.Subscriber.objects.get(email=email)
                    initial_subscribes = subscriber.subscribe.all()
                except models.Subscriber.DoesNotExist:
                    pass
            SubscriberForm = get_subscriber_form(models.Subscribe.objects.filter(group=group, is_active=True))
            forms.append({
                'group': group,
                'form': SubscriberForm(prefix=group.id, initial={
                    'subscribes': initial_subscribes
                })
            })
    return render(request, 'subscribe/frontend/index.html', {
        'forms': forms,
        'email_form': email_form
    })
Exemple #53
0
def index(request):
    email = ''
    groups = models.Group.objects.all()
    user = None
    if request.user.is_authenticated():
        email = request.user.email
        user = request.user
    # subscribes = Subscribe.objects.filter(is_active=True)
    if request.method == 'POST':
        email_form = EmailForm(request.POST)
        forms = []
        for group in groups:
            SubscriberForm = get_subscriber_form(
                models.Subscribe.objects.filter(group=group, is_active=True))
            forms.append({
                'group': group,
                'form': SubscriberForm(request.POST, prefix=group.id)
            })
        subscribes = []
        is_valid = True
        for form in forms:
            subscriber_form = form['form']
            if not subscriber_form.is_valid():
                is_valid = False
            else:
                subscribes += subscriber_form.cleaned_data['subscribes']

        if not email_form.is_valid():
            is_valid = False

        if is_valid:
            subscribes = set(subscribes)
            try:
                subscriber = models.Subscriber.objects.get(
                    email=email_form.cleaned_data['email'])
                exists_subscribes = list(subscriber.subscribe.all())
                for subscribe in subscribes:
                    if subscribe not in exists_subscribes:
                        subscriber.subscribe.add(subscribe)

                for exists_subscribe in exists_subscribes:
                    if exists_subscribe not in subscribes:
                        subscriber.subscribe.remove(exists_subscribe)

            except models.Subscriber.DoesNotExist:
                subscriber = models.Subscriber(user=user, email=email)
                subscriber.save()
                for subscribe in set(subscribes):
                    subscriber.subscribe.add(subscribe)
            return redirect('subscribe:frontend:index')
    else:
        email_form = EmailForm(initial={'email': email})
        forms = []
        for group in groups:
            initial_subscribes = []
            if email:
                try:
                    subscriber = models.Subscriber.objects.get(email=email)
                    initial_subscribes = subscriber.subscribe.all()
                except models.Subscriber.DoesNotExist:
                    pass
            SubscriberForm = get_subscriber_form(
                models.Subscribe.objects.filter(group=group, is_active=True))
            forms.append({
                'group':
                group,
                'form':
                SubscriberForm(prefix=group.id,
                               initial={'subscribes': initial_subscribes})
            })
    return render(request, 'subscribe/frontend/index.html', {
        'forms': forms,
        'email_form': email_form
    })
Exemple #54
0
def save_email_schedule(request, workflow, action, schedule_item):
    """
    Function to handle the creation and edition of email items
    :param request: Http request being processed
    :param workflow: workflow item related to the action
    :param action: Action item related to the schedule
    :param schedule_item: Schedule item or None if it is new
    :return:
    """

    # Create the form to ask for the email subject and other information
    form = EmailForm(data=request.POST or None,
                     instance=schedule_item,
                     columns=workflow.columns.filter(is_key=True))

    now = datetime.datetime.now(pytz.timezone(settings.TIME_ZONE))
    # Check if the request is GET, or POST but not valid
    if request.method == 'GET' or not form.is_valid():
        # Render the form
        return render(request, 'scheduler/email.html', {
            'action': action,
            'form': form,
            'now': now
        })

    # We are processing a valid POST request

    # Check that the email column has correct values (FIX)
    # correct_emails = all([validate_email(x[col_idx]) for x in data_table])

    # Save the schedule item object
    s_item = form.save(commit=False)

    # Assign additional fields and save
    s_item.user = request.user
    s_item.action = action
    s_item.type = 'email_send'
    s_item.status = 0  # Pending
    s_item.save()

    # Create the payload to record the event in the log
    payload = {
        'workflow': workflow.name,
        'workflow_id': workflow.id,
        'action': action.name,
        'action_id': action.id,
        'execute': s_item.execute.isoformat(),
        'subject': s_item.subject,
        'email_column': s_item.email_column.name,
        'send_confirmation': s_item.send_confirmation,
        'track_read': s_item.track_read
    }

    # Log the operation
    if schedule_item:
        log_type = 'schedule_email_edit'
    else:
        log_type = 'schedule_email_create'
    logs.ops.put(request.user, log_type, workflow, payload)

    # Notify the user. Show the time left until execution and a link to
    # view the scheduled events with possibility of editing/deleting.
    # Successful processing.
    now = datetime.datetime.now(pytz.timezone(settings.TIME_ZONE))
    tdelta = s_item.execute - now
    return render(request, 'scheduler/email_done.html', {
        'tdelta': str(tdelta),
        's_item': s_item
    })
Exemple #55
0
    def post(self, request, *args, **kwargs):
        """Handles the POST request to the 'account_forgot_password' named route.

        Args: request.
        Returns: A HttpResponse with a forgot_password_recovery_status template
                 otherwise, return forgot_password template.
        """
        email_form = EmailForm(request.POST, auto_id=True)
        if email_form.is_valid():
            try:
                # get the account for that email if it exists:
                input_email = email_form.cleaned_data.get('email')
                registered_user = User.objects.get(email__exact=input_email)

                # generate a recovery hash url for that account:
                recovery_hash = Hasher.gen_hash(registered_user)
                recovery_hash_url = request.build_absolute_uri(
                    reverse(
                        'account_reset_password',
                        kwargs={'recovery_hash': recovery_hash}
                    ))

                # compose the email:
                recovery_email_context = RequestContext(
                    request,
                    {'recovery_hash_url': recovery_hash_url})
                recovery_email = SendGrid.compose(
                    sender='Troupon <*****@*****.**>',
                    recipient=registered_user.email,
                    subject='Troupon: Password Recovery',
                    html=loader.get_template(
                        'authentication/forgot_password_recovery_email.html'
                    ).render(recovery_email_context),
                    text=loader.get_template(
                        'authentication/forgot_password_recovery_email.txt'
                    ).render(recovery_email_context),
                )
                # send it and get the request status:
                email_status = SendGrid.send(recovery_email)

                # inform the user of the status of the recovery mail:
                context = {
                    'page_title': 'Forgot Password',
                    'registered_user': registered_user,
                    'recovery_mail_status': email_status,
                }
                return render(
                    request,
                    'authentication/forgot_password_recovery_status.html',
                    context)

            except ObjectDoesNotExist:
                # set an error message:
                messages.add_message(
                    request, messages.ERROR,
                    'The email you entered does not \
                    belong to a registered user!')

        context = {
            'page_title': 'Forgot Password',
            'email_form': email_form,
        }
        context.update(csrf(request))
        return render(request, 'authentication/forgot_password.html', context)