Ejemplo n.º 1
0
def mass_mail_sending_view(request):
    m1 = EmailMessage('First Test message', 'This is the first test email',
                      '*****@*****.**',
                      ['*****@*****.**', '*****@*****.**'])
    m2 = EmailMessage('Second Test message', 'This is the second test email',
                      '*****@*****.**',
                      ['*****@*****.**', '*****@*****.**'])

    c = SMTPConnection()
    c.send_messages([m1, m2])

    return HttpResponse("Mail sent")
Ejemplo n.º 2
0
def mass_mail_sending_view(request):
    m1 = EmailMessage(
        'First Test message',
        'This is the first test email',
        '*****@*****.**',
        ['*****@*****.**', '*****@*****.**'])
    m2 = EmailMessage(
        'Second Test message',
        'This is the second test email',
        '*****@*****.**',
        ['*****@*****.**', '*****@*****.**'])

    c = SMTPConnection()
    c.send_messages([m1,m2])

    return HttpResponse("Mail sent")
Ejemplo n.º 3
0
    def save(self, subject=None):
        if subject is None:
            subject = '%s wants you to learn more about out this Vibha Project' % self.cleaned_data[
                'name']
        message = self.cleaned_data['body'] + self.cleaned_data['project_info']
        from_email = settings.DEFAULT_FROM_EMAIL

        # Split into several messages so recipients dont see the other recipients
        msg = []
        for recipient in self.cleaned_data['to_email']:
            m = EmailMessage(subject, message, from_email, [recipient])
            m.content_subtype = "html"
            msg.append(m)

        connection = SMTPConnection()
        connection.send_messages(msg)
Ejemplo n.º 4
0
def _our_send_mass_mail(datatuple, form_address, fail_silently=False, auth_user=None,
                   auth_password=None):
    """Our hacked version of the django send_mass_mail function, which relies
    on django having this patch:
    http://code.djangoproject.com/attachment/ticket/9214/9214-EmailMessage-r9084.diff
    """
    connection = SMTPConnection(username=auth_user, password=auth_password,
                                fail_silently=fail_silently)
    headers = {'From': form_address}
    messages = [EmailMessage(subject, message, sender, recipient, headers=headers)
                for subject, message, sender, recipient in datatuple]
    return connection.send_messages(messages)
Ejemplo n.º 5
0
    def handle(self, *args, **options):
        if not options["group_slug"]:
            sys.exit(__doc__)

        self._set_language(options["lang"])

        group = self._get_group(options["group_slug"])
        accounts = self._get_accounts(group)
        emails = self._build_emails(accounts)

        if not options["yes"] and not options["debug"]:
            answer = input("Send emails y/N ")

            if answer.lower() != "y":
                print("Canceled sending")
                sys.exit(0)

        if emails:
            if options["debug"]:
                self._print_debug(emails)
            else:
                connection = SMTPConnection()
                connection.send_messages(emails)
Ejemplo n.º 6
0
    def handle(self, *args, **options):
        if not options['group_slug']:
            sys.exit(__doc__)

        self._set_language(options['lang'])

        group = self._get_group(options['group_slug'])
        accounts = self._get_accounts(group)
        emails = self._build_emails(accounts)

        if not options['yes'] and not options['debug']:
            answer = raw_input(u"Send emails y/N ".encode('utf-8'))

            if answer.lower() != 'y':
                print "Canceled sending"
                sys.exit(0)

        if emails:
            if options['debug']:
                self._print_debug(emails)
            else:
                connection = SMTPConnection()
                connection.send_messages(emails)
Ejemplo n.º 7
0
    def handle(self, *args, **options):
        if not options['group_slug']:
            sys.exit(__doc__)

        self._set_language(options['lang'])

        group = self._get_group(options['group_slug'])
        accounts = self._get_accounts(group)
        emails = self._build_emails(accounts)

        if not options['yes'] and not options['debug']:
            answer = raw_input(u"Send emails y/N ".encode('utf-8'))

            if answer.lower() != 'y':
                print "Canceled sending"
                sys.exit(0)

        if emails:
            if options['debug']:
                self._print_debug(emails)
            else:
                connection = SMTPConnection()
                connection.send_messages(emails)
Ejemplo n.º 8
0
def send_invites():
    count = 0
    try:
        count = sys.argv[1]
    except:
        pass

    invites = Email_Invite.objects.filter(invited=False).order_by('created_date')[:count]
    
    messages = [ ]
    subject = 'Welcome to the Portrit preview!'
    html_content =  '<p>We are happy to announce the launch of the Portrit preview</p>' \
                    '<a href="http://portrit.com/">' \
                        '<img src="http://portrit.com/site_media/img/invite/invite.jpg"/>' \
                    '</a>' \
                    '<p>Please go to <a href="http://portrit.com">portrit.com</a> and login with the email address this message was sent to.</p>' \
                    '<p>With great power comes great responsibilty. With this in mind, we ask that you help us with any feedback you may have.<br>You can email us at <a href="mailto:[email protected]">[email protected]</a> or use the built in feedback control at the top of Portrit.</p>' \
                    '<br><br>' \
                    '<p style="color: #aeaeae; text-align: center; font-size: 12px;">You are receiving this email because you asked to receive an invite to portrit.com<br>' \
                    'Note: This email address is for distribution purposes only. Please do not reply to this email because your message will not be received.</p>'
    from_email = '*****@*****.**'
    from django.core.mail import SMTPConnection
    from django.core import mail
    connection = SMTPConnection()
    # Manually open the connection
    connection.open()
                              
    for invite in invites:
        email = mail.EmailMessage(subject, html_content, from_email,
                                    [invite.email], connection=connection)
        email.content_subtype = "html"
        messages.append(email)
        invite.invited = True
        invite.save()
    
    connection.send_messages(messages)
    connection.close()
Ejemplo n.º 9
0
def send_mail(subject, message_txt, message_html, sender, recipients):
    """Similar to django's send_mass_mail, but use EmailMultiAlternatives
    for email messages.

    Also, avoid creating a list with all the messages, use an iterator instead.
    """
    connection = SMTPConnection(fail_silently=False)

    def messages_iterator():
        for recipient in recipients:
            email = EmailMultiAlternatives(subject, message_txt, sender, recipient)
            email.attach_alternative(message_html, "text/html")
            yield email

    return connection.send_messages(messages_iterator())
Ejemplo n.º 10
0
    def handle(self, *args, **options):
        if len(args) != 0:
            raise CommandError(_("Command doesn't accept any arguments"))

        by_domain = options.get('by_domain')
        domain_name = options.get('domain_name')
        copy_admin = options.get('copy_admin')
        period = options.get('period')
        include_daily = options.get('include_daily')
        enddate = None

        period_re = re.compile(r"(?P<num>(\d+))\s+(?P<period>(day|week|month))(?:s)?")
        if period:
            match = period_re.match(period)
            if not match:
                raise CommandError(_("The period you specified is invalid"))
            num = match.group('num')
            ptype = match.group('period')
            if not ptype.endswith('s'):
                ptype = ptype + 's'
            delta = datetime.timedelta(**{ptype: int(num)})
            enddate = datetime.date.today() - delta

        from django.db.models import Count, Sum, Q
        from django.template.defaultfilters import filesizeformat
        from django.core.mail import EmailMessage, SMTPConnection
        from django.contrib.auth.models import User
        from django.conf import settings
        from django.template.loader import render_to_string
        from baruwa.accounts.models import UserProfile, UserAddresses
        from baruwa.messages.models import Message
        from baruwa.messages.templatetags.messages_extras import tds_trunc
        from baruwa.messages.models import MessageTotals
        from baruwa.utils.graphs import PieChart, PIE_CHART_COLORS, BarChart
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Table, \
        TableStyle, Paragraph, Image, PageBreak

        try:
            from django.forms.fields import email_re
        except ImportError:
            from django.core.validators import email_re

        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO

        table_style = TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Helvetica'),
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('GRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('ALIGN', (4, 1), (-1, -1), 'CENTER'),
            ('ALIGN', (0, 0), (0, -1), 'CENTER'),
            ('VALIGN', (4, 1), (-1, -1), 'MIDDLE'),
            ('SPAN', (4, 1), (-1, -1)),
        ])

        styles = getSampleStyleSheet()

        reports = [
            [
                'from_address', {'from_address__exact': ""}, 'num_count', 
                'Top senders by quantity'],
            [
                'from_address', {'from_address__exact': ""}, 'total_size', 
                'Top senders by volume'],
            [   
                'from_domain', {'from_domain__exact': ""}, 'num_count', 
                'Top sender domains by quantity'],
            [   
                'from_domain', {'from_domain__exact': ""}, 'total_size', 
                'Top sender domains by volume'],
            [   
                'to_address', {'to_address__exact': ""}, 'num_count', 
                'Top recipients by quantity'],
            [
                'to_address', {'to_address__exact': ""}, 'total_size', 
                'Top recipients by volume'],
            [
                'to_domain', {'to_domain__exact': "", 
                'to_domain__isnull': False}, 'num_count', 
                'Top recipient domains by quantity'],
            [
                'to_domain', {'to_domain__exact': "", 
                'to_domain__isnull': False}, 'total_size', 
                'Top recipient domains by volume'],
        ]

        emails = []
        admin_addrs = []
        if copy_admin:
            mails = User.objects.values('email').filter(is_superuser=True)
            admin_addrs = [mail['email'] for mail in mails]

        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 
            'postmaster@localhost')
        url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL', '')
        logo_dir = getattr(settings, 'MEDIA_ROOT', '')
        img = Image(logo_dir + '/imgs/css/logo.jpg')

        def build_chart(data, column, order, title):
            "build chart"
            headings = [('', _('Address'), _('Count'), _('Volume'), '')]
            rows = [[draw_square(PIE_CHART_COLORS[index]), 
            tds_trunc(row[column], 45), row['num_count'], 
            filesizeformat(row['total_size']), ''] 
            for index, row in enumerate(data)]

            if len(rows) != 10:
                missing = 10 - len(rows)
                add_rows = [
                    ('', '', '', '', '') for ind in range(missing)
                    ]
                rows.extend(add_rows)

            headings.extend(rows)
            dat = [row[order] for row in data]
            total = sum(dat)
            labels = [
                    ("%.1f%%" % ((1.0 * row[order] / total) * 100)) 
                    for row in data
                ]

            pie = PieChart()
            pie.chart.labels = labels
            pie.chart.data = dat
            headings[1][4] = pie

            table_with_style = Table(headings, [0.2 * inch, 
                2.8 * inch, 0.5 * inch, 0.7 * inch, 3.2 * inch])
            table_with_style.setStyle(table_style)

            paragraph = Paragraph(title, styles['Heading1'])

            return [paragraph, table_with_style]

        def build_parts(account, enddate, isdom=None):
            "build parts"
            parts = []
            sentry = 0
            for report in reports:
                column = report[0]
                exclude_kwargs = report[1]
                order_by = "-%s" % report[2]
                order = report[2]
                title = report[3]

                if isdom:
                    #dom
                    data = Message.objects.values(column).\
                    filter(Q(from_domain=account.address) | \
                    Q(to_domain=account.address)).\
                    exclude(**exclude_kwargs).annotate(
                        num_count=Count(column), total_size=Sum('size')
                    ).order_by(order_by)
                    if enddate:
                        data.filter(date__gt=enddate)
                    data = data[:10]
                else:
                    #all users
                    data = Message.report.all(user, enddate).values(column).\
                    exclude(**exclude_kwargs).annotate(
                        num_count=Count(column), total_size=Sum('size')
                    ).order_by(order_by)
                    data = data[:10]

                if data:
                    sentry += 1
                    pgraphs = build_chart(data, column, order, title)
                    parts.extend(pgraphs)
                    parts.append(Spacer(1, 70))
                    if (sentry % 2) == 0:
                        parts.append(PageBreak())
            parts.append(Paragraph(_('Message Totals'), styles['Heading1']))
            if isdom:
                #doms
                msg_totals = MessageTotals.objects.doms(account.address, enddate)
            else:
                #norm
                filters = []
                addrs = [
                    addr.address for addr in UserAddresses.objects.filter(
                        user=account
                    ).exclude(enabled__exact=0)]
                if enddate:
                    efilter = {
                                'filter': 3, 
                                'field': 'date', 
                                'value': str(enddate)
                               }
                    filters.append(efilter)
                msg_totals = MessageTotals.objects.all(
                    account, filters, addrs, profile.account_type)

            mail_total = []
            spam_total = []
            virus_total = []
            dates = []
            if include_daily:
                rows = [(
                Table([[draw_square(colors.white),
                Paragraph('Date', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch,]),
                Table([[draw_square(colors.green),
                Paragraph('Mail totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch,]),
                Table([[draw_square(colors.pink),
                Paragraph('Spam totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch,]),
                Table([[draw_square(colors.red),
                Paragraph('Virus totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch,]),
                )]
            for ind, msgt in enumerate(msg_totals):
                if ind % 10:
                    dates.append('')
                else:
                    dates.append(str(msgt.date))

                mail_total.append(int(msgt.mail_total))
                spam_total.append(int(msgt.spam_total))
                virus_total.append(int(msgt.virus_total))
                if include_daily:
                    rows.append((str(msgt.date), msgt.mail_total,
                    msgt.spam_total, msgt.virus_total))

            graph = BarChart()
            graph.chart.data = [
                    tuple(mail_total), tuple(spam_total), 
                    tuple(virus_total)
                ]
            graph.chart.categoryAxis.categoryNames = dates
            graph_table = Table([[graph]], [7.4 * inch])
            parts.append(graph_table)
            if include_daily:
                rows.append(('Totals', sum(mail_total), sum(spam_total),
                sum(virus_total)))
                parts.append(Spacer(1, 20))
                graph_table = Table(rows, [1.85 * inch, 1.85 * inch,
                1.85 * inch, 1.85 * inch,])
                graph_table.setStyle(TableStyle([
                ('FONTSIZE', (0, 0), (-1, -1), 8),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('GRID', (0, 0), (-1, -1), 0.15, colors.black),
                ('FONT', (0, -1), (-1, -1), 'Helvetica-Bold'),
                #('BACKGROUND', (0, -1), (-1, -1), colors.green),
                ]))
                parts.append(graph_table)
            return parts

        def build_pdf(charts):
            "Build a PDF"
            pdf = StringIO()
            doc = SimpleDocTemplate(pdf, topMargin=50, bottomMargin=18)
            logo = [(img, _('Baruwa mail report'))]
            logo_table = Table(logo, [2.0 * inch, 5.4 * inch])
            logo_table.setStyle(TableStyle([
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
            ('ALIGN', (1, 0), (-1, 0), 'RIGHT'),
            ('FONTSIZE', (1, 0), (-1, 0), 10),
            ('LINEBELOW', (0, 0), (-1, -1), 0.15, colors.black),
            ]))
            parts = [logo_table]
            parts.append(Spacer(1, 20))
            parts.extend(charts)
            try:
                doc.build(parts)
            except IndexError:
                pass
            return pdf

        def gen_email(pdf, user, owner):
            "generate and return email"
            text_content = render_to_string('reports/pdf_report.txt',
                {'user': user, 'url': url})
            subject = _('Baruwa usage report for: %(user)s') % {
                        'user': owner}
            if email_re.match(user.username):
                toaddr = user.username
            if email_re.match(user.email):
                toaddr = user.email

            if admin_addrs:
                msg = EmailMessage(subject, text_content, from_email, [toaddr], admin_addrs)
            else:
                msg = EmailMessage(subject, text_content, from_email, [toaddr])
            msg.attach('baruwa.pdf', pdf.getvalue(), "application/pdf")
            print _("* Queue %(user)s's report to: %(addr)s") % {
                'user': owner, 'addr': toaddr}
            pdf.close()
            return msg

        print _("=================== Processing reports ======================")
        if by_domain:
            #do domain query
            #print "camacamlilone"
            domains = UserAddresses.objects.filter(Q(enabled=1), Q(address_type=1))
            if domain_name != 'all':
                domains = domains.filter(address=domain_name)
                if not domains:
                    print _("========== domain name %(dom)s does not exist ==========") % {
                    'dom': domain_name
                    }
            for domain in domains:
                if email_re.match(domain.user.email) or email_re.match(domain.user.username):
                    parts = build_parts(domain, enddate, True)
                    if parts:
                        pdf = build_pdf(parts)
                        email = gen_email(pdf, domain.user, domain.address)
                        emails.append(email)
        else:
            #do normal query
            profiles = UserProfile.objects.filter(send_report=1)
            for profile in profiles:
                try:
                    user = profile.user
                    if email_re.match(user.email) or email_re.match(user.username):
                        parts = build_parts(user, enddate, False)
                        if parts:
                            pdf = build_pdf(parts)
                            email = gen_email(pdf, user, user.username)
                            emails.append(email)
                except User.DoesNotExist:
                    pass

        if emails:
            try:
                conn = SMTPConnection()
                conn.send_messages(emails)
                print _("====== sending %(num)s messages =======") % {
                        'num': str(len(emails))}
            except Exception, exception:
                print _("Sending failed ERROR: %(error)s") % {'error': str(exception)}
Ejemplo n.º 11
0
def create_campaign_message(request):
    if request.method == 'POST':
        if not 'project' in request.session:
            project = Project.objects.get(id=int(request.POST['pid']))
            funding_detail = project.projectfundingdetail_set.latest(
                'end_date')
            funding_detail_value = long(funding_detail.budget)
            to_session = {'project': project, 'funding_detail': funding_detail}
            request.session.update(to_session)
        else:
            project = request.session['project']
            funding_detail = request.session['funding_detail']
            funding_detail_value = long(funding_detail.budget)
        ''' 
        if request.POST.has_key('confirmed'):
            form = DonationAmountForm(data=request.POST,request=request,total_amount=request.session['donating_amount'])
            if not form.is_valid():
                return render_to_response('donorportal/create_campaign2.html',{'form':form},RequestContext(request))

            assert form.cleaned_data['amount'] == request.session['donating_amount']
            request.session['donated_amount'] = form.cleaned_data['amount']
        '''

        #Message form post request
        form = MessageForm()
        if request.POST.get('form-type') == 'message-form':
            form = MessageForm(request.POST)

        if form.is_valid():
            values = {}
            values.update(request.session)
            values.update(form.cleaned_data)
            camp_values = {
                'user': request.user,
                'amount': int(values['campaign_amount']),
                #This is 0, but the added donation, auto adds that value to donated.
                'amount_collected': 0,
                'description': values['description'],
                'project': values['project'],
                'end_date': values['campaign_end_date']
            }
            del request.session['project']
            camp = Campaign.objects.create(**camp_values)
            #donation = Donation()
            #donation.campaign = camp
            #donation.user = request.user
            #donation.amount = long(values['donated_amount'])
            #donation.save()

            extra_context = {
                'site': Site.objects.get_current(),
                'campaign': camp
            }
            extra_context.update(values)
            mail_context = RequestContext(request, extra_context)
            mail_message = loader.render_to_string(
                'email_templates/campaign_mail.txt', mail_context)
            subject = '%s is raising funds for %s project on Vibha' % (
                request.user.get_full_name(), values['project'].name)
            from_email = settings.DEFAULT_FROM_EMAIL

            # Split into several messages so recipients dont see the other recipients
            msg = []
            for recipient in form.cleaned_data['to_email_field']:
                m = EmailMessage(subject, mail_message, from_email,
                                 [recipient])
                m.content_subtype = "html"
                msg.append(m)

            connection = SMTPConnection()
            connection.send_messages(msg)

            return HttpResponseRedirect('../campaign/%s/' % (camp.id))
        payload = locals()
        return render_to_response('donorportal/create_campaign3.html', payload,
                                  RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('list_projects'))
Ejemplo n.º 12
0
def send_mass_mail_em(email_message_list, fail_silently=False, auth_user=None,
                   auth_password=None):
    connection = SMTPConnection(username=auth_user, password=auth_password,
                                fail_silently=fail_silently)
    return connection.send_messages(email_message_list)
Ejemplo n.º 13
0
	       if allowed == 1:
                   messages.append(msg)
               cursor.execute("update comm_queue_app_commd set end_at=NOW(),status=2 where id="+str(c[0]))        
          else:
               cursor.execute("update comm_queue_app_commd set end_at=NOW(),status=3 where id="+str(c[0]))
     if len(messages)!=0:
	  #connection = SMTPConnection(host='smtp.gmail.com',port=587,username=username,password=password,use_tls=True)
          if mailer_count==0:
              connection = SMTPConnection(host='mail.messagingengine.com',port=587,username='******',password='******',use_tls=True)
          elif mailer_count==1:
              connection = SMTPConnection(host='mail.messagingengine.com',port=587,username='******',password='******',use_tls=True)
          elif mailer_count==2:
              connection = SMTPConnection(host='mail.messagingengine.com',port=587,username='******',password='******',use_tls=True)
          elif mailer_count==3:
              connection = SMTPConnection(host='mail.messagingengine.com',port=587,username='******',password='******',use_tls=True)
          elif mailer_count==4:
              connection = SMTPConnection(host='mail.messagingengine.com',port=587,username='******',password='******',use_tls=True)
          # connection = SMTPConnection()
          logit(username)
          try:
              connection.send_messages(messages)
              curr_msg=curr_msg+len(messages)
              mailer_count=mailer_count + 1
              conn.commit()
          except smtplib.SMTPDataError:
              mailer_count=mailer_count + 1
              conn.rollback()
     if mailer_count>=5:
         mailer_count=mailer_min    
     time.sleep(60)
Ejemplo n.º 14
0
 def handle_noargs(self, **options):
     from django.db.models import Count, Sum
     from django.template.defaultfilters import filesizeformat
     from django.core.mail import EmailMessage, SMTPConnection
     from django.conf import settings
     from django.template.loader import render_to_string
     from baruwa.accounts.models import UserProfile, UserAddresses
     from baruwa.messages.models import Message
     from baruwa.messages.templatetags.messages_extras import tds_trunc
     from baruwa.messages.models import MessageTotals
     from baruwa.utils.graphs import PieChart, PIE_CHART_COLORS, BarChart
     from reportlab.lib import colors
     from reportlab.lib.styles import getSampleStyleSheet
     from reportlab.lib.units import inch
     from reportlab.platypus import SimpleDocTemplate, Spacer, Table, \
     TableStyle, Paragraph, Image, PageBreak
     
     try:
         from django.forms.fields import email_re
     except ImportError:
         from django.core.validators import email_re
     
     try:
         from cStringIO import StringIO
     except:
         from StringIO import StringIO
     
     table_style = TableStyle([
         ('FONT', (0, 0), (-1, -1), 'Helvetica'),
         ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
         ('FONTSIZE', (0, 0), (-1, -1), 8),
         ('GRID', (0, 0), (-1, -1), 0.15, colors.black),
         ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
         ('ALIGN', (4, 1), (-1, -1), 'CENTER'),
         ('ALIGN', (0, 0), (0, -1), 'CENTER'),
         ('VALIGN', (4, 1), (-1, -1), 'MIDDLE'),
         ('SPAN', (4, 1), (-1, -1)),
     ])
     
     styles = getSampleStyleSheet()
     
     reports = [
         [
             'from_address', {'from_address__exact':""}, 'num_count', 
             'Top senders by quantity'],
         [
             'from_address', {'from_address__exact':""}, 'size', 
             'Top senders by volume'],
         [   
             'from_domain', {'from_domain__exact':""}, 'num_count', 
             'Top sender domains by quantity'],
         [   
             'from_domain', {'from_domain__exact':""}, 'size', 
             'Top sender domains by volume'],
         [   
             'to_address', {'to_address__exact':""}, 'num_count', 
             'Top recipients by quantity'],
         [
             'to_address', {'to_address__exact':""}, 'size', 
             'Top recipients by volume'],
         [
             'to_domain', {'to_domain__exact':"", 
             'to_domain__isnull':False}, 'num_count', 
             'Top recipient domains by quantity'],
         [
             'to_domain', {'to_domain__exact':"", 
             'to_domain__isnull':False}, 'size', 
             'Top recipient domains by volume'],
     ]
     
     emails = []
     
     from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 
         'postmaster@localhost')
     url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL','')
     logo_dir = getattr(settings, 'MEDIA_ROOT', '')
     img = Image(logo_dir + '/imgs/css/logo.jpg')
     profiles = UserProfile.objects.filter(send_report=1)
     
     print "=================== Processing reports ======================"
    
     for profile in profiles:
         user = profile.user
         if email_re.match(user.email) or email_re.match(user.username):
             
             pdf = StringIO()
             
             doc = SimpleDocTemplate(pdf, topMargin=50, bottomMargin=18)
             logo = [(img, 'Baruwa mail report')]
             logo_table = Table(logo, [2.0 * inch, 5.4 * inch])
             logo_table.setStyle(TableStyle([
             ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
             ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
             ('ALIGN', (1, 0), (-1, 0), 'RIGHT'),
             ('FONTSIZE', (1, 0), (-1, 0), 10),
             ('LINEBELOW', (0, 0),(-1, -1), 0.15, colors.black),
             ]))
             parts = [logo_table]
             parts.append(Spacer(1, 20))
             sentry = 0
             for report in reports:
                 column = report[0]
                 exclude_kwargs = report[1]
                 order_by = "-%s" % report[2]
                 order = report[2]
                 title = report[3]
                 
                 data = Message.report.all(user).values(column).\
                 exclude(**exclude_kwargs).annotate(
                     num_count=Count(column), size=Sum('size')
                 ).order_by(order_by)[:10]
             
                 if data:
                     sentry += 1
                     headings = [('', 'Address', 'Count', 'Volume', '')]
                     rows = [[draw_square(PIE_CHART_COLORS[index]), 
                     tds_trunc(row[column], 45), row['num_count'], 
                     filesizeformat(row['size']),''] 
                     for index,row in enumerate(data)]
                 
                     if len(rows) != 10:
                         missing = 10 - len(rows)
                         add_rows = [
                             ('', '', '', '', '') for ind in range(missing)
                             ]
                         rows.extend(add_rows)
                     
                     headings.extend(rows)
                     dat = [row[order] for row in data]
                     total = sum(dat)
                     labels = [
                             ("%.1f%%" % ((1.0 * row[order] / total) * 100)) 
                             for row in data
                         ]
                     
                     pie = PieChart()
                     pie.chart.labels = labels
                     pie.chart.data = dat
                     headings[1][4] = pie
                     
                     table_with_style = Table(headings, [0.2 * inch, 
                         2.8 * inch, 0.5 * inch, 0.7 * inch, 3.2 * inch])
                     table_with_style.setStyle(table_style)
                 
                     paragraph = Paragraph(title, styles['Heading1'])
                     
                     parts.append(paragraph)
                     parts.append(table_with_style)
                     parts.append(Spacer(1, 70))
                     if (sentry % 2) == 0:
                         parts.append(PageBreak())
             #
             parts.append(Paragraph('Message Totals', styles['Heading1']))
             addrs = [
                 addr.address for addr in UserAddresses.objects.filter(
                     user=user
                 ).exclude(enabled__exact=0)]
             
             msg_totals = MessageTotals.objects.all(
                 user, [], addrs, profile.account_type)
             mail_total = []
             spam_total = []
             virus_total = []
             dates = []
             for ind, msgt in enumerate(msg_totals):
                 if ind % 10:
                     dates.append('')
                 else:
                     dates.append(str(msgt.date))
                     
                 mail_total.append(int(msgt.mail_total))
                 spam_total.append(int(msgt.spam_total))
                 virus_total.append(int(msgt.virus_total))
                 
             #graph = MessageTotalsGraph()
             graph = BarChart()
             graph.chart.data = [
                     tuple(mail_total), tuple(spam_total), 
                     tuple(virus_total)
                 ]
             graph.chart.categoryAxis.categoryNames = dates
             graph_table = Table([[graph],], [7.4 * inch])
             parts.append(graph_table)
             
             if not sentry:
                 sentry += 1
                 
             if sentry:
                 doc.build(parts)
                 
                 text_content = render_to_string('reports/pdf_report.txt',
                     {'user':user, 'url':url})
                 subject = 'Baruwa usage report for: %s' % user.username
                 if email_re.match(user.username):
                     toaddr = user.username
                 if email_re.match(user.email):
                     toaddr = user.email
                     
                 msg = EmailMessage(subject, text_content, from_email, [toaddr])
                 msg.attach('baruwa.pdf', pdf.getvalue(), "application/pdf")
                 #msg.send()
                 emails.append(msg)
                 print "* Queue "+user.username+"'s report to: "+toaddr
                 pdf.close()
     if emails:
         try:
             conn = SMTPConnection()
             conn.send_messages(emails)
             print "====== sending "+str(len(emails))+" messages ======="
         except Exception, exception:
             print "Sending failed ERROR: %s" % str(exception)