Exemple #1
0
def send_email(template, recipients=[], cc=[], bcc=[], params={}):
    import turbomail

    def replace(field, params):
        for key, value in params.iteritems():
            field = field.replace(u'${%s}' % key, unicode(value))
        return field

    template = os.path.join(config.get('mail.templates', ''), template + '.txt')
    if not os.path.exists(template):
        raise ValueError('Template %s does not exist' % template)

    file = open(template, 'r')
    subject = replace(unicode(file.readline().strip(), 'UTF-8'), params)
    content = replace(unicode(file.read(), 'UTF-8'), params)
    file.close()

    sender = list(config.get('mail.sender'))
    if isinstance(recipients, (str, unicode)):
        recipients = [recipients]
    elif not isinstance(recipients, list):
        recipients = list(recipients)
    if not isinstance(cc, list):
        cc = list(cc)
    if not isinstance(bcc, list):
        bcc = list(bcc)
    
    message = turbomail.Message(subject=subject, sender=sender,
        recipient=recipients, cc=cc, bcc=bcc)
    message.plain = content

    turbomail.enqueue(message)
 def send_email(self, to_addr, from_addr, subject, body):
     '''
         Sends an email.
         
         @param to_addr: address to which mail is sent
         @param from_adr: address from which mail is sent
         @param subject: subject of the mail
         @param body: text body of the mail
     '''
     
     # Using turbomail if it exists, 'dumb' method otherwise
     if turbomail and config.get('mail.on'):
         msg = turbomail.Message(from_addr, to_addr, subject)
         msg.plain = body
         turbomail.enqueue(msg)
     else:
         msg = MIMEText (body)
         msg['Subject'] = subject
         msg['From'] = from_addr
         msg['To'] = to_addr
     
         smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
         if self.smtp_username:
             smtp.login(self.smtp_username, self.smtp_pw)
         smtp.sendmail(from_addr, to_addr, msg.as_string())
         smtp.quit()
def upgrade_deal(deal_id, stage, pipeline_id=1, user_email=assignee_email, value=None):
    try:
        stage_id = 15 #_get_stage(name=stage, pipeline_id=pipeline_id)
        data = {
            "stage_id": stage_id
        }
        if stage == "Paying Customer": data['status'] = 'won'
        if value: data['value'] = value
        _api_call("deals/%s" % deal_id, "PUT", data)
        
        if stage == "Paying Customer":
            deal = _api_call("deals/%s" % deal_id)["data"] 
            user_id = _get_user(email=user_email)

            date = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
            time = "10:00"
            _create_activity(subject="Send thank you email for upgrade", type="email", due_date=date, due_time=time, deal_id=deal_id, person_id=deal["person_id"]["value"], org_id=deal["org_id"]["value"], user_id=user_id)
    except Exception, err:
        message = turbomail.Message("*****@*****.**", "*****@*****.**", 'Upgrade Deal')
        message.plain = json.dumps({
            "pipedrive_data": {
                "deal_id": deal_id,
                "pipeline_id": pipeline_id,
                "stage": stage
            },
            "error": str(err)
        })
        try: turbomail.enqueue(message)
        except: pass
Exemple #4
0
def send_email(to_addr, sender, subject, body, rich=None):
    # Using turbomail if it exists, 'dumb' method otherwise
    if turbomail and config.get('mail.on'):
        msg = turbomail.Message(sender, to_addr, subject,  encoding='utf-8')
        msg.plain = body
        if rich:
            msg.rich = rich
        turbomail.enqueue(msg)
    # Using tgext.mailer pluggable if it exists, 'dumb' method otherwise
    elif message:
        mailer = get_mailer(request)
        message_to_send = message(
            subject=subject,
            sender=sender,
            recipients=[to_addr],
            body=body,
            html=rich or None
        )

        if config.get('tm.enabled', False):
            mailer.send(message_to_send)
        else:
            mailer.send_immediately(message_to_send)
    else:
        _plain_send_mail(sender, to_addr, subject, body)
    def openTicket(self, **kwargs):

        main_menu, sub_menu = self.renderMenu('support')
        
        customer = identity.current.user.customer
        user = identity.current.user

        validators = {'department': V.String(not_empty=True),
                      'reply_to':  V.Email(not_empty=True),
                      'subject': V.UnicodeString(not_empty=True),
                      'message': V.UnicodeString(not_empty=True)
                      }
        errors = simpleValidate(validators, kwargs)
        if errors: 
            return apply(self.OpenTicket, [], kwargs)

        # Succeeded in validating, now need to send the message
        address_map = {'support': '*****@*****.**',
                       'billing': '*****@*****.**',
                       'abuse': '*****@*****.**'}

        to_address = address_map.get(kwargs['department'], '*****@*****.**')
        message = turbomail.Message(kwargs['reply_to'], to_address, kwargs['subject'])
        message.encoding = 'utf-8'
        message.replyto = kwargs['reply_to']
        message.plain = kwargs['message']
        message.rich = unicode(kwargs['message'])
        message.headers = {'x-panopta-customer': str(customer.id)}
        turbomail.enqueue(message)

        return dict(main_menu = main_menu,
                    reply_to = kwargs['reply_to'])
Exemple #6
0
def send_email(to_addr, from_addr, subject, body):
    # Using turbomail if it exists, 'dumb' method otherwise
    if turbomail and config.get('mail.on'):
        msg = turbomail.Message(from_addr, to_addr, subject)
        msg.plain = body
        turbomail.enqueue(msg)
    else:
        _plain_send_mail(from_addr, to_addr, subject, body)
 def test_message_enqueue(self):
     config = {'mail.on': True}
     fake_setuptools =  {'immediate': ImmediateManager,
                         'debug': DebugTransportFactory}
     interface.start(config, extra_classes=fake_setuptools)
     
     message = Message('*****@*****.**', '*****@*****.**', 'Test')
     message.plain = 'Hello world!'
     turbomail.enqueue(message)
 def test_can_send_pregenerated_messages_with_dict(self):
     config = {'mail.on': True}
     fake_setuptools =  {'immediate': ImmediateManager,
                         'debug': DebugTransportFactory}
     interface.start(config, extra_classes=fake_setuptools)
     
     msg_info = dict(sender='*****@*****.**', recipients='*****@*****.**',
                     message=rfc822_msg)
     turbomail.enqueue(msg_info)
def send_email(to_addr, sender, subject, body, rich=None):
    # Using turbomail if it exists, 'dumb' method otherwise
    if turbomail and config.get('mail.on'):
        msg = turbomail.Message(sender, to_addr, subject,  encoding='utf-8')
        msg.plain = body
        if rich:
            msg.rich = rich
        turbomail.enqueue(msg)
    else:
        _plain_send_mail(sender, to_addr, subject, body)
Exemple #10
0
def send_mail(sender, to, subject, body):
    from turbomail import MailNotEnabledException
    if to in config.get('exclude_mail').split():
        return
    message = turbomail.Message(sender, to, subject)
    message.plain = body
    try:
        log.debug("Sending mail: %r" % message.plain)
        turbomail.enqueue(message)
    except MailNotEnabledException, e:
        log.warning(str(e))
Exemple #11
0
def send_mail(to_addr, subject, text, from_addr=None):
    if from_addr is None:
        from_addr = config.get('accounts_email')
    message = turbomail.Message(from_addr, to_addr, subject)
    message.plain = text
    if config.get('mail.on', False):
        turbomail.enqueue(message)
    else:
        log.debug('Would have sent: %(subject)s' %
                  {'subject': to_bytes(subject)})
        log.debug('To: %(recipients)s' % {'recipients': to_bytes(to_addr)})
        log.debug('From: %(sender)s' % {'sender': to_bytes(from_addr)})
Exemple #12
0
def send_mail(to_addr, subject, text, from_addr=None):
    if from_addr is None:
        from_addr = config.get('accounts_email')
    message = turbomail.Message(from_addr, to_addr, subject)
    message.plain = text
    if config.get('mail.on', False):
        turbomail.enqueue(message)
    else:
        log.debug('Would have sent: %(subject)s' % {
            'subject': to_bytes(subject)})
        log.debug('To: %(recipients)s' % {
            'recipients': to_bytes(to_addr)})
        log.debug('From: %(sender)s' % {
            'sender': to_bytes(from_addr)})
Exemple #13
0
def send_mail(sender, to, subject, body, headers=None):
    from turbomail import MailNotEnabledException
    if to in config.get('exclude_mail').split():
        return
    if '@' not in to:
        to = '%s@%s' % (to, config.get('default_email_domain'))
    message = turbomail.Message(sender, to, subject)
    message.plain = body
    if headers:
        message.headers = headers
    try:
        log.debug("Sending mail: %r" % message.plain)
        turbomail.enqueue(message)
    except MailNotEnabledException, e:
        log.warning(str(e))
Exemple #14
0
def send_mail(sender, to, subject, body, headers=None):
    from turbomail import MailNotEnabledException
    if to in config.get('exclude_mail').split():
        return
    if '@' not in to:
        to = '%s@%s' % (to, config.get('default_email_domain'))
    message = turbomail.Message(sender, to, subject)
    message.plain = body
    if headers:
        message.headers = headers
    try:
        log.debug("Sending mail: %r" % message.plain)
        turbomail.enqueue(message)
    except MailNotEnabledException, e:
        log.warning(str(e))
def create_deal(title, organization, stage, name, email, phone=None, owner_email=owner_email, value="0", currency="USD", visible_to="0", pipeline_id=1, user_email=assignee_email, customer=None):
    try:

        custom_fields = {}
        if stage == "Trial Signup" and customer:
            CRM_URL = "%s/customer/%s" % (tgconfig.get("pipedrive.crm_base_url", "https://crm.panopta.com"), customer.id)
            custom_fields["0311d7820939efc3beed50558306d593767def24"] = CRM_URL
            
            CP_URL = "%s/report/manageCustomer?customer_id=%s" % (customer.brand.controlpanel_url if customer.brand else 'https://my.panopta.com', customer.id)
            custom_fields["57de508605ec72b1a46d2b95d5de3a08f034a36f"] = CP_URL            

        owner_id = _get_user(email=owner_email) 
        org_id = _create_organization(name=organization, owner_id=owner_id, visible_to=visible_to, **custom_fields)
        person_id = _create_person(name=name, owner_id=owner_id, org_id=org_id, email=email, phone=phone, visible_to=visible_to)
        stage_id = 12#_get_stage(name=stage, pipeline_id=pipeline_id)
        deal_id = _create_deal(title=title, value=value, currency=currency, person_id=person_id, org_id=org_id, stage_id=stage_id, visible_to=visible_to)

        if stage == "Trial Signup":
            user_id = _get_user(email=user_email)

            date1 = (datetime.now() + timedelta(days=2)).strftime("%Y-%m-%d")
            time1 = "10:00"
            _create_activity(subject="Initial review of account and send intro email", type="email", due_date=date1, due_time=time1, deal_id=deal_id, person_id=person_id, org_id=org_id, user_id=user_id)

            date2 = (datetime.now() + timedelta(days=21)).strftime("%Y-%m-%d")
            time2 = "10:00"
            _create_activity(subject="Pre trial expire review and followup", type="email", due_date=date2, due_time=time2, deal_id=deal_id, person_id=person_id, org_id=org_id, user_id=user_id)
    except Exception, err:
        deal_id = 0
        message = turbomail.Message("*****@*****.**", "*****@*****.**", 'New Deal')
        message.plain = json.dumps({
            "pipedrive_data": {
                "title": title,
                "value": value,
                "currency": currency,
                "person": name,
                "org": organization,
                "stage": stage,
                "visible_to": visible_to
            },
            "error": str(err)
        })
        try: turbomail.enqueue(message)
        except: pass
Exemple #16
0
    def _send_msg(self, msg, subject, recipients, from_addr=None):
        '''Send an email from the packagedb.'''
        if not from_addr:
            from_addr = self.MAILFROM

        if config.get('mail.on', False):
            for person in recipients:
                email = turbomail.Message(from_addr, person,
                        '[pkgdb] %s' % (subject,))
                email.plain = msg
                turbomail.enqueue(email)
        else:
            LOG.debug(_('Would have sent: %(subject)s') % {
                'subject': subject.encode('ascii', 'replace')})
            LOG.debug('To: %s' % recipients)
            LOG.debug('From: %s %s' %
                    (from_addr[0].encode('ascii', 'replace'),
                    from_addr[1].encode('ascii', 'replace')))
            LOG.debug('%s' % msg.encode('ascii', 'replace'))
Exemple #17
0
    def _send_msg(self, msg, subject, recipients, from_addr=None):
        '''Send an email from the packagedb.'''
        if not from_addr:
            from_addr = self.MAILFROM

        if config.get('mail.on', False):
            for person in recipients:
                email = turbomail.Message(from_addr, person,
                                          '[pkgdb] %s' % (subject, ))
                email.plain = msg
                turbomail.enqueue(email)
        else:
            LOG.debug(
                _('Would have sent: %(subject)s') %
                {'subject': subject.encode('ascii', 'replace')})
            LOG.debug('To: %s' % recipients)
            LOG.debug('From: %s %s' % (from_addr[0].encode(
                'ascii', 'replace'), from_addr[1].encode('ascii', 'replace')))
            LOG.debug('%s' % msg.encode('ascii', 'replace'))
    def openTicket(self, **kwargs):
        main_menu, sub_menu = self.renderMenu('support')
        
        validators = {'email':  V.Email(not_empty=True),
                      'subject': V.String(not_empty=True),
                      'message': V.String(not_empty=True),
                      'name': V.String(not_empty=True)
                      }
        errors = simpleValidate(validators, kwargs)
        if errors: 
            return apply(self.submit_ticket, [], kwargs)

        # Succeeded in validating, now need to send the message
        to_address = '*****@*****.**'
        message = turbomail.Message(kwargs['email'], to_address, kwargs['subject'])
        message.replyto = kwargs['email']
        message.plain = kwargs['message']
        turbomail.enqueue(message)

        return dict(main_menu = main_menu,
                    email = kwargs['email'])
Exemple #19
0
    def send_exception_email(self, status, url, data):
        """Send an email with the error info to the admin.

        Uses TurboMail if installed and activated, otherwise tries to send
        email with the smtplib module. The SMTP settings can be configured
        with the following configuration settings:

        error_catcher.smtp_host   - Mail server to connect to
                                    (default 'localhost')
        error_catcher.smtp_user   - User name for SMTP authentication.
                                    If unset no SMTP login is performed.
        error_catcher.smtp_passwd - Password for SMTP authentication
        """

        if not self.sender_email or not self.admin_email:
            log.exception(
                "Configuration error: could not send error" "because sender and/or admin email address is not set."
            )
            raise RuntimeError

        subject = "%d ERROR on the Server" % status
        text = ERROR_MAIL_TMPL % dict(url=url, data=data)

        if has_turbomail and config.get("mail.on"):
            msg = turbomail.Message(self.sender_email, self.admin_email, subject)
            msg.plain = text
            turbomail.enqueue(msg)
        else:
            from email.MIMEMultipart import MIMEMultipart
            from email.MIMEText import MIMEText
            from email.Utils import formatdate

            msg = MIMEMultipart()
            msg["From"] = self.sender_email
            msg["To"] = self.admin_email
            msg["Date"] = formatdate(localtime=True)
            msg["Subject"] = subject
            msg.attach(MIMEText(text))
            self._send_email_smtp(self.sender_email, self.admin_email, msg.as_string())
Exemple #20
0
 def send_email(self, to_addr, from_addr, username, design, interaction, bugs, ideas):
     '''
         Sends an email containing the information given as arguments.
         
         @param to_addr E-Mail receiver
         @param from_addr E-Mail sender
         @param username The name of the user who submitted the feedback
         @param design The users opinion about design
         @param interaction The users opinion about interaction
         @param bugs The users experiences with bugs
         @param ideas The users own ideas
     '''
     print to_addr, from_addr
     
     body = "<feedback username='******'>\n\t<design>" + design + "</design>\n" + "\t<interaction>" + interaction + "</interaction>\n" + "\t<bugs>" + bugs + "</bugs>\n\t" + "<ideas>" + ideas + "</ideas>\n</feedback>"
     # Using turbomail if it exists, 'dumb' method otherwise
     if turbomail and config.get('mail.on'):
         msg = turbomail.Message(from_addr, to_addr, username)
         msg.plain = body
         turbomail.enqueue(msg)
     else:
         msg = MIMEText (body)
         msg['Subject'] = username
         msg['From'] = from_addr
         msg['To'] = to_addr
         
         smtp_server = config.get('feedback.mail.smtp_server', 'localhost')
         smtp_port = config.get('feedback.mail.smtp_port', 25)
         
         smtp_username = config.get('feedback.mail.smtp_server.username')
         smtp_pw = config.get('feedback.mail.smtp_server.password')
         
         print smtp_username, smtp_pw
     
         smtp = smtplib.SMTP(smtp_server, smtp_port)
         if smtp_username:
             smtp.login(smtp_username, smtp_pw)
         smtp.sendmail(from_addr, to_addr, msg.as_string())
         smtp.quit()
Exemple #21
0
def send_email(to_addr, subject, body):
    '''
        Send an email.
        
        @param to_addr: the recipient
        @param subject: the subject
        @param body: the message body (text or html)   
    '''
    
    from_addr = config.get('registration.mail.admin_email')
    try:
        # Using turbomail if it exists, 'dumb' method otherwise
        if turbomail and config.get('mail.on'):
            msg = turbomail.Message(from_addr, to_addr, subject)
            msg.plain = body
            turbomail.enqueue(msg)
        else:        
            smtp_server = config.get('registration.mail.smtp_server', 'localhost')
            smtp_port = config.get('registration.mail.smtp_server_port', 25)
            smtp_username = config.get('registration.mail.smtp_server.username', None)
            smtp_pw = config.get('registration.mail.smtp_server.password', None)
            
            msg = MIMEText (body)
            msg.set_charset('utf-8')
            msg['Subject'] = subject
            msg['From'] = from_addr
            msg['To'] = to_addr
        
            smtp = smtplib.SMTP(smtp_server, smtp_port)
            if smtp_username:
                smtp.login(smtp_username, smtp_pw)
            smtp.sendmail(from_addr, to_addr, msg.as_string())
            smtp.quit()
            print "send email to %s" % to_addr
    except:
        print "Could not send email to %s (%s)" % (to_addr, subject)
    def ResetPassword(self, **kwargs):

        host = cherrypy.request.headers.get("X-Forwarded-Host")
        brand, brand_logo_url, brand_textkey, brand_name, brand_favicon_url = self.getBrandSpecificUI(host) 

        # Check reset password link
        if 'verify_code' in kwargs:
            try:
                email_address = kwargs['email_address'].strip().replace(" ", "+")
                verify_code = kwargs['verify_code'].strip()
                user = masterdb.User.select(AND(masterdb.User.q.email_address == email_address,
                                                 masterdb.User.q.deleted == 0))[0]
                if verify_code != md5.new("%s:%s" % (email_address, user.forgotpassword_code)).hexdigest() or \
                  (datetime.now() - user.forgotpassword_timestamp) > timedelta(days=turbogears.config.get('password_reset_link_valid_days', 2)):
                    raise

                fields = [PasswordElement('new_password', 'new_password', '', label=_("New Password"), help='', args=kwargs),
                    PasswordElement('confirm_new_password', 'confirm_new_password', '', label=_("Confirm New Password"), help='', args=kwargs)]

                return dict(fields = fields,
                            email_address = email_address,
                            verify_code = verify_code ,
                            brand = brand,
                            brand_logo_url = brand_logo_url,
                            brand_textkey = brand_textkey,
                            brand_name = brand_name,
                            brand_favicon_url = brand_favicon_url
                            )                  
            except:
                if brand and brand.controlpanel_url:
                    redirect("%s/login?reset=0" % brand.controlpanel_url)
                else:
                    redirect("/login?reset=0")

        # Validate email_address
        validators = {'email_address': V.Email(not_empty=True)}
        errors = simpleValidate(validators, kwargs)
        if errors:
            return apply(self.ForgotPassword, [], kwargs)

        email_address = kwargs['email_address']

        # Check if the email exist in database
        users = masterdb.User.select(AND(masterdb.User.q.email_address == email_address,
                                         masterdb.User.q.deleted == 0))
        if not users.count():
            # We tell them an email was sent regardless, so that someone trying to attack can't determine which addresses are tied to valid email addresses.
            if brand and brand.controlpanel_url:
                redirect("%s/login?reset=1" % brand.controlpanel_url)
            else:
                redirect("/login?reset=1")

        valid_chars = string.ascii_letters + string.digits
        valid_chars = valid_chars.replace('1', '')
        valid_chars = valid_chars.replace('l', '')
        valid_chars = valid_chars.replace('0', '')
        valid_chars = valid_chars.replace('O', '')
        valid_chars = valid_chars.replace('o', '')

        # Add the forgotpassword_code to matched users and send the reset email to them
        for user in users:
            forgotpassword_code = ''.join([choice(valid_chars) for i in range(12)])
            verify_code = md5.new("%s:%s" % (user.email_address, forgotpassword_code)).hexdigest()
            password_reset_link = "%sResetPassword?email_address=%s&verify_code=%s" % (user.customer.getControlPanelURL(include_protocol=True), user.email_address, verify_code)
            user.forgotpassword_code = forgotpassword_code
            user.forgotpassword_timestamp = datetime.now()

            message = turbomail.Message(('%s Support' % brand_name, brand and brand.support_email_address or '*****@*****.**'), email_address, '%s password reset' % brand_name)
            message.encoding = 'utf-8'
            message.bcc = '*****@*****.**'
            message.plain = _("""We have received a password reset request for your %(brand_name)s service. Please use the link below to reset your password for the %(email_address)s account. If you did not request a password reset, please ignore this message and no changes will be made to your account.

%(password_reset_link)s

Sincerely,
%(brand_name)s Support
%(support_address)s
""" % {'password_reset_link': password_reset_link,
       'email_address': user.email_address,
       'brand_name': brand_name,
       'support_address': brand and brand.support_email_address or '*****@*****.**',
       })
            turbomail.enqueue(message)
        if brand and brand.controlpanel_url:
            redirect("%s/login?reset=1" % brand.controlpanel_url)
        else:
            redirect("/login?reset=1")
Exemple #23
0
def send_mail(to_addr, subject, text, from_addr=None):
    if from_addr is None:
        from_addr = config.get('accounts_email')
    message = turbomail.Message(from_addr, to_addr, subject)
    message.plain = text
    turbomail.enqueue(message)
Exemple #24
0
def send_mail(to_addr, subject, text, from_addr=None):
    if from_addr is None:
        from_addr = config.get('accounts_email')
    message = turbomail.Message(from_addr, to_addr, subject)
    message.plain = text
    turbomail.enqueue(message)
def order_trial(name, email_address, company_name, plan):
    for blacklist_domain in turbogears.config.get("blacklisted_signup_domains", []):
        if email_address.endswith(blacklist_domain):
            logging.info("wtf chinese hackers, leave us alone: %s" % email_address)
            return None

    # Determine where they're coming from to determine their timezone
    timezone = "US/Central"
    try:
        ipaddr = cherrypy.request.headers.get("X-Forwarded-For")
        gir = gi.record_by_addr(ipaddr)
        country = gir["country_code"]
        region = gir["region"]
        search = country
        if country in ("US", "CA"):
            search = "%s-%s" % (country, region)
        if models.timezones.country_to_timezone.has_key(search):
            timezone = models.timezones.country_to_timezone[search]
    except:
        timezone = "US/Central"

    # Validation

    errors = []

    # Validate name
    if len(name.strip().split()) <= 1:
        errors.append((_("Please enter your first and last name."), "name"))

    # Validate email_addres
    taken_user = masterdb.User.selectBy(email_address=email_address)
    if taken_user.count() != 0 and email_address not in turbogears.config.get("whitelist_orderform_addresses", []):
        errors.append(
            (
                _(
                    "There is already a user created with this email address. You are only eligible for one free trial - please login to your account to convert to a full paying plan."
                ),
                "email_address",
            )
        )

    # Validate company_name
    if not company_name:
        errors.append((_("Please enter your company name."), "company_name"))

    # Validate plan
    if not plan:
        errors.append((_("You should specify the plan."), "plan"))

    if errors:
        raise TrialSignupException(errors)

    # Passed validation, save the data and send a validation code
    valid_chars = (
        (string.ascii_letters + string.digits)
        .replace("1", "")
        .replace("l", "")
        .replace("0", "")
        .replace("O", "")
        .replace("o", "")
    )
    validation_code = "".join([choice(valid_chars) for i in range(1, 8)])

    # Create pending order
    pending_order = masterdb.PendingOrder(
        name=name,
        email_address=email_address,
        company_name=company_name,
        plan=plan,
        username=email_address,
        timezone=timezone,
        validation_code=validation_code,
        password="",
        promotion=None,
        discount=None,
        phone="",
    )

    # Send out the email with the validation code

    email_template = "TrialValidation"
    template_file = join(EMAIL_TEMPLATE_DIR, "%s.html" % email_template)
    template_str = Template(open(template_file, "r").read())
    context = {"name": name.split()[0], "validation_code": validation_code}
    template = unicode(template_str.safe_substitute(context))
    subject = "Complete your Panopta sign up"
    support_email = ("Panopta Support", "*****@*****.**")

    message = turbomail.Message(support_email, email_address, subject)
    message.encoding = "utf-8"
    message.bcc = "*****@*****.**"
    message.rich = template
    turbomail.enqueue(message)

    # Send logging email internally for order tracking
    try:
        message = turbomail.Message(
            "*****@*****.**",
            ["*****@*****.**", "*****@*****.**"],
            "New trial signup - %s" % email_address,
        )
        message.plain = unicode(
            """
            Name: %s
            Company: %s
            Email Address: %s
            Timezone: %s"""
            % (name, company_name, email_address, timezone)
        )
        turbomail.enqueue(message)
    except:
        pass
def signup_trial(name, password, email, phone="", company_name="", source="", promo_code=None, skip_validate=False):
    errors = []

    # Determine where they're coming from to determine their timezone
    timezone = "US/Central"
    try:
        ipaddr = cherrypy.request.headers.get("X-Forwarded-For")
        gir = gi.record_by_addr(ipaddr)
        country = gir["country_code"]
        region = gir["region"]
        search = country
        if country in ("US", "CA"):
            search = "%s-%s" % (country, region)
        if models.timezones.country_to_timezone.has_key(search):
            timezone = models.timezones.country_to_timezone[search]
    except:
        timezone = "US/Central"

    # Validate name
    if len(name.strip().split()) <= 1:
        errors.append((_("Please enter your first and last name."), "name"))

    # Validate the promo code
    promotion = None
    if promo_code:
        promo = masterdb.Promotion.select(masterdb.Promotion.q.promo_code == str(promo_code))
        if not promo.count():
            pass
        elif promo[0].start_datetime > datetime.now():
            errors.append((_("Invalid promotion code."), "promo_code"))
        elif promo[0].end_datetime and promo[0].end_datetime < datetime.now():
            errors.append((_("Sorry, this promotion has expired."), "promo_code"))
        else:
            promotion = promo[0]

    taken_user = masterdb.User.selectBy(email_address=email)
    if taken_user.count() != 0 and email not in turbogears.config.get("whitelist_orderform_addresses", []):
        errors.append(
            (
                _(
                    "There is already a user created with this email address.  You are only eligible for one free trial - please login to your account to convert to a full paying plan."
                ),
                "email_address",
            )
        )

    if errors:
        raise TrialSignupException(errors)

    # Passed validation, save the data and send a validation code
    valid_chars = string.ascii_letters + string.digits
    valid_chars = valid_chars.replace("1", "")
    valid_chars = valid_chars.replace("l", "")
    valid_chars = valid_chars.replace("0", "")
    valid_chars = valid_chars.replace("O", "")
    valid_chars = valid_chars.replace("o", "")
    validation_code = "".join([choice(valid_chars) for i in range(1, 8)])
    discount = None

    if promotion:
        discount = promotion.discount

    for blacklist_domain in turbogears.config.get("blacklisted_signup_domains", []):
        if email.endswith(blacklist_domain):
            logging.info("wtf chinese hackers, leave us alone: %s" % email)
            return None

    pending_order = masterdb.PendingOrder(
        name=name,
        username=email,
        password=password,
        email_address=email,
        timezone=timezone,
        validation_code=validation_code,
        promotion=promotion,
        discount=discount,
        source=source,
        phone=phone,
        company_name=company_name,
    )

    email_template = "validation"
    subject = "Panopta account verification"
    support_email = ("Panopta Support", "*****@*****.**")
    brand = None
    if promotion:
        brand = promotion.brand

    if brand:
        email_template = "validation-" + brand.textkey.replace("partner.", "")
        subject = "%s account verification" % brand.name
        support_email = ("%s Support" % brand.name, brand.support_email_address)

    template_html_file = join(EMAIL_TEMPLATE_DIR, "%s.html" % email_template)
    template_text_file = join(EMAIL_TEMPLATE_DIR, "%s.txt" % email_template)
    if not template_html_file or not template_text_file:
        raise Exception("no brand templates '%s' and '%s'" % (template_html_file, template_text_file))

    template_html = Template(open(template_html_file, "r").read())
    template_text = Template(open(template_text_file, "r").read())

    tparams = {"validation_code": validation_code, "email_address": email}
    if brand:
        tparams.update(
            {
                "support_email": brand.support_email_address,
                "controlpanel": brand.base_domain,
                "logo_url": brand.logo_secure_url,
            }
        )
    template_html = unicode(template_html.safe_substitute(tparams))
    template_text = unicode(template_text.safe_substitute(tparams))

    if not skip_validate:
        # Send out the email with the validation code
        message = turbomail.Message(support_email, email, subject)
        message.encoding = "utf-8"
        message.bcc = "*****@*****.**"
        message.rich = template_html
        message.plain = template_text
        turbomail.enqueue(message)

    # Send logging email internally for order tracking
    try:
        message = turbomail.Message(
            "*****@*****.**", ["*****@*****.**", "*****@*****.**"], "New trial signup - %s" % email
        )
        #    message.encoding = "utf-8"
        message.plain = unicode(
            """
Brand: %s
Name: %s
Company: %s
Email Address: %s
Phone Number: %s
Timezone: %s
Source: %s
Promotion: %s"""
            % (
                brand and brand.name or "Panopta",
                name,
                company_name,
                email,
                phone,
                timezone,
                source,
                promotion and promotion.name or "None",
            )
        )
        turbomail.enqueue(message)
    except:
        pass

    return pending_order