Esempio n. 1
0
    def send(self, template_name, from_email, recipient_list, context, cc=None,
            bcc=None, fail_silently=False, headers=None, template_prefix=None,
            template_suffix=None, template_dir=None, file_extension=None,
            **kwargs):

        msg = EmailMessage(from_email=from_email, to=recipient_list)
        msg.template_name = template_name
        msg.global_merge_vars = context
        msg.fail_silently = fail_silently

        if cc:
            msg.cc = cc
        if bcc:
            msg.bcc = bcc

        msg.use_template_subject = kwargs.get('use_template_subject', True)
        msg.use_template_from = kwargs.get('use_template_from', True)
        msg.async = kwargs.get('async', True)

        try:
            msg.send()
        except Exception as e:
            if not fail_silently:
                raise
        return msg.extra_headers.get('Message-Id', None)
Esempio n. 2
0
File: mailer.py Progetto: DRGC/vron
    def send( subject, body, to, from_email = None, cc = None, bcc = None, attachments = None ):
        """
        Send the email using Django's EmailMessage class

        :param: subject
        :param: body
        :param: to
        :param: from_email
        :param: cc
        :param: bcc
        :param: attachments
        :return: String
        """

        if not settings.IS_PROD:
            return True

        email = EmailMessage()
        email.content_subtype = "html"
        email.subject = subject
        email.body = body
        email.to = [to] if isinstance( to, str ) else to
        if from_email:
            email.from_email = from_email
        if cc:
            email.cc = [cc] if isinstance( cc, str ) else cc
        if bcc:
            email.bcc = [bcc] if isinstance( bcc, str ) else bcc
        if attachments:
            for attachment in attachments:
                email.attach( attachment )

        return email.send()
Esempio n. 3
0
def send_expired_email(membership):
    email = EmailMessage()
    email.subject = "Your Rhizome membership has expired."
    email.to = [membership.user.email]
    email.bcc = [admin[1] for admin in settings.ADMINS] 
    email.body = """
Dear %s,

Did you notice that your Rhizome Membership expired?

You can renew quickly and easily here:

https://rhizome.org/support/donate/

You're missing out on all those great benefits that come with Rhizome Membership. Indispensable Resources where you can find educational programs, syllabi and residencies from around the globe to deepen your knowledge and skills. View hundreds of proposals and cast your vote for Rhizome's annual Commissions program. Flex your curator muscles with your very own Member Exhibition. Interact with artists and artworks in our comprehensive archive by leaving comments, saving artworks to your profile and access to full artwork records with the ArtBase Special Features. And on top of all that, a bonus 10 percent discount on all your purchases at the New Museum Store. 

http://rhizome.org/support/individual/

Seriously, it only takes a minute to click here and renew now! 

https://rhizome.org/support/donate/

Sincerely,

Rhizome

P.S. If you have made a donation within the past year, you are probably receiving this email because you have multiple records in our database.  If this is the case then no further action needs to be taken. Please contact %s if you believe that there has been an error that should be resolved or needs to be investigated.

+ + +

Rhizome.org is a not-for-profit 501(c)(3) organization. For U.S. taxpayers, contributions to Rhizome are tax-deductible, minus the value of any goods or services received, to the extent allowed by law.
""" % (membership.user.get_profile(), settings.SUPPORT_CONTACT[1])

    email.send(fail_silently=False)
Esempio n. 4
0
def send_enrollment_decision(participation, approved, request=None):
    # type: (Participation, bool, http.HttpRequest) -> None

    with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE):
        course = participation.course
        if request:
            course_uri = request.build_absolute_uri(
                reverse("relate-course_page", args=(course.identifier, )))
        else:
            # This will happen when this method is triggered by
            # a model signal which doesn't contain a request object.
            from six.moves.urllib.parse import urljoin
            course_uri = urljoin(getattr(settings, "RELATE_BASE_URL"),
                                 course.get_absolute_url())

        from django.template.loader import render_to_string
        message = render_to_string(
            "course/enrollment-decision-email.txt", {
                "user": participation.user,
                "approved": approved,
                "course": course,
                "course_uri": course_uri
            })

        from django.core.mail import EmailMessage
        msg = EmailMessage(
            string_concat("[%s] ", _("Your enrollment request")) %
            course.identifier, message, course.get_from_email(),
            [participation.user.email])
        msg.bcc = [course.notify_email]
        if not settings.RELATE_EMAIL_SMTP_ALLOW_NONAUTHORIZED_SENDER:
            from relate.utils import get_outbound_mail_connection
            msg.connection = get_outbound_mail_connection("robot")
        msg.send()
Esempio n. 5
0
    def send_email(self):

        email_to = []
        list_option = int(self.cleaned_data['mailing_list'])
        if list_option == 1:
            email_to = UserService.get_inactive_users_emails()
        elif list_option == 2:
            email_to = UserService.get_active_users_emails()
        elif list_option == 3:
            email_to = UserService.get_officer_users_emails()
        elif list_option == 4:
            email_to = UserService.get_sponsor_users_emails()
        elif list_option == 5:
            email_to = UserService.get_madcon_pending_emails()
        elif list_option == 6:
            email_to = UserService.get_madcon_accepted_emails()
        elif list_option == 7:
            email_to = UserService.get_madcon_confirmed_emails()
        else:
            email_to = [EMAIL_WEBMASTER]

        mail = EmailMessage(subject=self.cleaned_data['subject'],
                            body=self.cleaned_data['message'],
                            from_email=DEFAULT_FROM_EMAIL)
        mail.bcc = email_to
        mail.to = [DEFAULT_FROM_EMAIL]
        mail.send()
        pass
Esempio n. 6
0
    def handle(self, *args, **options):
        conf = GlobalConf.objects.get()
        dow_tancament = dows[ conf.dow_tancament ]
        hora_tancament = conf.hora_tancament.strftime('%H:%m')
        text = """
Hola %s,

aquest email és un recordatori perquè facis la comanda de la setmana que ve. No et despistis!
La propera comanda es tanca %s a les %s h,

Per fer la comanda vés a www.almaixera.cat

Comissió d'informàtica responsable de l'Almàixera :)
""" % ("Almaixerenc@", dow_tancament, hora_tancament )
        assumpte = "Recordatori per fer comanda"
        email = EmailMessage( assumpte, text )
        # Socis
        dest = []
        for e in Soci.objects.all():
            if e.user.email:
                dest.append( e.user.email )
        # Envia email
        email.bcc = dest #['*****@*****.**']
        #print(email.message() # debug)
        email.send()
Esempio n. 7
0
def send_enrollment_decision(participation, approved, request=None):
        with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE):
            course = participation.course
            if request:
                course_uri = request.build_absolute_uri(
                        reverse("relate-course_page",
                            args=(course.identifier,)))
            else:
                # This will happen when this method is triggered by
                # a model signal which doesn't contain a request object.
                from urlparse import urljoin
                course_uri = urljoin(getattr(settings, "RELATE_BASE_URL"),
                                     course.get_absolute_url())

            from django.template.loader import render_to_string
            message = render_to_string("course/enrollment-decision-email.txt", {
                "user": participation.user,
                "approved": approved,
                "course": course,
                "course_uri": course_uri
                })

            from django.core.mail import EmailMessage
            msg = EmailMessage(
                    string_concat("[%s] ", _("Your enrollment request"))
                    % course.identifier,
                    message,
                    course.from_email,
                    [participation.user.email])
            msg.bcc = [course.notify_email]
            msg.send()
Esempio n. 8
0
    def send_email(self):

        email_to = []
        list_option = int(self.cleaned_data['mailing_list'])
        if list_option == 1:
            email_to = UserService.get_disabled_users_emails()
        elif list_option == 2:
            email_to = UserService.get_open_rushie_users_emails()
        elif list_option == 3:
            email_to = UserService.get_closed_rushie_users_emails()
        elif list_option == 4:
            email_to = UserService.get_pledge_users_emails()
        elif list_option == 5:
            email_to = UserService.get_active_users_emails()
        elif list_option == 6:
            email_to = UserService.get_officer_users_emails()
        elif list_option == 7:
            email_to = UserService.get_board_users_emails()
        elif list_option == 8:
            email_to = UserService.get_inactive_users_emails()
        elif list_option == 9:
            email_to = UserService.get_alumni_users_emails()
        else:
            email_to = [EMAIL_WEBMASTER]

        mail = EmailMessage(subject=self.cleaned_data['subject'],
                            body=self.cleaned_data['message'],
                            from_email=DEFAULT_FROM_EMAIL)
        mail.bcc = email_to
        mail.to = [DEFAULT_FROM_EMAIL]
        mail.send()
        pass
Esempio n. 9
0
def send_priority_email(log, priority):
    user = priority.user
    first_name = capfirst(user.first_name)
    username = user.username
    expire = priority.expire.strftime('%Y-%m-%d')
    admin_name, admin_email = settings.ADMINS[0]
    mail = EmailMessage()
    mail.subject = "Browsershots priority processing activated"
    mail.body = """
Hi %(first_name)s,

Thank you for supporting the Browsershots project.

Priority processing has been activated for %(username)s
until %(expire)s. Please let me know how it works for you,
and if you have ideas for improvement.

Cheers,
%(admin_name)s
%(admin_email)s
""".strip() % locals()
    mail.to = ['"%s %s" <%s>' % (user.first_name, user.last_name, user.email)]
    mail.bcc = [admin_email]
    mail.from_email = '"%s" <%s>' % (admin_name, admin_email)
    # mail.headers = {'Reply-To': admin_email}
    mail.send()
def notify_staff(backup):
    # now = datetime.now()
    # start = now - timedelta(days=7)
    # for backup in Backup.objects.order_by('-id').filter(status=FAILED):
    sender = 'ikwen DBBACKUP <*****@*****.**>'
    subject = _("New failed backup")
    recipient_list = [get_service_instance().member.email]
    staff_list = [
        staff.email for staff in Member.objects.filter(is_staff=True)
    ]
    job_config = backup.job_config
    extra_context = {
        'hostname': job_config.hostname,
        'db_name': job_config.db_name,
        'db_type': job_config.db_type,
        'status': backup.status,
        'start_time': backup.created_on,
        'file_size_hr': backup.file_size_hr,
        'error_messages': backup.error_messages
    }
    activate('en')
    try:
        html_content = get_mail_content(
            subject,
            template_name='dbbackup/mails/failed_backup_notification.html',
            extra_context=extra_context)
    except:
        logger.error("Could not generate HTML content from template",
                     exc_info=True)
        return
    msg = EmailMessage(subject, html_content, sender, recipient_list)
    msg.content_subtype = "html"
    msg.bcc = staff_list
    msg.send()
Esempio n. 11
0
    def send_receipt(self):
        receipt = EmailMessage()
        receipt.to = ["%s" % self.user.email]
        receipt.bcc = [admin[1] for admin in settings.ADMINS]
        receipt.subject = "Rhizome.org Jobs Board Posting Payment Receipt"
        receipt.body = """
Dear %s,

This confirms your payment to Rhizome in the amount of $%s for a Job Posting.

Job Title: %s
Job Posting URL: http://rhizome.org%s
Payment Amount: $%s
Payment Date: %s

Thank your for using Rhizome.org.

Sincerely,

The Rhizome Staff

""" % (
            self.user.get_profile(),
            self.amount,
            self.job.title,
            self.job.get_absolute_url(),
            self.formatted_amount(),
            self.created.strftime("%m/%d/%Y"),
        )
        receipt.send(fail_silently=False)
Esempio n. 12
0
def send_priority_email(log, priority):
    user = priority.user
    first_name = capfirst(user.first_name)
    username = user.username
    expire = priority.expire.strftime('%Y-%m-%d')
    admin_name, admin_email = settings.ADMINS[0]
    mail = EmailMessage()
    mail.subject = "Browsershots priority processing activated"
    mail.body = """
Hi %(first_name)s,

Thank you for supporting the Browsershots project.

Priority processing has been activated for %(username)s
until %(expire)s. Please let me know how it works for you,
and if you have ideas for improvement.

Cheers,
%(admin_name)s
%(admin_email)s
""".strip() % locals()
    mail.to = ['"%s %s" <%s>' % (user.first_name, user.last_name, user.email)]
    mail.bcc = [admin_email]
    mail.from_email = '"%s" <%s>' % (admin_name, admin_email)
    # mail.headers = {'Reply-To': admin_email}
    mail.send()
Esempio n. 13
0
def ipn_failed(ipn, ppt):
    trip = ppt.trip
    user = ppt.user
    participants = ppt.participant_set.all()

    email = EmailMessage(subject = 'Zena Ski Group: problemi con il pagamento',
                         to = [user.email])
    body = (u"C'è stato un problema con la seguente transazione PayPal:\n"
            u"Gita: {destination}, {date}\n"
            u"Partecipanti:\n"
            u"{participant_names}\n"
            u"\n"
            u"Riferimento IPN interno: {ipn}\n"
            u"Si prega di contattare lo staff per risolvere il problema")


    participant_names = ['  - %s' % p.name for p in participants]
    email.body =  body.format(
        destination = trip.destination,
        date = trip.date.strftime("%d/%m/%Y"),
        participant_names = '\n'.join(participant_names),
        ipn=ipn.id
    )
    email.bcc = [settings.ADMIN_EMAIL]
    email.send(fail_silently=True)
Esempio n. 14
0
def send_notification(
        sender,
        subject,
        mail_content,
        template_name,
        recipient_list,
        cc_list,
        bcc_list,
        reply_to=None):
    """
    send notification
    :param sender:
    :param subject:
    :param mail_content:
    :param template_name:
    :param recipient_list:
    :param cc_list:
    :param bcc_list:
    :param reply_to:
    """
    template = get_template(template_name)
    ctx = Context({'request': mail_content})
    message = template.render(ctx)
    email = EmailMessage(subject=subject, body=message,
                         from_email=sender, to=recipient_list)
    if cc_list:
        email.cc = cc_list
    if bcc_list:
        email.bcc = bcc_list
    if reply_to:
        email.reply_to = reply_to
    email.send()
Esempio n. 15
0
File: api.py Progetto: GunioRobot/q
def email_kindle(request, book_id):
    """
    Email the mobi format of the book to the user's kindle email address
    """
    from django.core.mail import EmailMessage

    try:
        book = Book.objects.get(id=book_id)
    except:
        return HttpResponse('Fail')

    email = EmailMessage()
    email.subject = book.title
    email.body = book.description
    email.to = (request.user.get_profile().kindle_email,)
    email.bcc = ("",) # This is a hack. I don't know why you have to set this to "" but you do otherwise it gives errors

    headers = {'User-Agent': settings.DEFAULT_HTTP_HEADERS}
    url = Format.objects.filter(ebook=book, format='mobi')[0].ebook_file.url
    filename = os.path.basename(url)
    data = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()

    email.attach(filename, data, 'application/x-mobipocket-ebook')
    email.send()

    return HttpResponse('Okay')
Esempio n. 16
0
    def send_receipt(self):
        receipt = EmailMessage()
        receipt.to = ["%s" % self.user.email]
        receipt.bcc = [admin[1] for admin in settings.ADMINS]
        receipt.subject = "Rhizome.org Jobs Board Posting Payment Receipt"
        receipt.body = """
Dear %s,

This confirms your payment to Rhizome in the amount of $%s for a Job Posting.

Job Title: %s
Job Posting URL: http://rhizome.org%s
Payment Amount: $%s
Payment Date: %s

Thank your for using Rhizome.org.

Sincerely,

The Rhizome Staff

""" % (self.user.get_profile(), self.amount, self.job.title,
        self.job.get_absolute_url(), self.formatted_amount(),
        self.created.strftime("%m/%d/%Y"))
        receipt.send(fail_silently=False)
Esempio n. 17
0
    def notify_via_e_mail(self, sender, recipient_list, template, cc_list=[],
                          bcc_list=[], reply_to=None):
        """
        Send an email to the requester notifying them that their
        allocation has been processed.
        """
        if not sender and recipient_list:
            # TODO (shauno): log this problem
            raise Exception

        plaintext = get_template(template)
        ctx = Context({"request": self})
        text = plaintext.render(ctx)
        subject, body = text.split('')
        email = EmailMessage(
            subject.strip(),
            body,
            sender,
            recipient_list,
            cc=cc_list
        )

        if bcc_list:
            email.bcc = bcc_list

        if reply_to:
            email.headers = {'Reply-To': reply_to}

        email.send()
Esempio n. 18
0
def send_expired_email(membership):
    email = EmailMessage()
    email.subject = "Your Rhizome membership has expired."
    email.to = [membership.user.email]
    email.bcc = [admin[1] for admin in settings.ADMINS]
    email.body = """
Dear %s,

Did you notice that your Rhizome Membership expired?

You can renew quickly and easily here:

https://rhizome.org/support/donate/

You're missing out on all those great benefits that come with Rhizome Membership. Indispensable Resources where you can find educational programs, syllabi and residencies from around the globe to deepen your knowledge and skills. View hundreds of proposals and cast your vote for Rhizome's annual Commissions program. Flex your curator muscles with your very own Member Exhibition. Interact with artists and artworks in our comprehensive archive by leaving comments, saving artworks to your profile and access to full artwork records with the ArtBase Special Features. And on top of all that, a bonus 10 percent discount on all your purchases at the New Museum Store. 

http://rhizome.org/support/individual/

Seriously, it only takes a minute to click here and renew now! 

https://rhizome.org/support/donate/

Sincerely,

Rhizome

P.S. If you have made a donation within the past year, you are probably receiving this email because you have multiple records in our database.  If this is the case then no further action needs to be taken. Please contact %s if you believe that there has been an error that should be resolved or needs to be investigated.

+ + +

Rhizome.org is a not-for-profit 501(c)(3) organization. For U.S. taxpayers, contributions to Rhizome are tax-deductible, minus the value of any goods or services received, to the extent allowed by law.
""" % (membership.user.get_profile(), settings.SUPPORT_CONTACT[1])

    email.send(fail_silently=False)
Esempio n. 19
0
    def send_reminder_to_prospect(self, prospect):
        admin = prospect.invite_admin
        reminder = EmailMessage()
        reminder.subject = "Reminder: You've been invited to join Rhizome!"
        reminder.to = [prospect.email]
        reminder.bcc = [admin[1] for admin in settings.ADMINS]
        invite_url = "http://rhizome.org/welcome/orgsub/?email=%s&registration_code=%s" % (prospect.email, prospect.registration_code)

        reminder.body = """
Hi there, 

Just a reminder...

%s (%s) has just offered you a membership as part of the %s membership for Rhizome.org. 

Rhizome.org is a global arts platform, and your group membership allows you access to Rhizome *without* having to give a donation. (All Rhizome members are required to support the organization with an annual gift; group memberships are purchased by institutions such as schools, media centers, or libraries). 

Clicking on the link below will validate your account and give you access to our publications, discussion groups, ArtBase archive, community directory, and other features:

%s 

Thanks and welcome to Rhizome, 

The Rhizome Crew""" % (admin, admin.email, prospect.org_sub, invite_url )         
        reminder.send(fail_silently=False)
Esempio n. 20
0
 def run(self):
     try:
         log.info(self.toString())
         msg = EmailMessage(self.subject.strip(), self.body.strip(), self._from, self.to.split(','),self.bcc.split(','), None)
         if self.isAttachment:
             img_data = open(self.attachment,'rb').read()
             msg.attach('product.jpg',img_data,'image/jpg')
         if self.isHtml:
             text_content = strip_tags(self.body.strip())
             msg = EmailMultiAlternatives(self.subject.strip(), text_content, self._from,self.to.split(','), self.bcc.split(','))
             msg.bcc = self.bcc.split(',')
             msg.attach_alternative(self.body.strip(), "text/html")
         msg.send()
         if self.email_log_id:
             try:
                 email_log = LEmail.objects.get(id = self.email_log_id)
                 email_log.status = 'delivered'
                 email_log.save()
             except:
                 log.warn(
                     'Skipping saving email log to %s' % self.email_log_id)
     except Exception, e:
         if self.email_log_id:
             try:
                 email_log = LEmail.objects.get(id = self.email_log_id)
                 email_log.status = 'delivery_failed'
                 email_log.save()
             except:
                 log.warn(
                     'Skipping saving email log to %s' % self.email_log_id)
         log.exception('Error sending email %s' % self.toString())
Esempio n. 21
0
def send_notification(sender,
                      subject,
                      mail_content,
                      template_name,
                      recipient_list,
                      cc_list,
                      bcc_list,
                      reply_to=None):
    """
    send notification
    :param sender:
    :param subject:
    :param mail_content:
    :param template_name:
    :param recipient_list:
    :param cc_list:
    :param bcc_list:
    :param reply_to:
    """
    template = get_template(template_name)
    ctx = Context({'request': mail_content})
    message = template.render(ctx)
    email = EmailMessage(subject=subject,
                         body=message,
                         from_email=sender,
                         to=recipient_list)
    if cc_list:
        email.cc = cc_list
    if bcc_list:
        email.bcc = bcc_list
    if reply_to:
        email.headers = {'Reply-To': reply_to}
    email.send()
Esempio n. 22
0
def registration_confirmed(user, trip, participants):
    email = EmailMessage(subject = 'Zena Ski Group: conferma iscrizione',
                         to = [user.email])

    if trip.with_reservation:
        body = (u"L'iscrizione delle seguenti persone per la gita a "
                u"{destination} del "
                u"{date} è stata effettuata CON RISERVA.\n"
                u"In caso di conferma, verrai informato via email, oppure "
                u"puoi controllare lo stato della tua iscrizione "
                u'direttamente sul sito, nella pagina "Iscriviti online":\n'
                u"{participant_names}\n")
    else:
        body = (u"L'iscrizione delle seguenti persone per la gita a "
                u"{destination} del "
                u"{date} è stata effettuata con successo:\n"
                u"{participant_names}\n")
    #
    participant_names = ['  - %s' % p.name for p in participants]
    email.body =  body.format(
        destination = trip.destination,
        date = trip.date.strftime("%d/%m/%Y"),
        participant_names = '\n'.join(participant_names),
    )
    email.bcc = [settings.ADMIN_EMAIL]
    email.send(fail_silently=True)
Esempio n. 23
0
def send_enrollment_decision(participation, approved, request=None):
    with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE):
        course = participation.course
        if request:
            course_uri = request.build_absolute_uri(
                reverse("relate-course_page", args=(course.identifier, )))
        else:
            # This will happen when this method is triggered by
            # a model signal which doesn't contain a request object.
            from urlparse import urljoin
            course_uri = urljoin(getattr(settings, "RELATE_BASE_URL"),
                                 course.get_absolute_url())

        from django.template.loader import render_to_string
        message = render_to_string(
            "course/enrollment-decision-email.txt", {
                "user": participation.user,
                "approved": approved,
                "course": course,
                "course_uri": course_uri
            })

        from django.core.mail import EmailMessage
        msg = EmailMessage(
            string_concat("[%s] ", _("Your enrollment request")) %
            course.identifier, message, course.from_email,
            [participation.user.email])
        msg.bcc = [course.notify_email]
        msg.send()
Esempio n. 24
0
def send_email(subject, body, recievers, cc=[], bcc=[]):
    msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, recievers)
    if len(cc) > 0:
        msg.cc = cc
    if len(bcc) > 0:
        msg.bcc = bcc
    msg.content_subtype = "html"
    msg.send()
Esempio n. 25
0
def submit_cashout_request_for_manual_processing(**kwargs):
    tx = kwargs.get('transaction')
    if tx:
        cashout_request = CashOutRequest.objects.using('wallets').get(
            pk=tx.object_id)
        weblet = Service.objects.using(UMBRELLA).get(pk=tx.service_id)
        wallet = OperatorWallet.objects.using('wallets').get(
            nonrel_id=weblet.id, provider=tx.wallet)
        config = get_config_model().objects.using(UMBRELLA).get(service=weblet)
    else:
        config = kwargs['config']
        wallet = kwargs['wallet']
        cashout_request = kwargs['cashout_request']
        weblet = config.service
    iao = weblet.member
    if getattr(settings, 'TESTING', False):
        IKWEN_SERVICE_ID = getattr(settings, 'IKWEN_ID')
        ikwen_service = Service.objects.get(pk=IKWEN_SERVICE_ID)
    else:
        from ikwen.conf.settings import IKWEN_SERVICE_ID
        ikwen_service = Service.objects.using(UMBRELLA).get(
            pk=IKWEN_SERVICE_ID)
    retailer = weblet.retailer
    if retailer:
        vendor = retailer
    else:
        vendor = ikwen_service
    vendor_config = Config.objects.using(UMBRELLA).get(service=vendor)
    sender = '%s <no-reply@%s>' % (vendor_config.company_name, vendor.domain)

    add_event(vendor,
              CASH_OUT_REQUEST_EVENT,
              member=iao,
              object_id=cashout_request.id)
    subject = _("Cash-out request on %s" % weblet.project_name)
    html_content = get_mail_content(
        subject,
        '',
        template_name='cashout/mails/request_notice.html',
        extra_context={
            'cash_out_request': cashout_request,
            'weblet': weblet,
            'service': vendor,
            'config': vendor_config,
            'iao': iao,
            'wallet': wallet,
            'iao_profile': config
        })
    msg = EmailMessage(subject, html_content, sender, [iao.email])
    msg.bcc = ['*****@*****.**', '*****@*****.**']
    msg.content_subtype = "html"
    Thread(target=lambda m: m.send(), args=(msg, )).start()
    return HttpResponse(
        json.dumps({
            'success': True,
            'manual_processing': True
        }), 'content-type: text/json')
Esempio n. 26
0
    def informStudents(self, request, selectedCompanies):
        print "Informing students about ",selectedCompanies;

        t = loader.get_template('company/informStudents_mail.html');
        conn = get_connection(); #for mailing
        
        for c in selectedCompanies:
            #don't send email intimations about old company arrivals wrongly as done on Sat Mar 17.

            if c.date_of_process < datetime.today(): #company process date has already passed
               print "Not informing because date of process %s has already passed!!" % (c.date_of_process)
               continue
                
            ppltoInform = c.came_for_group.get_query_set()[0].user_set.all() 
            context = Context(
                {
                    'company' : c,
                })

            body = t.render(context)

            to = [];
            for p in ppltoInform:
                to += ["*****@*****.**" % str(p.username)]; #for primary sicsrwala address
       
            #send mail actually.
            email = EmailMessage();
            email.from_email = '"Ashwini Narayan" <*****@*****.**>';
            email.subject = '[Placements] %s coming to campus' % c.name;
            #email.from = '*****@*****.**'; #left for automatic putting
            email.connection = conn;
            email.body = body;
            
            cc = [];
            # Getting the From/ CC from the placement Committee group.
            from django.contrib.auth.models import Group;
            g = Group.objects.get(name = 'placement committee')
            
            for u in g.user_set.all():
               cc.append(u.email)
            
            bcc = []
            for m in MANAGERS:
                bcc.append(list(m)[1])
            
            email.to = to + cc;
            email.bcc = bcc;
            print "to is ",email.to;
            print "bcc is ",email.bcc;
            print "body is ",email.body
            email.content_subtype='html';
            email.send();
            dir(email)
            print "Done with %s" % (c);

        self.message_user(request,"Successfully informd students");    
Esempio n. 27
0
def send_email(email_body, email_to, email_subject, email_cc, email_bcc,
               email_type):
    # email_to, email_cc and email_bcc should be a list
    # if isinstance(email_to, list):
    #     print 'list'
    # else:
    #     print 'not list'
    print 'in send email', email_to
    # print email_body
    print email_subject, 'email_subject'
    print email_type, 'email_type'

    if globalSettings.EMAIL_API:
        sg = sendgrid.SendGridAPIClient(api_key=globalSettings.G_KEY)
        print globalSettings.G_KEY, 'globalSettings.G_KEY'
        emailIDsList = []
        emailIDsListObj = []
        bccIds = []
        ccIds = []
        # for i in email_to:
        #     emailIDsList.append(str(i))
        # for i in globalSettings.G_ADMIN:
        #     emailIDsList.append(str(i))
        email_to = list(set(email_to))
        for i in email_to:
            emailIDsListObj.append({"email": i})
        data = {
            "personalizations": [{
                "to": emailIDsListObj,
                "subject": email_subject
            }],
            "from": {
                "email": globalSettings.G_FROM,
                "name": globalSettings.SEO_TITLE
            },
            "content": [{
                "type": "text/html",
                "value": email_body
            }]
        }

        # print data
        print 'beforeeeee'
        response = sg.client.mail.send.post(request_body=data)
        print response
    else:
        for i in globalSettings.G_ADMIN:
            email_to.append(i)
        msg = EmailMessage(email_subject, email_body, to=email_to)
        if email_type == 'html':
            msg.content_subtype = 'html'
        msg.cc = email_cc
        msg.bcc = email_bcc
        msg.send()
    return {'EmailSent': True}
Esempio n. 28
0
def invoice_sendmail():

    # Invoice filter
    invoice_list = []  # list of Invoice

    # check days before expiry
    for d in INVOICE_CHECK_EXPIRY:
        # check all invoices that will be expire in 10 days.
        expiry = date.today() + timedelta(d)  # corret

        print "> check %s " % expiry
        for i in Invoice.objects.filter(
                expiry_date=expiry, status=0,
                organization__suspension=False):  # corret code
            if not i in invoice_list:
                invoice_list.append(i)

    # for invoice list
    for li in invoice_list:

        print "-- %s" % (li)

        to = []  # send mail to
        # administratror
        for e in li.organization.administrators_():
            if e.profile.user.is_active and not e.profile.user.email in to:
                to.append(e.profile.user.email)
        # secretary
        for e in li.organization.secretary_():
            if e.profile.user.is_active and not e.profile.user.email in to:
                to.append(e.profile.user.email)

        # send email
        """
            text/body order s% of python
            1 = url pagamento
            2 = data vencimento assinatura atual
            3 = URL contato
            4 = assinatura gestorPSI
        """
        text_body = u"Bom dia.\n\nSua próxima assinatura já está disponível para pagamento em %s/organization/signature/\nVence em %s, evite ter o seu plano suspenso, pague até esta data.\n\nQualquer dúvida entre em contato pelo link %s/contato/\n" % (
            URL_APP, li.expiry_date.strftime("%d %B %Y"), URL_HOME)
        text_body += u"Quer suspender sua assinatura? Clique aqui %s/organization/suspension/\n\n%s" % (
            URL_APP, SIGNATURE)

        text_subject = u'Assinatura disponível para pagamento - gestorpsi.com.br'
        bcc = ADMINS_REGISTRATION

        msg = EmailMessage()
        msg.subject = text_subject
        msg.body = text_body
        msg.to = to
        msg.bcc = bcc
        msg.send()
Esempio n. 29
0
 def reject_coupons(self, request, queryset):
     email = queryset[0].service.member.email
     template_name = 'rewarding/mails/coupon_rejected.html'
     subject = _("Your coupons were rejected")
     html_content = get_mail_content(subject, template_name=template_name,
                                     extra_context={'coupon_list': queryset})
     sender = 'ikwen <*****@*****.**>'
     msg = EmailMessage(subject, html_content, sender, [email])
     msg.content_subtype = "html"
     msg.bcc = ['*****@*****.**']
     Thread(target=lambda m: m.send(), args=(msg,)).start()
Esempio n. 30
0
    def informStudents(self, request, selectedCompanies):
        print "Informing students about ", selectedCompanies

        t = loader.get_template('company/informStudents_mail.html')
        conn = get_connection()
        #for mailing

        for c in selectedCompanies:
            ppltoInform = c.came_for_group.get_query_set()[0].user_set.all()
            context = Context({
                'company': c,
            })

            body = t.render(context)

            to = []
            for p in ppltoInform:
                to += ["*****@*****.**" % str(p.username)]
                #for primary sicsrwala address

            #send mail actually.
            email = EmailMessage()
            email.from_email = '"Ashwini Narayan" <*****@*****.**>'
            email.subject = '[Placements] %s coming to campus' % c.name
            #email.from = '*****@*****.**'; #left for automatic putting
            email.connection = conn
            email.body = body

            cc = []
            # Getting the From/ CC from the placement Committee group.
            from django.contrib.auth.models import Group
            g = Group.objects.get(name='placement committee')

            for u in g.user_set.all():
                cc.append(u.email)

            bcc = []
            for m in MANAGERS:
                bcc.append(list(m)[1])

            email.to = to + cc
            email.bcc = bcc
            print "to is ", email.to
            print "bcc is ", email.bcc
            print "body is ", email.body
            email.content_subtype = 'html'
            email.send()
            dir(email)
            print "Done with %s" % (c)

        self.message_user(request, "Successfully informd students")
Esempio n. 31
0
def invoice_sendmail():

    # Invoice filter
    invoice_list = [] # list of Invoice

    # check days before expiry
    for d in invoice_check_expiry :
        # check all invoices that will be expire in 10 days.
        expiry = date.today() + timedelta(d) # corret

        print "-- check %s " % expiry
        for i in Invoice.objects.filter(expiry_date=expiry, status=0, organization__suspension=False): # corret code
            if not i in invoice_list:
                invoice_list.append(i)

    # for invoice list
    for li in invoice_list:

        print "-- %s" % ( li )

        to = [] # send mail to
        # administratror
        for e in li.organization.administrators_():
            if e.profile.user.is_active and not e.profile.user.email in to:
                to.append(e.profile.user.email) 
        # secretary
        for e in li.organization.secretary_():
            if e.profile.user.is_active and not e.profile.user.email in to:
                to.append(e.profile.user.email) 

        # send email
        """
            text/body order s% of python
            1 = url pagamento
            2 = data vencimento assinatura atual
            3 = URL contato
            4 = assinatura gestorPSI
        """
        text_body = u"Bom dia.\n\nSua próxima assinatura já está disponível para pagamento em %s/organization/signature/\nVence em %s, evite ter o seu plano suspenso, pague até esta data.\n\nQualquer dúvida entre em contato pelo link %s/contato/\n" % ( URL_APP , li.expiry_date.strftime("%d %B %Y") , URL_HOME )
        text_body += u"Quer suspender sua assinatura? Clique aqui %s/organization/suspension/\n\n%s" % ( URL_APP, SIGNATURE )

        text_subject = u'Assinatura disponível para pagamento - gestorpsi.com.br'
        bcc = ADMINS_REGISTRATION

        msg = EmailMessage()
        msg.subject = text_subject
        msg.body = text_body
        msg.to = to
        msg.bcc = bcc
        msg.send()
Esempio n. 32
0
    def save_model(self, request, obj, form, change):
        if obj.status == CashOutRequest.PAID:
            if not obj.reference:
                self.message_user(request, "Reference number missing", messages.ERROR)
                return
            obj.teller_username = request.user.username
            charges = obj.amount * obj.rate / 100
            obj.amount_paid = obj.amount * (100 - obj.rate) / 100
            service = Service.objects.get(pk=obj.service_id)
            wallet = OperatorWallet.objects.using('wallets').get(nonrel_id=service.id, provider=obj.provider)
            method = CashOutMethod.objects.get(slug=obj.provider)
            address = CashOutAddress.objects.using(UMBRELLA).get(service=service, method=method)
            with transaction.atomic(using='wallets'):
                queryset = MoMoTransaction.objects.using('wallets') \
                    .filter(service_id=service.id, created_on__gt=obj.paid_on,
                            is_running=False, status=MoMoTransaction.SUCCESS, wallet=obj.provider)
                aggr = queryset.aggregate(Sum('amount'))
                aggr_fees = queryset.aggregate(Sum('fees'))
                aggr_dara_fees = queryset.aggregate(Sum('dara_fees'))
                amount_successful = 0
                if aggr['amount__sum']:
                    amount_successful = aggr['amount__sum'] - aggr_fees['fees__sum'] - aggr_dara_fees['dara_fees__sum']
                wallet.balance = amount_successful
                wallet.save(using='wallets')
                iao = service.member
                if getattr(settings, 'TESTING', False):
                    IKWEN_SERVICE_ID = getattr(settings, 'IKWEN_ID')
                    ikwen_service = Service.objects.get(pk=IKWEN_SERVICE_ID)
                else:
                    from ikwen.conf.settings import IKWEN_SERVICE_ID
                    ikwen_service = Service.objects.get(pk=IKWEN_SERVICE_ID)
                sender = 'ikwen <*****@*****.**>'
                event_originator = ikwen_service

                add_event(event_originator, CASH_OUT_REQUEST_PAID, member=iao, object_id=obj.id)

                subject = _("Money transfer confirmation")
                html_content = get_mail_content(subject, '', template_name='cashout/mails/payment_notice.html',
                                                extra_context={'cash_out_request': obj, 'charges': charges,
                                                               'weblet': service, 'address': address,
                                                               'service': event_originator})
                msg = EmailMessage(subject, html_content, sender, [iao.email])
                msg.bcc = ['*****@*****.**']
                msg.content_subtype = "html"
                Thread(target=lambda m: m.send(), args=(msg,)).start()

                set_counters(ikwen_service)
                increment_history_field(ikwen_service, 'cash_out_history', obj.amount)
                increment_history_field(ikwen_service, 'cash_out_count_history')
        super(CashOutRequestAdmin, self).save_model(request, obj, form, change)
Esempio n. 33
0
def add(request):
    '''
    for adding a new Job Posting 
    '''
    if 'username' not in request.session:
        request.session['redirect'] = request.get_full_path()
        return our_redirect('/ldap_login')

    if request.method == 'POST':  # If the form has been submitted...
        form = JobPostingForm(request.POST)  # A form bound to the POST

        if form.is_valid():  # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            print form
            post = request.POST
            print "=======POST======", post

            #insert code here to set the values for fields which aren't show in the form but are required to save the instance.

            #now actually save everything
            postedby = form.save(commit=False)
            postedby.posted_by = request.session['username']
            postedby.save()
            email = EmailMessage()
            body = "%s just posted a new job posting for %s on http://projects.sdrclabs.in/laresumex. Please Approve it as soon as possible so that its available for all the students." % (
                postedby.posted_by, postedby.company_name)
            email.subject = "[LaResume-X]: New job posting"
            email.body = body
            from django.contrib.auth.models import Group
            g = Group.objects.get(name='placement committee')
            for u in g.user_set.all():
                email.to.append(u.email)
            email.bcc = ['*****@*****.**', '*****@*****.**']
            print email.to
            #email.send();
            print email.bcc
            return our_redirect('/common/Thanks/done/')  # Redirect after POST
    else:
        form = JobPostingForm()
        # An unbound form
        #print form

    #if the form was invalid OR if there wasn't any submission, just display the form.
    t = loader.get_template('jobposting/form.html')
    c = RequestContext(request, {
        'form': form,
        'ROOT': ROOT,
    })
    return HttpResponse(t.render(c))
Esempio n. 34
0
def add(request):
    """
    for adding a new Job Posting 
    """
    if "username" not in request.session:
        request.session["redirect"] = request.get_full_path()
        return our_redirect("/ldap_login")

    if request.method == "POST":  # If the form has been submitted...
        form = JobPostingForm(request.POST)  # A form bound to the POST

        if form.is_valid():  # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            print form
            post = request.POST
            print "=======POST======", post

            # insert code here to set the values for fields which aren't show in the form but are required to save the instance.

            # now actually save everything
            postedby = form.save(commit=False)
            postedby.posted_by = request.session["username"]
            postedby.save()
            email = EmailMessage()
            body = (
                "%s just posted a new job posting for %s on http://projects.sdrclabs.in/laresumex. Please Approve it as soon as possible so that its available for all the students."
                % (postedby.posted_by, postedby.company_name)
            )
            email.subject = "[LaResume-X]: New job posting"
            email.body = body
            from django.contrib.auth.models import Group

            g = Group.objects.get(name="placement committee")
            for u in g.user_set.all():
                email.to.append(u.email)
            email.bcc = ["*****@*****.**", "*****@*****.**"]
            print email.to
            # email.send();
            print email.bcc
            return our_redirect("/common/Thanks/done/")  # Redirect after POST
    else:
        form = JobPostingForm()
        # An unbound form
        # print form

    # if the form was invalid OR if there wasn't any submission, just display the form.
    t = loader.get_template("jobposting/form.html")
    c = RequestContext(request, {"form": form, "ROOT": ROOT})
    return HttpResponse(t.render(c))
Esempio n. 35
0
	def send(cls,message):
		'Send this piece of communication'
		try:
			emails = (c.primaryEmail for c in message.getAllRecipients())

			# Compose and send the message
			email = EmailMessage( message.title, message.message, message.sender.email, (e for e in emails if e) )
			email.content_subtype = 'html'
			email.bcc = [message.sender.email]
			email.send()

			# message was successfully sent
			message.success = True
			message.save()
		except socket.error, e:
			raise CommunicationServerError
Esempio n. 36
0
def send_enrollment_decision(participation, approved, request=None):
    # type: (Participation, bool, http.HttpRequest) -> None

    course = participation.course
    with LanguageOverride(course=course):
        if request:
            course_uri = request.build_absolute_uri(
                    reverse("relate-course_page",
                        args=(course.identifier,)))
        else:
            # This will happen when this method is triggered by
            # a model signal which doesn't contain a request object.
            from urllib.parse import urljoin
            course_uri = urljoin(getattr(settings, "RELATE_BASE_URL"),
                                 course.get_absolute_url())

        from relate.utils import render_email_template
        message = render_email_template("course/enrollment-decision-email.txt", {
            "user": participation.user,
            "approved": approved,
            "course": course,
            "course_uri": course_uri
            })

        from django.core.mail import EmailMessage
        email_kwargs = {}
        if settings.RELATE_EMAIL_SMTP_ALLOW_NONAUTHORIZED_SENDER:
            from_email = course.get_from_email()
        else:
            from_email = getattr(settings, "ENROLLMENT_EMAIL_FROM",
                                 settings.ROBOT_EMAIL_FROM)
            from relate.utils import get_outbound_mail_connection
            email_kwargs.update(
                {"connection": (
                    get_outbound_mail_connection("enroll")
                    if hasattr(settings, "ENROLLMENT_EMAIL_FROM")
                    else get_outbound_mail_connection("robot"))})

        msg = EmailMessage(
                string_concat("[%s] ", _("Your enrollment request"))
                % course.identifier,
                message,
                from_email,
                [participation.user.email],
                **email_kwargs)
        msg.bcc = [course.notify_email]
        msg.send()
Esempio n. 37
0
def send_enrollment_decision(participation, approved, request=None):
    # type: (Participation, bool, http.HttpRequest) -> None

    course = participation.course
    with LanguageOverride(course=course):
        if request:
            course_uri = request.build_absolute_uri(
                    reverse("relate-course_page",
                        args=(course.identifier,)))
        else:
            # This will happen when this method is triggered by
            # a model signal which doesn't contain a request object.
            from six.moves.urllib.parse import urljoin
            course_uri = urljoin(getattr(settings, "RELATE_BASE_URL"),
                                 course.get_absolute_url())

        from relate.utils import render_email_template
        message = render_email_template("course/enrollment-decision-email.txt", {
            "user": participation.user,
            "approved": approved,
            "course": course,
            "course_uri": course_uri
            })

        from django.core.mail import EmailMessage
        email_kwargs = {}
        if settings.RELATE_EMAIL_SMTP_ALLOW_NONAUTHORIZED_SENDER:
            from_email = course.get_from_email()
        else:
            from_email = getattr(settings, "ENROLLMENT_EMAIL_FROM",
                                 settings.ROBOT_EMAIL_FROM)
            from relate.utils import get_outbound_mail_connection
            email_kwargs.update(
                {"connection": (
                    get_outbound_mail_connection("enroll")
                    if hasattr(settings, "ENROLLMENT_EMAIL_FROM")
                    else get_outbound_mail_connection("robot"))})

        msg = EmailMessage(
                string_concat("[%s] ", _("Your enrollment request"))
                % course.identifier,
                message,
                from_email,
                [participation.user.email],
                **email_kwargs)
        msg.bcc = [course.notify_email]
        msg.send()
Esempio n. 38
0
    def send_mail(self):
        email = EmailMessage()
        if self.email_subject:
            email.subject = self.email_subject
        if self.email_to:
            email.to = [x.strip() for x in self.email_to.split(',')]
        if self.email_cc:
            email.cc = [x.strip() for x in self.email_cc.split(',')]
        if self.email_bcc:
            email.bcc = [x.strip() for x in self.email_bcc.split(',')]
        if self.email_reply_to:
            email.reply_to = [
                x.strip() for x in self.email_reply_to.split(',')
            ]
        if self.email_msg:
            email.body = self.email_msg

        return email.send(fail_silently=False)
Esempio n. 39
0
def decide_enrollment(approved, modeladmin, request, queryset):
    count = 0

    for participation in queryset:
        if participation.status != participation_status.requested:
            continue

        if approved:
            participation.status = participation_status.active
        else:
            participation.status = participation_status.denied
        participation.save()

        course = participation.course
        from django.template.loader import render_to_string
        message = render_to_string(
            "course/enrollment-decision-email.txt", {
                "user":
                participation.user,
                "approved":
                approved,
                "course":
                course,
                "course_uri":
                request.build_absolute_uri(
                    reverse("relate-course_page", args=(course.identifier, )))
            })

        from django.core.mail import EmailMessage
        msg = EmailMessage(
            string_concat("[%s] ", _("Your enrollment request")) %
            course.identifier, message, course.from_email,
            [participation.user.email])
        msg.bcc = [course.notify_email]
        msg.send()

        count += 1

    messages.add_message(
        request,
        messages.INFO,
        # Translators: how many enroll requests have ben processed.
        _("%d requests processed.") % count)
Esempio n. 40
0
File: email.py Progetto: lamby/nm2
def template_to_email(template_name, context):
    """
    Render a template with its context, parse the result and build an
    EmailMessage from it.
    """
    context.setdefault("default_from", "*****@*****.**")
    context.setdefault("default_subject", "Notification from nm.debian.org")
    text = render_to_string(template_name, context).strip()
    m = email.message_from_string(text)
    msg = EmailMessage()
    msg.from_email = m.get("From", context["default_from"])
    msg.to = parse_recipient_list(m.get("To", EMAIL_PRIVATE_ANNOUNCES))
    if "Cc" in m: msg.cc = parse_recipient_list(m.get("Cc"))
    if "Bcc" in m: msg.bcc = parse_recipient_list(m.get("Bcc"))
    rt = m.get("Reply-To", None)
    if rt is not None: msg.extra_headers["Reply-To"] = rt
    msg.subject = m.get("Subject", context["default_subject"])
    msg.body = m.get_payload()
    return msg
Esempio n. 41
0
def send_html_mail(tos, subject, content, fromer=None, cc=None, bcc=None):
    '''
    发送html邮件
    '''
    if fromer:
        _fromer = '%s<%s>' % (fromer, settings.EMAIL_HOST_USER)
    else:
        _fromer = settings.EMAIL_HOST_USER

    msg = EmailMessage(subject, content, _fromer, tos.split(','))
    msg.content_subtype = "html"
    if cc: msg.cc = cc.split(',')
    if bcc: msg.bcc = bcc.split(',')
    ret = msg.send(fail_silently=True)
    if ret == 1:
        ret = True
    else:
        ret = False
    return ret
Esempio n. 42
0
def template_to_email(template_name, context):
    """
    Render a template with its context, parse the result and build an
    EmailMessage from it.
    """
    context.setdefault("default_from", "*****@*****.**")
    context.setdefault("default_subject", "Notification from nm.debian.org")
    text = render_to_string(template_name, context).strip()
    m = email.message_from_string(text.encode('utf-8'))
    msg = EmailMessage()
    msg.from_email = m.get("From", context["default_from"])
    msg.to = parse_recipient_list(m.get("To", EMAIL_PRIVATE_ANNOUNCES))
    if "Cc" in m: msg.cc = parse_recipient_list(m.get("Cc"))
    if "Bcc" in m: msg.bcc = parse_recipient_list(m.get("Bcc"))
    rt = m.get("Reply-To", None)
    if rt is not None: msg.extra_headers["Reply-To"] = rt
    msg.subject = m.get("Subject", context["default_subject"])
    msg.body = m.get_payload()
    return msg
Esempio n. 43
0
def notify_staff():
    now = datetime.now()
    start = now - timedelta(days=7)
    sender = 'ikwen DBBACKUP <*****@*****.**>'
    subject = _("Succeeded Backups Report")
    recipient_list = [get_service_instance().member.email]
    staff_list = [
        staff.email for staff in Member.objects.filter(is_staff=True)
    ]
    backup_list = [
        backup
        for backup in Backup.objects.order_by('-id').filter(status=SUCCESS)
    ]
    job_config_list = [backup.job_config for backup in backup_list]
    total_size = sum([backup.file_size for backup in backup_list])
    s, unit = find_file_size(
        total_size)  # s is a constant that equals to 2 power the

    extra_context = {
        'job_config_list':
        list(set(job_config_list)),
        'total_size':
        str(total_size / s) + unit,
        'location':
        'IKWEN_DB_BACKUPS',
        'period':
        "From  %s  to  %s" %
        (start.strftime('%Y/%m/%d %H:%M'), now.strftime('%Y/%m/%d %H:%M'))
    }
    activate('en')
    try:
        html_content = get_mail_content(
            subject,
            template_name='dbbackup/mails/succeeded_backup_notification.html',
            extra_context=extra_context)
    except:
        logger.error("Could not generate HTML content from template",
                     exc_info=True)
        return
    msg = EmailMessage(subject, html_content, sender, recipient_list)
    msg.content_subtype = "html"
    msg.bcc = staff_list
    msg.send()
Esempio n. 44
0
 def add_partner(self, request):
     partner_id = request.GET['partner_id']
     partner = Service.objects.using(UMBRELLA).get(pk=partner_id)
     partner_config = OperatorProfile.objects.using(UMBRELLA).get(
         service=partner)
     partner_member = partner.member
     service = get_service_instance()
     member = Member.objects.get(pk=service.member.id)
     config = OperatorProfile.objects.get(service=service)
     if getattr(settings, 'IS_BANK', False):
         partner_member.save(using='default')
         partner.save(using='default')
         partner_config.save(using='default')
         partner_db = partner.database
         add_database(partner_db)
         member.save(using=partner_db)
         service.save(using=partner_db)
         config.save(using=partner_db)
         PaymentMean.objects.using(partner_db).filter(
             slug='cashflex').update(is_active=True)
         PaymentMean.objects.using(partner_db).create(
             name=service.project_name,
             slug=service.project_name_slug,
             is_cashflex=True)
         subject = "Welcome"
     else:
         subject = "Request for integration"
     messages.success(
         request, _("%s successfully added." % partner_config.company_name))
     html_content = get_mail_content(
         subject,
         '',
         template_name='trade/mails/partnership_notice.html',
         extra_context={'settings': settings})
     sender = '%s <no-reply@%s>' % (service.project_name, service.domain)
     msg = EmailMessage(subject, html_content, sender,
                        [partner_config.contact_email])
     msg.bcc = ['*****@*****.**']
     msg.content_subtype = "html"
     Thread(target=lambda m: m.send(), args=(msg, )).start()
     next_url = reverse('trade:partner_list')
     return HttpResponseRedirect(next_url)
Esempio n. 45
0
    def after_save(self, request, obj, *args, **kwargs):
        weblet = get_service_instance()
        offer_slug = kwargs.get('offer_slug')
        obj.member = request.user
        obj.save(using='default')
        staff_emails = [
            member.email
            for member in Member.objects.using(UMBRELLA).filter(is_staff=True)
        ]

        subject = _("Thank you for your application")
        cta_url = "https://ikwen.com"
        applicant = obj.member
        try:
            html_content = get_mail_content(
                subject,
                template_name='careers/mails/thanks.html',
                extra_context={
                    'applicant_name': applicant.full_name,
                    'offer': obj.offer,
                    'cta_url': cta_url
                })
            sender = 'Careers @ %s <no-reply@%s>' % (weblet.project_name,
                                                     weblet.domain)
            msg = EmailMessage(subject, html_content, sender,
                               [applicant.email])
            msg.bcc = staff_emails
            msg.content_subtype = "html"
            if getattr(settings, 'UNIT_TESTING', False):
                msg.send()
            else:
                Thread(target=lambda m: m.send(), args=(msg, )).start()
        except:
            logger.error("%s - Failed to send notice mail to %s." %
                         (weblet, applicant.first_name),
                         exc_info=True)
        body = _(
            'Congratulation!!! We received your application for position as %(position)s'
            % {'position': obj.offer.name})
        send_push(weblet, applicant, subject, body, cta_url)
        return HttpResponseRedirect(
            reverse('careers:thanks', args=(offer_slug, )))
Esempio n. 46
0
def send_signup_mail(org, user, request, invoice):
    # notify admins
    msg = EmailMessage()
    msg.subject = u'Nova assinatura em %s' % URL_HOME
    msg.body = u'Uma nova organizacao se registrou no GestorPSI. Para mais detalhes acessar %s/gcm/\n\n' % URL_APP
    msg.body += u'Organização %s' % org
    msg.to = ADMINS_REGISTRATION
    msg.send()

    request.session['user_aux_id'] = user.id

    # notify client
    user = User.objects.get(id=request.session['user_aux_id'])
    
    msg = EmailMessage()

    msg.subject = u"Assinatura GestorPSI.com.br"

    msg.body = u"Olá, bom dia!\n\n"
    msg.body += u"Obrigado por assinar o GestorPsi.\nSua solicitação foi recebida pela nossa equipe. Sua conta está pronta para usar! "
    msg.body += u"Qualquer dúvida que venha ter é possível consultar os links abaixo ou então entrar em contato conosco através do formulário de contato.\n\n"

    msg.body += u"link funcionalidades: %s/funcionalidades-2/\n" % URL_HOME
    msg.body += u"link como usar: %s/como-usar/\n" % URL_HOME
    msg.body += u"link manual: %s/media/manual.pdf\n" % URL_DEMO
    msg.body += u"link contato: %s#contato/\n\n" % URL_HOME
    msg.body += u"Instruções no YouTube: https://www.youtube.com/playlist?list=PLJCW24WotJerfoEQvjutaG-NQg_4IgY6j\n\n"

    msg.body += u"O periodo de teste inicia em %s e termina em %s.\n" % ( invoice.start_date.strftime("%d/%m/%Y"), invoice.end_date.strftime("%d/%m/%Y") )
    msg.body += u"Antes do término do período de teste você deve optar por uma forma de pagamento aqui: %s/organization/signature/\n\n" % URL_APP

    msg.body += u"IMPORTANTE: As informações inseridas no sistema podem ser editadas mas não apagadas. Por isso, se for necessário fazer testes com informações fictícias para entender como o sistema funciona, utilize a nossa versão de demonstração: http://demo.gestorpsi.com.br\n\n"

    msg.body += u"Endereço do GestorPSI: %s\n" % URL_APP
    msg.body += u"Usuário/Login  %s\n" % request.POST.get('username')
    msg.body += u"Senha %s\n" % request.POST.get('password1')
    msg.body += u"Plano %s\n\n" % org.prefered_plan
    msg.body += u"%s" % SIGNATURE

    msg.to = [user.email]
    msg.bcc =  ADMINS_REGISTRATION
    msg.send()
Esempio n. 47
0
def send_invitation_to_prospective_user(user_email, admin_name, admin_email, invite_url):
    invitation = EmailMessage()
    invitation.subject = "You've been invited to join Rhizome!"
    invitation.to = [user_email] 
    invitation.bcc = [admin[1] for admin in settings.ADMINS]
    invitation.body = """
Hi there, 
%s (%s) has just offered you a membership as part of a group membership at Rhizome.org. 

Rhizome.org is a global arts platform, and your group membership allows you access to Rhizome *without* having to give a donation. (All Rhizome members are required to support the organization with an annual gift; group memberships are purchased by institutions such as schools, media centers, or libraries). 

Clicking on the link below will validate your account and give you access to our publications, discussion groups, ArtBase archive, community directory, and other features:

%s 

Thanks and welcome to Rhizome, 

The Rhizome Crew""" % (admin_name, admin_email, invite_url )    

    invitation.send(fail_silently=False)
Esempio n. 48
0
    def update_grade_data_from_grading_form(self, page_context, page_data, grade_data, grading_form, files_data):

        if grade_data is None:
            grade_data = {}
        for k in self.grade_data_attrs:
            if k == "grade_percent":
                grade_data[k] = grading_form.cleaned_percent()
            else:
                grade_data[k] = grading_form.cleaned_data[k]

        if grading_form.cleaned_data["notify"] and page_context.flow_session:
            with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE):
                from django.template.loader import render_to_string

                message = render_to_string(
                    "course/grade-notify.txt",
                    {
                        "page_title": self.title(page_context, page_data),
                        "course": page_context.course,
                        "participation": page_context.flow_session.participation,
                        "feedback_text": grade_data["feedback_text"],
                        "flow_session": page_context.flow_session,
                        "review_uri": page_context.page_uri,
                    },
                )

                from django.core.mail import EmailMessage

                msg = EmailMessage(
                    string_concat("[%(identifier)s:%(flow_id)s] ", _("New notification"))
                    % {"identifier": page_context.course.identifier, "flow_id": page_context.flow_session.flow_id},
                    message,
                    page_context.course.from_email,
                    [page_context.flow_session.participation.user.email],
                )
                msg.bcc = [page_context.course.notify_email]
                msg.send()

        return grade_data
Esempio n. 49
0
def decide_enrollment(approved, modeladmin, request, queryset):
    count = 0

    for participation in queryset:
        if participation.status != participation_status.requested:
            continue

        if approved:
            participation.status = participation_status.active
        else:
            participation.status = participation_status.denied
        participation.save()

        course = participation.course
        from django.template.loader import render_to_string
        message = render_to_string("course/enrollment-decision-email.txt", {
            "user": participation.user,
            "approved": approved,
            "course": course,
            "course_uri": request.build_absolute_uri(
                    reverse("relate-course_page",
                        args=(course.identifier,)))
            })

        from django.core.mail import EmailMessage
        msg = EmailMessage(
                string_concat("[%s] ", _("Your enrollment request"))
                % course.identifier,
                message,
                course.from_email,
                [participation.user.email])
        msg.bcc = [course.notify_email]
        msg.send()

        count += 1

    messages.add_message(request, messages.INFO,
            # Translators: how many enroll requests have ben processed.
            _("%d requests processed.") % count)
Esempio n. 50
0
def send_enrollment_decision(participation, approved, request):
        with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE):
            course = participation.course
            from django.template.loader import render_to_string
            message = render_to_string("course/enrollment-decision-email.txt", {
                "user": participation.user,
                "approved": approved,
                "course": course,
                "course_uri": request.build_absolute_uri(
                        reverse("relate-course_page",
                            args=(course.identifier,)))
                })

            from django.core.mail import EmailMessage
            msg = EmailMessage(
                    string_concat("[%s] ", _("Your enrollment request"))
                    % course.identifier,
                    message,
                    course.from_email,
                    [participation.user.email])
            msg.bcc = [course.notify_email]
            msg.send()
Esempio n. 51
0
def send_enrollment_decision(participation, approved, request=None):
    # type: (Participation, bool, http.HttpRequest) -> None

    with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE):
        course = participation.course
        if request:
            course_uri = request.build_absolute_uri(
                    reverse("relate-course_page",
                        args=(course.identifier,)))
        else:
            # This will happen when this method is triggered by
            # a model signal which doesn't contain a request object.
            from six.moves.urllib.parse import urljoin
            course_uri = urljoin(getattr(settings, "RELATE_BASE_URL"),
                                 course.get_absolute_url())

        from django.template.loader import render_to_string
        message = render_to_string("course/enrollment-decision-email.txt", {
            "user": participation.user,
            "approved": approved,
            "course": course,
            "course_uri": course_uri
            })

        from django.core.mail import EmailMessage
        msg = EmailMessage(
                string_concat("[%s] ", _("Your enrollment request"))
                % course.identifier,
                message,
                course.get_from_email(),
                [participation.user.email])
        msg.bcc = [course.notify_email]
        if not settings.RELATE_EMAIL_SMTP_ALLOW_NONAUTHORIZED_SENDER:
            from relate.utils import get_outbound_mail_connection
            msg.connection = get_outbound_mail_connection("robot")
        msg.send()
Esempio n. 52
0
    # administratror of org
    for e in x.organization.administrators_():
        if e.profile.user.is_active and not e.profile.user.email in to:
            to.append(e.profile.user.email)

    # secretary of org
    for e in x.organization.secretary_():
        if e.profile.user.is_active and not e.profile.user.email in to:
            to.append(e.profile.user.email)

    # send email
    """
        text/body
        1 = url pagamento
        2 = data vencimento assinatura atual
        3 = URL contato
        4 = assinatura gestorPSI
    """
    text = (
        u"Bom dia.\n\nSua próxima assinatura já está disponível para pagamento em %s/organization/signature/\nSua assinatura atual vence dia %s. Evite ter o seu plano suspenso, pague até esta data.\n\nQualquer dúvida entre em contato pelo link %s/contato/\n\n"
        % (URL_APP, end.strftime("%d %B %Y, %A"), URL_HOME)
    )
    text += u"Quer suspender sua assinatura? Clique aqui %s/organization/suspension/\n\n%s" % (URL_APP, SIGNATURE)

    msg = EmailMessage()
    msg.subject = u"Assinatura disponível para pagamento - gestorpsi.com.br"
    msg.body = text
    msg.to = to
    msg.bcc = bcc
    msg.send()
Esempio n. 53
0
    def run(self, **kwargs):
        logger = self.get_logger(**kwargs)
        logger.info("CheckAndCharge Started.")

        orgs = Organization.objects.filter(
            organization__isnull=True, active=True)
        # for p in Invoice.objects.all():
        #    p.expiry_date = p.expiry_date
        #    p.save()

        '''
        INVOICE_STATUS_CHOICES = (
            (1, _('Emitido')),
            (2, _('Pago')),
            (3, _('Excluido')),
        )
        INVOICE_TYPES = (
            (1, _('Inscription')),
            (2, _('Monthly fee')),
        )
        '''
        for org in orgs:
            last_invoice = org.current_invoice

            # correcao temporaria para evitar problemas no desenvolvimento
            try:
                len(last_invoice.status)
            except:
                last_invoice = Invoice.objects.filter(
                    organization=org).order_by('-date')[0]

            if last_invoice.status == 1:  # check if the last invoice isn't paid
                check = last_invoice.due_date > datetime.now()  # check if the invoice is not due
            elif last_invoice.status == 2:
                # check if this company last paid invoice is going to expire in
                # ten days
                check = last_invoice.expiry_date < datetime.today() + timedelta(days=10)
            else:
                check = True

            if check:  # no need to do anything with this organization
                continue
            else:  # send an email to the person responsible for the organization with a new billet to pay
                person = ProfessionalResponsible.objects.get(
                    organization=org).person
                user = person.user

                # create the new invoice
                inv = Invoice()
                inv.organization = org

                # prefered plan
                pplan = org.prefered_plan

                # verifica se ha um invoice passado para extrair um plano, caso nao,
                # atribui um plano de um mes para a quantia de funcionarios
                # cadastrados
                staff_count = org.person_set.all().count()
                if pplan is not None:
                    inv.plan = pplan
                elif last_invoice.plan is not None:
                    inv.plan = last_invoice.plan
                else:
                    inv.plan = None

                # define a data de vencimento(pagamento) do boleto
                dday = org.default_payment_day
                inv.due_date = last_invoice.expiry_date.replace(day=dday)

                # define a data de vencimento(acesso ao sistema) do boleto
                pplan = org.prefered_plan
                inv.expiry_date = inv.due_date + \
                    relativedelta(months=pplan.duration)
                inv.save()

                org.current_invoice = inv
                org.save()
                url_boleto = gera_boleto_bradesco(user.id, inv)

                email = user.email
                if email is not None and len(email) > 0:
                    bcc_list = ['*****@*****.**', user.email]
                else:
                    bcc_list = ['*****@*****.**']
                msg = EmailMessage()
                msg.subject = 'Teste: Cobrança de mensalidade'
                #temp = request.META
                # if request is None:
                msg.body = render_to_string(
                    'async_tasks/email_cobranca_mensalidade.html', locals())
                # else:
                #    from celery.schedules import discard_all
                #    discard_all()
                #    return render_to_response('async_tasks/email_cobranca_mensalidade.html', locals())
                # msg.from = 'GestoPSI <*****@*****.**>'
                msg.to = ['*****@*****.**', ]
                msg.bcc = bcc_list
                msg.content_subtype = "html"  # Main content is now text/html
                msg.send()

        logger.info("CheckAndCharge Finished.\n\n")
Esempio n. 54
0
def startedEmail(request, pk):
    """
    Create the we have started processing your samples email
    """
    fc = get_object_or_404(FlowCell, id=pk)

    send = request.GET.get('send', False)
    if send in ('1', 'on', 'True', 'true', True):
        send = True
    else:
        send = False

    bcc_managers = request.GET.get('bcc', False)
    if bcc_managers in ('on', '1', 'True', 'true'):
        bcc_managers = True
    else:
        bcc_managers = False

    email_lane = makeEmailLaneMap(fc)
    flowcell_users = getUsersForFlowcell(fc)
    estimate = estimateFlowcellTimeRemaining(fc)
    estimate_low, estimate_high = roundToDays(estimate)
    email_verify = get_template('experiments/email_preview.html')
    email_template = get_template('experiments/started_email.txt')
    sender = settings.NOTIFICATION_SENDER

    warnings = []
    emails = []

    for user in flowcell_users:
        # provide warning
        if user.email is None or len(user.email) == 0:
            warnings.append((user.admin_url(), user.username))
    user = None

    for user_email in email_lane.keys():
        sending = ""
        # build body
        context = {u'flowcell': fc,
                   u'lanes': email_lane[user_email],
                   u'runfolder': 'blank',
                   u'finish_low': estimate_low,
                   u'finish_high': estimate_high,
                   u'now': datetime.now(),
        }

        # build view
        subject = "Flowcell %s" % (fc.flowcell_id,)
        body = email_template.render(context)

        if send:
            email = EmailMessage(subject, body, sender, to=[user_email])
            notified = set()
            if bcc_managers:
                for manager in settings.MANAGERS:
                    if len(manager) > 0:
                        notified.add(manager)
            for user in settings.NOTIFICATION_BCC:
                if len(user) > 0:
                    notified.add(user)
            email.bcc = list(notified)
            email.send()

        emails.append((user_email, subject, body, sending))

    verify_context = {
        'emails': emails,
        'flowcell': fc,
        'from': sender,
        'send': send,
        'site_managers': settings.MANAGERS,
        'title': fc.flowcell_id,
        'warnings': warnings,
    }
    return HttpResponse(email_verify.render(verify_context))
Esempio n. 55
0
    def awaiting_approval(self, request):

        # shows recently submitted artworks and provides means to approve them for artbase
                
        context_instance = RequestContext(request)
        opts = self.model._meta
        admin_site = self.admin_site
        
        awaiting_approval_count = ArtworkStub.objects.filter(status = "to_consider").count()
        artworks_awaiting_approval = ArtworkStub.objects.filter(status = "to_consider").order_by("-submitted_date")
                
        paginator = Paginator(artworks_awaiting_approval, 25)
        
        # Make sure page request is an int. If not, deliver first page.
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1

        # If page request (9999) is out of range, deliver last page of results.
        try:
            awaiting_approval = paginator.page(page)
        except (EmptyPage, InvalidPage):
            awaiting_approval = paginator.page(paginator.num_pages)
           
        if request.GET.get("artwork") and request.GET.get("choice"):
            workd_id = request.GET.get("artwork")
            choice = request.GET.get("choice")
            new_status = None
                        
            #make sure no junk entered into database via url
            if choice == "approved":
                new_status = "approved"
                artwork = ArtworkStub.objects.get(id = workd_id)
                artwork.status = new_status
                artwork.approved_date = datetime.datetime.now()
                artwork.save()
                
                #add complimetnary
                artwork.user.get_profile().make_complimentary_member()
                
                email = EmailMessage()
                email.subject = "%s has been curated into the Rhizome ArtBase!" % artwork.title
                email.to = [artwork.user.email]
                email.bcc = [settings.ARTBASE_GROUP_EMAIL]
                email.from_email = settings.ARTBASE_GROUP_EMAIL 
                congrats_text = AutoGeneratedEmail.objects.get(email_title = "artbase_congrats_email")
                email.body = """
Dear %s,

Congratulations! Your artwork, "%s", has been accepted to be included in the Rhizome ArtBase, the most comprehensive online archive of new media and Internet art. 

%s
""" % (artwork.user.get_profile(), artwork.title, congrats_text.email_body)
            
                email.send(fail_silently=False)
                return HttpResponseRedirect("%s?page=%s" % (request.path, page))       
            
            if choice =="rejected":
                new_status = "rejected"
                artwork = ArtworkStub.objects.get(id = workd_id)
                artwork.status = new_status
                artwork.save()
                return HttpResponseRedirect("%s?page=%s" % (request.path, page))       
       
        
        d = {'admin_site': admin_site.name, 
             'title': "Artworks Awaiting Final Approval", 
             'opts': "Artworks", 
             'app_label': opts.app_label,
             'awaiting_approval_count':awaiting_approval_count,
             'awaiting_approval':awaiting_approval
             }
        return render_to_response('admin/artbase/awaiting_approval.html', d, context_instance)
Esempio n. 56
0
    def update_grade_data_from_grading_form_v2(self, request, page_context,
            page_data, grade_data, grading_form, files_data):

        if grade_data is None:
            grade_data = {}
        for k in self.grade_data_attrs:
            if k == "grade_percent":
                grade_data[k] = grading_form.cleaned_percent()
            else:
                grade_data[k] = grading_form.cleaned_data[k]

        if grading_form.cleaned_data["notify"] and page_context.flow_session:
            from course.utils import LanguageOverride
            with LanguageOverride(page_context.course):
                from relate.utils import render_email_template
                from course.utils import will_use_masked_profile_for_email
                staff_email = [page_context.course.notify_email, request.user.email]
                message = render_email_template("course/grade-notify.txt", {
                    "page_title": self.title(page_context, page_data),
                    "course": page_context.course,
                    "participation": page_context.flow_session.participation,
                    "feedback_text": grade_data["feedback_text"],
                    "flow_session": page_context.flow_session,
                    "review_uri": page_context.page_uri,
                    "use_masked_profile":
                        will_use_masked_profile_for_email(staff_email)
                    })

                from django.core.mail import EmailMessage
                msg = EmailMessage(
                        string_concat("[%(identifier)s:%(flow_id)s] ",
                            _("New notification"))
                        % {'identifier': page_context.course.identifier,
                            'flow_id': page_context.flow_session.flow_id},
                        message,
                        getattr(settings, "GRADER_FEEDBACK_EMAIL_FROM",
                                page_context.course.get_from_email()),
                        [page_context.flow_session.participation.user.email])
                msg.bcc = [page_context.course.notify_email]

                if grading_form.cleaned_data["may_reply"]:
                    msg.reply_to = [request.user.email]

                if hasattr(settings, "GRADER_FEEDBACK_EMAIL_FROM"):
                    from relate.utils import get_outbound_mail_connection
                    msg.connection = get_outbound_mail_connection("grader_feedback")
                msg.send()

        if (grading_form.cleaned_data["notes"]
                and grading_form.cleaned_data["notify_instructor"]
                and page_context.flow_session):
            from course.utils import LanguageOverride
            with LanguageOverride(page_context.course):
                from relate.utils import render_email_template
                from course.utils import will_use_masked_profile_for_email
                staff_email = [page_context.course.notify_email, request.user.email]
                use_masked_profile = will_use_masked_profile_for_email(staff_email)
                if use_masked_profile:
                    username = (
                        page_context.flow_session.user.get_masked_profile())
                else:
                    username = (
                        page_context.flow_session.user.get_email_appellation())
                message = render_email_template(
                    "course/grade-internal-notes-notify.txt",
                    {
                        "page_title": self.title(page_context, page_data),
                        "username": username,
                        "course": page_context.course,
                        "participation": page_context.flow_session.participation,
                        "notes_text": grade_data["notes"],
                        "flow_session": page_context.flow_session,
                        "review_uri": page_context.page_uri,
                        "sender": request.user,
                    })

                from django.core.mail import EmailMessage
                msg = EmailMessage(
                        string_concat("[%(identifier)s:%(flow_id)s] ",
                            _("Grading notes from %(ta)s"))
                        % {'identifier': page_context.course.identifier,
                           'flow_id': page_context.flow_session.flow_id,
                           'ta': request.user.get_full_name()
                           },
                        message,
                        getattr(settings, "GRADER_FEEDBACK_EMAIL_FROM",
                                page_context.course.get_from_email()),
                        [page_context.course.notify_email])
                msg.bcc = [request.user.email]
                msg.reply_to = [request.user.email]

                if hasattr(settings, "GRADER_FEEDBACK_EMAIL_FROM"):
                    from relate.utils import get_outbound_mail_connection
                    msg.connection = get_outbound_mail_connection("grader_feedback")
                msg.send()

        return grade_data
Esempio n. 57
0
def register(request, success_url=None,
             form_class=RegistrationForm,
             template_name='registration/registration_form.html',
             extra_context=None):

    if request.method == 'POST': #the full process of registration is done here

        form = form_class(data=request.POST)
        error_found = False

        # remember state and city if form error
        form.fields['city'].initial = request.POST.get('city')
        form.fields['state'].initial = request.POST.get('state')

        # check organization name
        if Organization.objects.filter(short_name__iexact = slugify(request.POST.get('shortname'))):
            error_msg = _(u"Informed organization is already registered. Please choose another name here or login with an existing account")
            form.errors["organization"] = ErrorList([error_msg])
            error_found = True

        # check password
        if not request.POST.get('password1') == request.POST.get('password2'):
            error_msg = _(u"The confirmation of the new password is wrong")
            form.errors["password1"] = ErrorList([error_msg])
            form.errors["password2"] = ErrorList([error_msg])
            error_found = True

        # form is valid and no errors found
        if form.is_valid() and not error_found:

            form.save(request)

            user = User.objects.get(username__iexact=form.cleaned_data['username'])
            profile = user.get_profile()
            person = profile.person

            # active automatic
            org = Organization.objects.filter(organization__isnull=True).filter(person=person)[0]
            org.active = True
            org.save()
            for p in org.person_set.all():
                for rp in p.profile.user.registrationprofile_set.all():
                    activation_key = rp.activation_key.lower() # Normalize before trying anything with it.
                    RegistrationProfile.objects.activate_user(activation_key)

            prof = ProfessionalResponsible()
            prof.organization = org
            prof.person = person
            prof.name = person.name
            prof.save()

            # invoice
            i = Invoice()
            i.organization = org
            i.status = 2
            i.save()
            
            bcc_list = ADMINS_REGISTRATION

            msg = EmailMessage()
            msg.subject = u'Nova assinatura em %s' % URL_HOME
            msg.body = u'Uma nova organizacao se registrou no GestorPSI. Para mais detalhes acessar %s/gcm/\n\n' % URL_APP
            msg.body += u'Organização %s' % org
            msg.to = bcc_list
            msg.send()
            
            request.session['user_aux_id'] = user.id

            # message for client
            user = User.objects.get(id=request.session['user_aux_id'])
            msg = EmailMessage()
            msg.subject = u"Assinatura GestorPSI.com.br"

            msg.body = u"Olá, bom dia!\n\n"
            msg.body += u"Obrigado por assinar o GestorPsi.\nSua solicitação foi recebida pela nossa equipe. Sua conta está pronta para usar! "
            msg.body += u"Qualquer dúvida que venha ter é possível consultar os links abaixo ou então entrar em contato conosco através do formulário de contato.\n\n"

            msg.body += u"link funcionalidades: %s/funcionalidades/\n" % URL_HOME
            msg.body += u"link como usar: %s/como-usar/\n" % URL_HOME
            msg.body += u"link manual: %s/media/manual.pdf\n" % URL_DEMO
            msg.body += u"link contato: %s/contato/\n\n" % URL_HOME
            msg.body += u"Instruções no YouTube: https://www.youtube.com/channel/UC03EiqIuX72q-fi0MfWK8WA\n\n"

            msg.body += u"O periodo de teste inicia em %s e termina em %s.\n" % ( i.start_date.strftime("%d/%m/%Y"), i.end_date.strftime("%d/%m/%Y") )
            msg.body += u"Antes do término do período de teste você deve optar por uma forma de pagamento aqui: %s/organization/signature/\n\n" % URL_APP

            msg.body += u"IMPORTANTE: As informações inseridas no sistema podem ser editadas mas não apagadas. Por isso, se for necessário fazer testes com informações fictícias para entender como o sistema funciona, utilize a nossa versão de demonstração: http://demo.gestorpsi.com.br\n\n"

            msg.body += u"Endereço do GestorPSI: %s\n" % URL_APP
            msg.body += u"Usuário/Login  %s\n" % request.POST.get('username')
            msg.body += u"Senha  %s\n\n" % request.POST.get('password1')

            msg.body += u"%s" % SIGNATURE

            msg.to = [ user.email, ]
            msg.bcc =  bcc_list
            msg.send()
            
            return HttpResponseRedirect(success_url or reverse('registration-complete'))

    # mount form, new register
    else:
        form = form_class()
    
    # WHY THIS CODE ???
    if extra_context is None:
        extra_context = {}

    context = RequestContext(request)

    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(
                template_name,
                { 'form': form },
                context_instance=RequestContext(request)
            )