示例#1
0
文件: tasks.py 项目: CCLab/sezam
def send_report(pia_request, status, **kwargs):
    """
    Send a report message to the User.
    """
    template= kwargs.get('template', 'emails/report_overdue_to_user.txt')
    message_subject= kwargs.get('subject', None)
    report_date= kwargs.get('report_date', None)
    if report_date is None:
        report_date= datetime.strftime(pia_request.created, '%d.%m.%Y')
    authority= pia_request.authority
    user= pia_request.user
    try:
        email_to= user.email
    except:
        print AppMessage('UserEmailNotFound', value=(user.username,)).message
        return None
    email_from= DEFAULT_FROM_EMAIL
    message_subject= get_message_subject(status, number=pia_request.pk,
                                         date=report_date)
    message_content= render_to_string(template, {'email_to': email_to,
        'request_id': str(pia_request.pk), 'request_date': report_date,
        'authority': authority, 'user': user, 'domain': get_domain_name()})
    message_request= EmailMessage(message_subject, message_content,
        DEFAULT_FROM_EMAIL, [email_to], headers = {'Reply-To': email_from})
    try: # sending the message to the User, check if it doesn't fail.
        message_request.send(fail_silently=False)
    except Exception as e:
        print AppMessage('MailSendFailed').message % e
        return None
    return True # Success.
示例#2
0
文件: tasks.py 项目: CCLab/sezam
def send_reminder(pia_request, overdue_date=None, **kwargs):
    """
    Send a reminder message to the Authority.
    """
    template= kwargs.get('email_template', 'emails/reminder_overdue.txt')
    if overdue_date is None:
        overdue_date= datetime.strftime(pia_request.created, '%d.%m.%Y')
    authority= pia_request.authority
    try:
        email_to= authority.email
    except:
        print AppMessage('AuthEmailNotFound', value=(authority.slug, authority.name,)).message
        return None
    email_from= email_from_name(pia_request.user.get_full_name(),
                                id=pia_request.id,
                                delimiter='.')
    message_subject= get_message_subject('overdue',
                                         number=pia_request.pk,
                                         date=overdue_date)
    message_content= render_to_string(template, { 'email_to': email_to,
        'request_id': str(pia_request.pk), 'request_date': overdue_date,
        'authority': authority, 'info_email': 'info@%s' % get_domain_name()})
    message_request= EmailMessage(message_subject, message_content,
        DEFAULT_FROM_EMAIL, [email_to], headers = {'Reply-To': email_from})
    try: # sending the message to the Authority, check if it doesn't fail.
        message_request.send(fail_silently=False)
    except Exception as e:
        print >> sys.stderr, '[%s] %s' % (datetime.now().isoformat(),
            AppMessage('MailSendFailed').message % e)
        return None
    return True # Success. 
示例#3
0
文件: views.py 项目: CCLab/sezam
def add_authority(request, slug=None, **kwargs):
    """
    Add new Authority in case if it can't be found in the database.
    """
    user_message = request.session.pop('user_message', {})
    template = kwargs.get('template', 'add_record.html')
    admin_mail_template = 'emails/authority_added.txt'
    from_link = None

    # Show the form to enter Authority data.
    if request.method == 'GET':
        from_link = request.GET.get('from', None)
        initial = {'slug': 'slug', 'order': 100}
        form = AuthorityProfileForm(initial=initial)

    # Check if the form is correct, save Authority in the db.
    elif request.method == 'POST':
        form = AuthorityProfileForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            authority = AuthorityProfile(**data)
            try:
                authority.save()
            except Exception as e:
                print >> sys.stderr, '[%s] %s' % (datetime.now().isoformat(), e)
                user_message = update_user_message({}, e.args[0], 'fail')
                form = AuthorityProfileForm(instance=authority)
            if authority.id: # Added successfully.
                user_message = update_user_message(user_message,
                    AppMessage('AuthSavedInactive').message % authority.name,
                    'success')

                # Send notification to managers.
                subject = _(u'New authority in the db: ') + authority.name
                content = render_to_string(admin_mail_template, {
                    'authority': authority, 'user': request.user,
                    'domain': get_domain_name()})
                try:
                    send_mail_managers(subject, content, fail_silently=False,
                                       headers={'Reply-To': request.user.email})
                except Exception as e:
                    print >> sys.stderr, '[%s] %s' % (datetime.now().isoformat(), e)

                # Create notifier.
                item = TaggedItem.objects.create(name=authority.name,
                                                content_object=authority)
                evnt = EventNotification.objects.create(
                    item=item, action='active', receiver=request.user,
                    summary='Authority %s becomes active' % authority.name)

                request.session['user_message'] = user_message
                return redirect(reverse('display_authorities'))

    return render_to_response(template,
                              {'form': form,
                               'from': from_link,
                               'mode': 'authority',
                               'user_message': user_message,
                               'page_title': _(u'Add authority')},
        context_instance=RequestContext(request))
示例#4
0
文件: tasks.py 项目: CCLab/sezam
def check_mail(mailbox_settings=None):
    """
    Checks mail for responses.
    If there is any response, creates a Message and adds it to the Thread.
    Also processes attachments in the emails and adds them to newly
    created messages.
    """

    # Pattern to look for in `to` fields: delimiters include dash and dot.
    addr_template= r'(\-|\.){1}\d+\@%s' % get_domain_name()
    addr_pattern= re.compile(addr_template+'$') # End of line is required only locally.

    # Collect mailboxes to check. NB: Mailbox should always be a list.
    messages_total= 0
    mailboxes= collect_mailboxes(mailbox_settings)
    for mailbox in mailboxes:
        imp= MailImporter(mailbox,
                          attachment_dir=ATTACHMENT_DIR,
                          addr_template=addr_template)
        unread_messages= imp.process_mails(imp.imap_connect(), header_only=False)
        for msg in unread_messages:
            messages_total += 1
            # Extract only the first(!) meaningful e-mail address.
            try:
                field_to= [t.strip() for t in msg['header']['to'].split(',') if addr_pattern.search(t)][0]
            except:
                # There are no such address in it - is it a spam?
                # TO-DO: log it or to add the `from` address to the blacklist?
                # Should the message be deleted?
                print AppMessage('ResponseNotFound', value=msg['header']).message
                continue
            # Extracting request id.
            try:
                request_id= int(field_to.split('@')[0].rsplit('.', 1)[-1])
            except:
                try:
                    request_id= int(field_to.split('@')[0].rsplit('-', 1)[-1])
                except:
                    print AppMessage('ResponseNotFound', value=msg['header']).message
                    continue
            new_message= new_message_in_thread(request_id, msg)
            if new_message:
                report_to_user_sent= send_report(new_message.request,
                    status='response_received',
                    template='emails/response_received.txt')
    return AppMessage('CheckMailComplete', value=messages_total).message \
        % messages_total
示例#5
0
def get_resource_name(request):
    hostname= request.META.get('HTTP_HOST', None)
    try:
        return {'resource_name': Site.objects.get(domain=hostname).name}
    except:
        return {'resource_name': get_domain_name()}