Exemple #1
0
def contact_us(request):
    if request.method == 'POST':
        form = MailForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            city = form.cleaned_data['city']
            number = form.cleaned_data['number']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            feedback = form.cleaned_data['feedback']
            sg = sendgrid.SendGridAPIClient(
                apikey=
                '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'
            )

            from_email = Email('[email protected] ')
            to_email = Email("*****@*****.**")
            subject = subject
            content = Content(
                "text/plain",
                "Following email is from a user who visited Social Bot Web App"
                + "\n\n" + feedback + "\n\nFrom: " + name + "\n\nCity: " +
                city + "\n\nPhone Number: " + number + "\n\nEmail: " + email)
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)
            print("mail sent.")
            return HttpResponseRedirect('/feed/')
Exemple #2
0
def view_mail_thread(request, mail):
    mail = Mail.objects.get(pk=mail)
    mails = _get_mail_list(request)
    start = mail.start_of_thread()
    if not request.user.is_anonymous() \
           and request.method == "POST":
        form = MailForm(request, request.POST, request.FILES)
        if form.is_valid():
            mail = form.save(in_reply_to=start.end_of_thread())
            return redirect(reverse('preview',
                                    kwargs={'mail': mail.pk}))
    else:
        if request.user.is_anonymous():
            form = MailForm(request)
        else:
            form = MailForm(request,
                               initial={'mfrom':request.user.email,
                                        'mto':start.mto.email,
                                        'subject':'Re: %s' % start.subject})
    if start == mail:
        return locals()
    else:
        return redirect(reverse('mail',
                                kwargs={'mail':start.id})\
                        + "#mail-%d" % mail.id)
Exemple #3
0
def home(request):
    context = {}

    if request.method == 'POST':
        form = MailForm(request.POST)
        if form.is_valid():
            emails.save({'_id': form.save_mail().encode('ascii')})
            context['success'] = True

    return render(request, 'base.html', context)
Exemple #4
0
def email_me(request):
    if request.method == 'POST':
        mailForm = MailForm(request.POST)
        if mailForm.is_valid():
            send_mail(mailForm.cleaned_data['subject'],mailForm.cleaned_data['message'],mailForm.cleaned_data['email'],['*****@*****.**'])
            return HttpResponseRedirect('/news/')
        else:
            return render_to_response('mail_me.html',{'mailForm':mailForm}, RequestContext(request))
    else:
        return render_to_response('mail_me.html',{'mailForm':MailForm()}, RequestContext(request))
Exemple #5
0
def userprofile(request):
    (profile, created) = UserProfile.objects.get_or_create(user=request.user)
    form = mailform = None

    if request.method == 'POST':
        if request.POST['submit'] == 'Save':
            form = UserProfileForm(request.user,
                                   request.POST,
                                   instance=profile)
            if form.is_valid():
                form.save()
                messages.add_message(request, messages.INFO,
                                     "User profile saved.")
                return HttpResponseRedirect('.')
        elif request.POST['submit'] == 'Add email':
            mailform = MailForm(request.POST)
            if mailform.is_valid():
                m = UserExtraEmail(user=request.user,
                                   email=mailform.cleaned_data['email'],
                                   confirmed=False,
                                   token=generate_random_token(),
                                   tokensent=datetime.now())
                m.save()
                send_template_mail(
                    settings.NOTIFICATION_FROM, request.user.username, m.email,
                    'Your email address for commitfest.postgresql.org',
                    'extra_email_mail.txt', {
                        'token': m.token,
                        'user': m.user
                    })
                messages.info(
                    request,
                    "A confirmation token has been sent to %s" % m.email)
                return HttpResponseRedirect('.')
        else:
            messages.error(request,
                           "Invalid submit button pressed! Nothing saved.")
            return HttpResponseRedirect('.')

    if not form:
        form = UserProfileForm(request.user, instance=profile)
    if not mailform:
        mailform = MailForm()

    extramails = UserExtraEmail.objects.filter(user=request.user)

    return render_to_response('userprofileform.html', {
        'form': form,
        'extramails': extramails,
        'mailform': mailform,
    },
                              context_instance=RequestContext(request))
Exemple #6
0
def view_mail_thread(request, mail):
    mail = Mail.objects.get(pk=mail)
    mails = _get_mail_list(request)
    start = mail.start_of_thread()
    if not request.user.is_anonymous() \
           and request.method == "POST":
        form = MailForm(request, request.POST, request.FILES)
        if form.is_valid():
            mail = form.save(in_reply_to=start.end_of_thread())
            return redirect(reverse('preview', kwargs={'mail': mail.pk}))
    else:
        if request.user.is_anonymous():
            form = MailForm(request)
        else:
            form = MailForm(request,
                            initial={
                                'mfrom': request.user.email,
                                'mto': start.mto.email,
                                'subject': 'Re: %s' % start.subject
                            })
    if start == mail:
        return locals()
    else:
        return redirect(reverse('mail',
                                kwargs={'mail':start.id})\
                        + "#mail-%d" % mail.id)
Exemple #7
0
def email_me(request):
    if request.method == 'POST':
        mailForm = MailForm(request.POST)
        if mailForm.is_valid():
            send_mail(mailForm.cleaned_data['subject'],
                      mailForm.cleaned_data['message'],
                      mailForm.cleaned_data['email'], ['*****@*****.**'])
            return HttpResponseRedirect('/news/')
        else:
            return render_to_response('mail_me.html', {'mailForm': mailForm},
                                      RequestContext(request))
    else:
        return render_to_response('mail_me.html', {'mailForm': MailForm()},
                                  RequestContext(request))
Exemple #8
0
def write(request):
    mails = _get_mail_list(request)
    footer = get_footer_for_mail()
    if request.method == "POST":
        form = MailForm(request, request.POST, request.FILES)
        if form.is_valid():
            mail = form.save()
            return redirect(reverse('posted',
                                    kwargs={'mail': mail.pk}))
    else:
        if request.user.is_anonymous():
            form = MailForm(request)
        else:
            form = MailForm(request,
                               initial={'mfrom':request.user.email,
                                        'name':request.user.full_name})
    return locals()
Exemple #9
0
def mail():
    # 实例化表单
    form = MailForm()
    if form.validate_on_submit():
        # 获取用户提交的数据;
        toEmails = form.toEmails.data.split(',')
        toFilename = form.toFilename.data

        try:
            send_mail(toEmails, "西部开源邮件测试", toFilename)
        except Exception as e:
            flash("邮件发送失败, 失败原因: %s!" % (e))
        else:
            flash("邮件发送成功!")
        return redirect(url_for('mail'))

    return render_template('send_mail.html', form=form)
Exemple #10
0
def sent_mail(request):
    if request.method == "POST":
        form = MailForm(request.POST)
        if form.is_valid():
            sender_name = form.cleaned_data["sender_name"]
            email = form.cleaned_data["email"]
            letter_text = form.cleaned_data["letter_text"]
            try:
                send_mail("Сообщение от ", letter_text, email, ["*****@*****.**"], fail_silently=False)
                message = "Сообщение отправлено!"
            except:
                message = "Ошибка отправки!!"

            request.session["mail_message"] = message
        else:
            request.session["mail_message"] = "Ошибка формы отправки!"
    return redirect("/")
Exemple #11
0
def mail_form(mail_id=0):
    form = MailForm()

    if request.method == 'POST':

        recipient = form.recipient.data
        subject = form.subject.data
        text = form.text.data

        mail_status = None
        if request.form['submit'] == 'save':
            mail_status = 'draft'
        if request.form['submit'] == 'send':
            mail_status = 'sent'

        if mail_id == 0:
            r1 = requests.put(api_url + '/mail',
                              headers=headers,
                              auth=(session['user']['token'], 'unused'),
                              data=json.dumps({'recipient': recipient,
                                               'subject': subject,
                                               'text': text,
                                               'status': mail_status}))
        else:
            r1 = requests.put(api_url + '/mail/' + str(mail_id),
                              headers=headers,
                              auth=(session['user']['token'], 'unused'),
                              data=json.dumps({'recipient': recipient,
                                               'subject': subject,
                                               'text': text,
                                               'status': mail_status}))
        if r1.status_code == 400:
            flash(json.loads(r1.text)['error'], 'danger')
        elif r1.status_code == 201 or r1.status_code == 200:
            if request.form['submit'] == 'send':
                flash('Mail was successfully sent', 'success')
            if request.form['submit'] == 'save':
                flash('Mail was successfully saved', 'success')
        else:
            return _render_template('error_page.html', status_code=r1.status_code)

        return redirect(url_for('get_all_mails'))

    else:
        return _render_template('mail_form.html',
                                form=form,
                                section='new',
                                new_mails_count=new_mails_count(),
                                draft_mails_count=draft_mails_count())
Exemple #12
0
def write(request):
    mails = _get_mail_list(request)
    footer = get_footer_for_mail()
    if request.method == "POST":
        form = MailForm(request, request.POST, request.FILES)
        if form.is_valid():
            mail = form.save()
            return redirect(reverse('posted', kwargs={'mail': mail.pk}))
    else:
        if request.user.is_anonymous():
            form = MailForm(request)
        else:
            form = MailForm(request,
                            initial={
                                'mfrom': request.user.email,
                                'name': request.user.full_name
                            })
    return locals()
Exemple #13
0
def get_mail(mail_id, section):
    if section not in sections:
        return _render_template('error_page.html', status_code=404, message='Page not found')

    r = requests.get(api_url + '/mail/' + str(mail_id),
                     headers=headers,
                     auth=(session['user']['token'], 'unused'))

    if r.status_code == 200:
        mail = json.loads(r.text)['mail']

        # Set the flag is_viewed as True
        if section == 'inbox':
            requests.put(api_url + '/mail/' + str(mail_id),
                         headers=headers,
                         auth=(session['user']['token'], 'unused'),
                         data=json.dumps({'recipient': None,
                                          'subject': None,
                                          'text': None,
                                          'status': None,
                                          'is_viewed': True}))

        # Fill form fields
        if section == 'draft':
            form = MailForm()
            form.recipient.data = mail['recipient']
            form.subject.data = mail['subject']
            form.text.data = mail['text']

            return _render_template('mail_form.html',
                                    section='draft',
                                    form=form,
                                    updated_id=mail_id,
                                    new_mails_count=new_mails_count(),
                                    draft_mails_count=draft_mails_count())

        return _render_template('mail.html',
                                section=section,
                                mail=format_mail(mail),
                                new_mails_count=new_mails_count(),
                                draft_mails_count=draft_mails_count())

    else:
        return _render_template('error_page.html', status_code=r.status_code)
Exemple #14
0
def mail2all(request, course_id):
    course = get_object_or_404(Course, pk=course_id)
    # Re-compute list of recipients on every request, for latest updates
    students = User.objects.filter(profile__courses__pk=course_id)
    maillist = ','.join(students.values_list('email', flat=True))

    if request.method == "POST":
        if 'subject' in request.POST and 'message' in request.POST:
            # Initial form submission, render preview
            request.session['subject'] = request.POST['subject']
            request.session['message'] = request.POST['message']
            student = students[0]
            preview_subject = _replace_placeholders(request.POST['subject'],
                                                    student, course)
            preview_message = _replace_placeholders(request.POST['message'],
                                                    student, course)
            return render(
                request, 'mail_preview.html', {
                    'preview_subject': preview_subject,
                    'preview_message': preview_message,
                    'preview_from': request.user.email,
                    'course': course
                })
        elif 'subject' in request.session and 'message' in request.session:
            # Positive preview, send it
            data = [
                (_replace_placeholders(request.session['subject'], s, course),
                 _replace_placeholders(request.session['message'], s,
                                       course), request.user.email, [s.email])
                for s in students
            ]
            sent = send_mass_mail(data, fail_silently=True)
            messages.add_message(request, messages.INFO,
                                 '%u message(s) sent.' % sent)
            return redirect('teacher:index')

    # show empty form in all other cases
    mailform = MailForm()
    return render(request, 'mail_form.html', {
        'maillist': maillist,
        'course': course,
        'mailform': mailform
    })