예제 #1
0
def _send_activation_email(user, project, database, base_url):
    """Send an email to the user just after we have defined their diagnosis."""
    advice_modules = {a.advice_id: a for a in _advice_modules(database)}
    advices = [a for a in project.advices if a.advice_id in advice_modules]
    if not advices:
        logging.error(  # pragma: no-cover
            'Weird: the advices that just got created do not exist in DB.'
        )  # pragma: no-cover
        return  # pragma: no-cover
    data = {
        'baseUrl':
        base_url,
        'projectId':
        project.project_id,
        'firstName':
        user.profile.name,
        'ofProjectTitle':
        french.maybe_contract_prefix(
            'de ', "d'",
            french.lower_first_letter(
                _get_job_name(project.target_job, user.profile.gender))),
        'advices': [{
            'adviceId': a.advice_id,
            'title': advice_modules[a.advice_id].title
        } for a in advices],
    }
    response = mail.send_template(
        # https://app.mailjet.com/template/168827/build
        '168827',
        user.profile,
        data,
        dry_run=not _EMAIL_ACTIVATION_ENABLED)
    if response.status_code != 200:
        logging.warning('Error while sending diagnostic email: %s\n%s',
                        response.status_code, response.text)
예제 #2
0
    def send_reset_password_token(self, email):
        """Sends an email to user with a reset token so that they can reset their password."""
        user_dict = self._db.user.find_one({'profile.email': email})
        if not user_dict:
            flask.abort(403, "Nous n'avons pas d'utilisateur avec cet email : %s" % email)
        user_auth_dict = self._db.user_auth.find_one({'_id': user_dict['_id']})
        if not user_auth_dict or not user_auth_dict.get('hashedPassword'):
            flask.abort(
                403, 'Utilisez Facebook ou Google pour vous connecter, comme la première fois.')

        hashed_old_password = user_auth_dict.get('hashedPassword')
        auth_token = _timestamped_hash(
            int(time.time()), email + str(user_dict['_id']) + hashed_old_password)

        user_profile = user_pb2.UserProfile()
        proto.parse_from_mongo(user_dict.get('profile'), user_profile)

        reset_link = parse.urljoin(flask.request.url, '/?' + parse.urlencode({
            'email': email,
            'resetToken': auth_token}))
        template_vars = {
            'resetLink': reset_link,
            'firstName': user_profile.name,
        }
        result = mail.send_template(
            '71254', user_profile, template_vars, monitoring_category='reset_password')
        if result.status_code != 200:
            logging.error('Failed to send an email with MailJet:\n %s', result.text)
            flask.abort(result.status_code)
예제 #3
0
def send_email_to_user(user, base_url, now):
    """Sends an email to the user to measure the Net Promoter Score."""
    # Renew actions for the day if needed.
    mail_result = mail.send_template(
        _MAILJET_TEMPLATE_ID,
        user.profile,
        {
            'baseUrl': base_url,
            'firstName': user.profile.name,
            'emailInUrl': parse.quote(user.profile.email),
            'dateInUrl': parse.quote(now.strftime('%Y-%m-%d')),
        },
        dry_run=DRY_RUN,
    )
    mail_result.raise_for_status()
    return True
예제 #4
0
def main():
    """Send an email to a user to tell them to focus on the network."""
    campaign_id = 'focus-network'
    template_id = '205970'
    email_count = 0
    selected_users = _DB.user.find({
        'registeredAt': {
            '$gt': '2017-04-01',
            '$lt': '2017-07-10',
        },
        'projects.networkEstimate': 1,
    })
    for user_dict in selected_users:
        user_id = user_dict.pop('_id')
        user = user_pb2.User()
        proto.parse_from_mongo(user_dict, user)

        if any(email.campaign_id == campaign_id for email in user.emails_sent):
            # We already sent the email to that person.
            continue

        template_vars = network_vars(user)
        if not template_vars:
            continue

        req = mail.send_template(template_id, user.profile, template_vars)
        print('Email sent to %s' % user.profile.email)

        if req.status_code != 200:
            logging.warning('Error while sending an email: %d',
                            req.status_code)
            continue

        email_sent = user.emails_sent.add()
        email_sent.sent_at.GetCurrentTime()
        email_sent.mailjet_template = template_id
        email_sent.campaign_id = campaign_id
        _DB.user.update_one({'_id': user_id}, {
            '$set': {
                'emailsSent':
                json_format.MessageToDict(user).get('emailsSent', []),
            }
        })
        email_count += 1

    return email_count
예제 #5
0
def send_email_to_user(user, base_url, weekday, database):
    """Sends an email to the user with their current actions."""
    if not user.projects:
        return False
    # Renew actions for the day if needed.
    advice = advisor.select_advice_for_email(user, weekday, database)
    if not advice:
        logging.warning('No useful advice to send for: %s', user.profile.email)
        return False

    advice_module = advisor.get_advice_module(advice.advice_id, database)
    if not advice_module:
        logging.warning('Module for advice "%s" not found in DB.', advice.advice_id)
        return False

    tips = advisor.select_tips_for_email(user, user.projects[0], advice, database)
    if not tips:
        logging.warning('No tips for advice "%s".', advice.advice_id)

    advice_modules = [
        advisor.get_advice_module(a.advice_id, database)
        for a in user.projects[0].advices]

    mail_result = mail.send_template(
        _MAILJET_ADVICE_TEMPLATE_ID,
        user.profile,
        dict({
            'advices': [
                {'adviceId': a.advice_id, 'title': a.title}
                for a in advice_modules if a],
            'baseUrl': base_url,
            'fact': random.choice(advice_module.email_facts),
            'firstName': user.profile.name,
            'frequency': frequency(user.profile.email_days),
            'nextday': see_you_day(user.profile.email_days, weekday),
            'numStars': advice.num_stars,
            'projectId': user.projects[0].project_id,
            'subject': advice_module.email_subject,
            'suggestionSentence': advice_module.email_suggestion_sentence,
            'title': advice_module.email_title,
        }, **_flatten([json_format.MessageToDict(t) for t in tips], prefix='tips')),
        dry_run=DRY_RUN,
        monitoring_category='daily_notification',
    )
    mail_result.raise_for_status()
    return True
예제 #6
0
def blast_campaign(campaign_id,
                   action,
                   registered_from,
                   registered_to,
                   dry_run_email='',
                   user_hash=''):
    """Send a campaign of personalized emails."""
    if action == 'send' and auth.SECRET_SALT == auth.FAKE_SECRET_SALT:
        raise ValueError('Set the prod SECRET_SALT env var before continuing.')
    campaign = _CAMPAIGNS[campaign_id]
    template_id = campaign.mailjet_template
    selected_users = _DB.user.find(
        dict(
            campaign.mongo_filters, **{
                'profile.email': {
                    '$not': re.compile(r'@example.com$')
                },
                'registeredAt': {
                    '$gt': registered_from,
                    '$lt': registered_to,
                }
            }))
    email_count = 0
    email_errors = 0

    for user_dict in selected_users:
        user_id = user_dict.pop('_id')
        user = user_pb2.User()
        proto.parse_from_mongo(user_dict, user)
        user.user_id = str(user_id)

        if user_hash and not user.user_id.startswith(user_hash):
            continue

        if any(email.campaign_id == campaign_id for email in user.emails_sent):
            # We already sent the email to that person.
            continue

        template_vars = campaign.get_vars(user)
        if not template_vars:
            continue

        if action == 'list':
            logging.info('%s %s', user.user_id, user.profile.email)
            continue

        if action == 'dry-run':
            user.profile.email = dry_run_email
        if action in ('dry-run', 'send'):
            res = mail.send_template(template_id,
                                     user.profile,
                                     template_vars,
                                     sender_email=campaign.sender_email,
                                     sender_name=campaign.sender_email)
            logging.info('Email sent to %s', user.profile.email)

        if action == 'dry-run':
            try:
                res.raise_for_status()
            except requests.exceptions.HTTPError:
                raise ValueError(
                    'Could not send email for vars:\n{}'.format(template_vars))
        elif res.status_code != 200:
            logging.warning('Error while sending an email: %d',
                            res.status_code)
            email_errors += 1
            continue

        sent_response = res.json()
        message_id = next(iter(sent_response.get('Sent', [])),
                          {}).get('MessageID', 0)
        if not message_id:
            logging.warning('Impossible to retrieve the sent email ID:\n%s',
                            sent_response)
        if action == 'dry-run':
            return 1

        email_sent = user.emails_sent.add()
        email_sent.sent_at.GetCurrentTime()
        email_sent.sent_at.nanos = 0
        email_sent.mailjet_template = template_id
        email_sent.campaign_id = campaign_id
        email_sent.mailjet_message_id = message_id
        _DB.user.update_one({'_id': user_id}, {
            '$set': {
                'emailsSent':
                json_format.MessageToDict(user).get('emailsSent', []),
            }
        })
        email_count += 1
        if email_count % 100 == 0:
            print('{} emails sent ...'.format(email_count))

    if action == 'send':
        report.notify_slack(
            "Report for 3 month employment-status blast: I've sent {:d} emails (and got {:d} \
            errors).".format(email_count, email_errors))
    return email_count