Example #1
0
def send_mail(rawRecipients, subject, body, one_email=False):
    if rawRecipients and len(rawRecipients) > 0:
        recipients = [] # cleaned list
        for recipient in rawRecipients:
            if 'email' in recipient and 'display_name' in recipient and recipient['email'] is not None and recipient['display_name'] is not None:
                recipients.append(recipient)

        email_info = u'\nSending email to {recipients} with subject "{subject}" with body: {body}' \
            .format(recipients=', '.join([r['display_name'] + ' - ' + r['email'] for r in recipients]), subject=subject,
                    body=body)
        log.info(email_info)
        send_mails = config.get('hdx.orgrequest.sendmails', 'true')
        if 'true' == send_mails:
            if one_email:
                # new_recipients = []
                # for recipient in recipients:
                #     new_recipients.append({'name': recipient['display_name'], 'email': recipient['email']})
                hdx_mailer.mail_recipient(recipients_list=recipients, subject=subject, body=body)
            else:
                for recipient in recipients:
                    hdx_mailer.mail_recipient([recipient], subject, body)
        else:
            log.warn('HDX-CKAN was configured to not send email requests')
    else:
        raise NoRecipientException('The are no recipients for this request. Contact an administrator ')
Example #2
0
def hdx_send_mail_contributor(context, data_dict):
    _check_access('hdx_send_mail_contributor', context, data_dict)

    subject = u'[HDX] {fullname} {topic} for \"[Dataset] {pkg_title}\"'.format(
        fullname=data_dict.get('fullname'), topic=data_dict.get('topic'), pkg_title=data_dict.get('pkg_title'))
    requester_body_html = __create_body_for_contributor(data_dict, False)

    admins_body_html = __create_body_for_contributor(data_dict, True)

    recipients_list = []
    org_members = get_action("hdx_member_list")(context, {'org_id': data_dict.get('pkg_owner_org')})
    if org_members:
        admins = org_members.get('admins')
        for admin in admins:
            context['keep_email'] = True
            user = get_action("user_show")(context, {'id': admin})
            if user.get('email'):
                recipients_list.append({'email': user.get('email'), 'display_name': user.get('display_name')})

    bcc_recipients_list = [{'email': data_dict.get('hdx_email'), 'display_name': 'HDX'}]

    hdx_mailer.mail_recipient(recipients_list=recipients_list, subject=subject, body=admins_body_html,
                              sender_name=data_dict.get('fullname'), sender_email=data_dict.get('email'),
                              bcc_recipients_list=bcc_recipients_list, footer=_FOOTER_CONTACT_CONTRIBUTOR,
                              reply_wanted=True)

    requester_list = [{'email': data_dict.get('email'), 'display_name': data_dict.get('fullname')}]
    hdx_mailer.mail_recipient(recipients_list=requester_list, subject=subject, body=requester_body_html,
                              sender_name=data_dict.get('fullname'), sender_email=data_dict.get('email'),
                              footer=_FOOTER_CONTACT_CONTRIBUTOR)

    return None
Example #3
0
def hdx_send_mail_contributor(context, data_dict):
    subject = u'[HDX] {fullname} {topic} for \"[Dataset] {pkg_title}\"'.format(
        fullname=data_dict.get('fullname'), topic=data_dict.get('topic'), pkg_title=data_dict.get('pkg_title'))
    html = u"""\
            <p>{fullname} sent the following message: </p>
            <p>{msg}</p>
            <p>Dataset: <a href=\"{pkg_url}\">{pkg_title}</a>
        """.format(fullname=data_dict.get('fullname'), msg=data_dict.get('msg'), pkg_url=data_dict.get('pkg_url'),
                   pkg_title=data_dict.get('pkg_title'))

    recipients_list = []
    org_members = get_action("hdx_member_list")(context, {'org_id': data_dict.get('pkg_owner_org')})
    if org_members:
        admins = org_members.get('admins')
        for admin in admins:
            user = get_action("user_show")(context, {'id': admin})
            if user.get('email'):
                recipients_list.append({'email': user.get('email'), 'display_name': user.get('display_name')})
    recipients_list.append({'email': data_dict.get('email'), 'display_name': data_dict.get('fullname')})

    bcc_recipients_list = [{'email': data_dict.get('hdx_email'), 'display_name': 'HDX'}]

    hdx_mailer.mail_recipient(recipients_list=recipients_list, subject=subject, body=html,
                              sender_name=data_dict.get('fullname'), sender_email=data_dict.get('email'),
                              bcc_recipients_list=bcc_recipients_list, footer=_FOOTER_CONTACT_CONTRIBUTOR)

    return None
Example #4
0
def hdx_send_mail_members(context, data_dict):
    subject = u'[HDX] {fullname} sent a group message regarding \"[Dataset] {pkg_title}\"'.format(
        fullname=data_dict.get('fullname'), topic=data_dict.get('topic'), pkg_title=data_dict.get('pkg_title'))
    html = u"""\
            <p>{fullname} sent the following message to {topic} of {pkg_owner_org}: </p>
            <p>{msg}</p>
        """.format(fullname=data_dict.get('fullname'), topic=data_dict.get('topic').lower(),
                   pkg_owner_org=data_dict.get('pkg_owner_org'), msg=data_dict.get('msg'))

    if data_dict.get('source_type') == 'dataset':
        html += u'<p>Dataset: <a href=\"{pkg_url}\">{pkg_title}</a>'.format(pkg_url=data_dict.get('pkg_url'),
                                                                            pkg_title=data_dict.get('pkg_title'))

    recipients_list = []
    org_members = get_action("hdx_member_list")(context, {'org_id': data_dict.get('pkg_owner_org_id')})
    if org_members:
        admins = org_members.get(data_dict.get('topic_key'))
        for admin in admins:
            user = get_action("user_show")(context, {'id': admin})
            if user.get('email'):
                recipients_list.append({'email': user.get('email'), '_display_name': user.get('display_name')})
    recipients_list.append({'email': data_dict.get('email'), 'display_name': data_dict.get('fullname')})

    hdx_mailer.mail_recipient(recipients_list=recipients_list, subject=subject, body=html,
                              sender_name=data_dict.get('fullname'), sender_email=data_dict.get('email'),
                              footer=_FOOTER_GROUP_MESSAGE)

    return None
Example #5
0
def send_validation_email(user, token):
    validate_link = h.url_for(
        controller=
        'ckanext.hdx_users.controllers.mail_validation_controller:ValidationController',
        action='validate',
        token=token['token'])
    link = '{0}{1}'
    subject = "HDX: Complete your registration"
    print 'Validate link: ' + validate_link
    html = """\
            <p>Hello,</p> 
            <br/>
            <p>Thank you for your interest in the <a href="https://data.humdata.org/">Humanitarian Data Exchange (HDX)</a>. Please complete the registration process by clicking the link below.</p>
            <br/>
            <p><a href="{link}">Verify Email</a></p>
            <br/>
            <p>Best wishes,</p>
            <p>The HDX team</p>
        """.format(link=link.format(config['ckan.site_url'], validate_link))

    try:
        hdx_mailer.mail_recipient([{'email': user['email']}], subject, html)
        return True
    except exceptions.Exception, e:
        error_summary = str(e)
        log.error(error_summary)
        return False
Example #6
0
    def invite_friends(self):
        '''
        Step 6: user can invite friends by email to access HDX
        :return:
        '''

        context = {
            'model': model,
            'session': model.Session,
            'auth_user_obj': c.userobj,
            'user': c.user
        }
        try:
            check_access('hdx_basic_user_info', context)
        except NotAuthorized:
            return OnbNotAuth
        try:
            if not c.user:
                return OnbNotAuth
            usr = c.userobj.display_name or c.user
            user_id = c.userobj.id or c.user
            ue_dict = self._get_ue_dict(user_id,
                                        user_model.HDX_ONBOARDING_FRIENDS)
            get_action('user_extra_update')(context, ue_dict)

            subject = u'{fullname} invited you to join HDX!'.format(
                fullname=usr)
            link = config['ckan.site_url'] + '/user/register'
            hdx_link = '<a href="{link}">HDX</a>'.format(link=link)
            # tour_link = '<a href="https://www.youtube.com/watch?v=P8XDNmcQI0o">tour</a>'
            faq_link = '<a href="https://data.humdata.org/faq">reading our FAQ</a>'
            html = u"""\
                <html>
                  <head></head>
                  <body>
                    <p>{fullname} invited you to join the <a href="https://humdata.org">Humanitarian Data Exchange (HDX)</a>, an open platform for sharing humanitarian data. Anyone can access the data on HDX but registered users are able to share data and be part of the HDX community.</p>
                    <p>You can learn more about HDX by {faq_link}.</p>
                    <p>Join {hdx_link}</p>
                  </body>
                </html>
            """.format(fullname=usr, faq_link=faq_link, hdx_link=hdx_link)

            friends = [
                request.params.get('email1'),
                request.params.get('email2'),
                request.params.get('email3')
            ]
            for f in friends:
                if f and configuration.config.get(
                        'hdx.onboarding.send_confirmation_email',
                        'false') == 'true':
                    hdx_mailer.mail_recipient([{
                        'display_name': f,
                        'email': f
                    }], subject, html)

        except Exception, e:
            error_summary = str(e)
            return self.error_message(error_summary)
Example #7
0
def notify_admins(data_dict):
    try:
        if data_dict.get('admins'):
            # for admin in data_dict.get('admins'):
            hdx_mailer.mail_recipient(data_dict.get('admins'), data_dict.get('subject'), data_dict.get('message'))
    except Exception, e:
        log.error("Email server error: can not send email to admin users" + e.message)
        return False
Example #8
0
    def invite_friends(self):
        '''
        Step 6: user can invite friends by email to access HDX
        :return:
        '''

        context = {
            'model': model,
            'session': model.Session,
            'auth_user_obj': c.userobj,
            'user': c.user
        }
        try:
            check_access('hdx_basic_user_info', context)
        except NotAuthorized:
            return OnbNotAuth
        try:
            if not c.user:
                return OnbNotAuth
            # usr = c.userobj.display_name or c.user
            user_id = c.userobj.id or c.user
            ue_dict = self._get_ue_dict(user_id,
                                        user_model.HDX_ONBOARDING_FRIENDS)
            get_action('user_extra_update')(context, ue_dict)

            subject = u'Invitation to join the Humanitarian Data Exchange (HDX)'
            email_data = {
                'user_fullname': c.userobj.fullname,
                'user_email': c.userobj.email,
            }
            cc_recipients_list = [{
                'display_name': c.userobj.fullname,
                'email': c.userobj.email
            }]
            friends = [
                request.params.get('email1'),
                request.params.get('email2'),
                request.params.get('email3')
            ]
            for f in friends:
                if f and configuration.config.get(
                        'hdx.onboarding.send_confirmation_email',
                        'false') == 'true':
                    hdx_mailer.mail_recipient(
                        [{
                            'display_name': f,
                            'email': f
                        }],
                        subject,
                        email_data,
                        cc_recipients_list=cc_recipients_list,
                        snippet='email/content/onboarding_invite_others.html')
        except Exception, e:
            error_summary = str(e)
            return self.error_message(error_summary)
Example #9
0
def _mail_new_membership_request(locale,
                                 admin,
                                 group,
                                 url,
                                 user_obj,
                                 data_dict=None,
                                 admin_list=None):
    try:
        if admin_list:
            subject = user_obj.display_name + u' has asked to join your organisation'
            email_data = {
                'org_name':
                group.display_name,
                'org_membership_url':
                config.get('ckan.site_url') + '/organization/members/' +
                group.name,
                'user_fullname':
                user_obj.display_name,
                'user_email':
                user_obj.email,
                'message':
                data_dict.get('message')
            }
            hdx_mailer.mail_recipient(
                admin_list,
                subject,
                email_data,
                footer=user_obj.email,
                snippet='email/content/join_organization_request.html')

            subject = u'Your request to join organisation ' + group.display_name
            email_data = {
                'org_name': group.display_name,
                'user_fullname': user_obj.display_name,
                'user_email': user_obj.email
            }
            hdx_mailer.mail_recipient(
                [{
                    'display_name': user_obj.display_name,
                    'email': user_obj.email
                }],
                subject,
                email_data,
                footer=user_obj.email,
                snippet=
                'email/content/join_organization_request_confirmation_to_user.html'
            )

    except MailerException, e:
        log.error(e)
Example #10
0
def hdx_send_reset_link(context, data_dict):
    from urlparse import urljoin
    import ckan.lib.mailer as mailer
    import ckan.lib.helpers as h
    import ckanext.hdx_users.controllers.mailer as hdx_mailer

    model = context['model']

    id = data_dict.get('id', None)
    if id:
        user = model.User.get(id)
        context['user_obj'] = user
        if user is None:
            raise NotFound

    mailer.create_reset_key(user)

    subject = mailer.render_jinja2(
        'emails/reset_password_subject.txt',
        {'site_title': config.get('ckan.site_title')})
    # Make sure we only use the first line
    subject = subject.split('\n')[0]

    reset_link = user_fullname = recipient_mail = None
    if user:
        recipient_mail = user.email if user.email else None
        user_fullname = user.fullname or ''
        reset_link = urljoin(
            config.get('ckan.site_url'),
            h.url_for(controller='user',
                      action='perform_reset',
                      id=user.id,
                      key=user.reset_key))

    body = u"""\
                <p>Dear {fullname}, </p>
                <p>You have requested your password on {site_title} to be reset.</p>
                <p>Please click on the following link to confirm this request:</p>
                <p> <a href=\"{reset_link}\">{reset_link}</a></p>
            """.format(fullname=user_fullname,
                       site_title=config.get('ckan.site_title'),
                       reset_link=reset_link)

    if recipient_mail:
        hdx_mailer.mail_recipient([{
            'display_name': user_fullname,
            'email': recipient_mail
        }], subject, body)
Example #11
0
def hdx_send_reset_link(context, data_dict):
    from urlparse import urljoin
    import ckan.lib.helpers as h

    model = context['model']

    user = None
    reset_link = None
    user_fullname = None
    recipient_mail = None

    id = data_dict.get('id', None)
    if id:
        user = model.User.get(id)
        context['user_obj'] = user
        if user is None:
            raise NotFound

    expiration_in_hours = int(config.get('hdx.password.reset_key.expiration_in_hours', 3))
    if user:
        reset_password.create_reset_key(user, expiration_in_hours)

        recipient_mail = user.email if user.email else None
        user_fullname = user.fullname or ''
        reset_link = urljoin(config.get('ckan.site_url'),
                             h.url_for(controller='user', action='perform_reset', id=user.id, key=user.reset_key))

    # body = u"""\
    #             <p>Dear {fullname}, </p>
    #             <p>You have requested your password on {site_title} to be reset.</p>
    #             <p>Please click on the following link to confirm this request:</p>
    #             <p> <a href=\"{reset_link}\">{reset_link}</a></p>
    #         """.format(fullname=user_fullname, site_title=config.get('ckan.site_title'),
    #                    reset_link=reset_link)

    email_data = {
        'user_fullname': user_fullname,
        'user_reset_link': reset_link,
        'expiration_in_hours': expiration_in_hours,
    }
    if recipient_mail:
        subject = u'HDX password reset'
        hdx_mailer.mail_recipient([{'display_name': user_fullname, 'email': recipient_mail}], subject,
                                  email_data, footer=recipient_mail,
                                  snippet='email/content/password_reset.html')
Example #12
0
def hdx_send_mail_members(context, data_dict):
    recipients_list = []
    org_members = get_action("hdx_member_list")(
        context, {
            'org_id': data_dict.get('pkg_owner_org_id')
        })
    if org_members:
        users_list = org_members.get(data_dict.get('topic_key'))
        for _user in users_list:
            # user = get_action("user_show")(context, {'id': admin})
            user_obj = model.User.get(_user)
            if user_obj and user_obj.email:
                recipients_list.append({
                    'email': user_obj.email,
                    'display_name': user_obj.fullname
                })
    # recipients_list.append({'email': data_dict.get('email'), 'display_name': data_dict.get('fullname')})
    users_role = ''
    if data_dict.get('topic_key') == 'all':
        users_role = 'administrator(s), editor(s), and member(s)'
    elif data_dict.get('topic_key') == 'admins':
        users_role = 'administrator(s)]'
    elif data_dict.get('topic_key') == 'editors':
        users_role = 'editor(s)]'
    elif data_dict.get('topic_key') == 'members':
        users_role = 'member(s)]'
    subject = u'HDX group message from ' + data_dict.get('pkg_owner_org')
    email_data = {
        'org_name': data_dict.get('pkg_owner_org'),
        'user_fullname': data_dict.get('fullname'),
        'user_email': data_dict.get('email'),
        'msg': data_dict.get('msg'),
        'users_role': users_role
    }
    hdx_mailer.mail_recipient(recipients_list,
                              subject,
                              email_data,
                              sender_name=data_dict.get('fullname'),
                              sender_email=data_dict.get('email'),
                              footer='*****@*****.**',
                              snippet='email/content/group_message.html')
    return None
Example #13
0
def send_validation_email(user, token):
    # link = '{0}{1}'
    # html = """\
    #         <p>Hello,</p>
    #         <br/>
    #         <p>Thank you for your interest in the <a href="https://data.humdata.org/">Humanitarian Data Exchange (HDX)</a>. Please complete the registration process by clicking the link below.</p>
    #         <br/>
    #         <p><a href="{link}">Verify Email</a></p>
    #         <br/>
    #         <p>Best wishes,</p>
    #         <p>The HDX team</p>
    #     """.format(link=link.format(config['ckan.site_url'], validate_link))
    validation_link = h.url_for(
        controller=
        'ckanext.hdx_users.controllers.mail_validation_controller:ValidationController',
        action='validate',
        token=token['token'])
    link = '{0}{1}'
    subject = "Complete your HDX registration"
    email_data = {
        'validation_link': link.format(config['ckan.site_url'],
                                       validation_link),
    }
    try:
        print validation_link
        hdx_mailer.mail_recipient(
            [{
                'email': user['email']
            }],
            subject,
            email_data,
            footer=user['email'],
            snippet='email/content/onboarding_email_validation.html')
        return True
    except exceptions.Exception, e:
        error_summary = str(e)
        log.error(error_summary)
        return False
Example #14
0
                <html>
                  <head></head>
                  <body>
                    <p>A user sent the following question using the FAQ contact us form.</p>
                    <p>Name: {fullname}</p>
                    <p>Email: {email}</p>
                    <p>Section: {topic}</p>
                    <p>Message: {msg}</p>
                  </body>
                </html>
                """.format(fullname=fullname,
                           email=email,
                           topic=topic,
                           msg=msg)
            hdx_mailer.mail_recipient([{
                'display_name': 'HDX',
                'email': hdx_email
            }], subject, html)

        except exceptions.Exception, e:
            error_summary = e.error or str(e)
            return self.error_message(error_summary)
        return FaqSuccess

    def error_message(self, error_summary):
        return json.dumps({
            'success': False,
            'error': {
                'message': error_summary
            }
        })
Example #15
0
def _mail_process_status(locale,
                         member_user,
                         approve,
                         group_name,
                         capacity,
                         group_id=None):
    try:
        if approve:
            subject = u'Approval of your request to join organisation ' + group_name
            email_data = {
                'user_fullname': member_user.display_name,
                'org_name': group_name,
                'capacity': capacity
            }
            hdx_mailer.mail_recipient(
                [{
                    'display_name': member_user.display_name,
                    'email': member_user.email
                }],
                subject,
                email_data,
                footer=member_user.email,
                snippet='email/content/join_organization_approval_to_user.html'
            )
            admin_list = []
            if group_id:
                for admin in get_organization_admins(group_id):
                    if admin.email != member_user.email:
                        admin_list.append({
                            'display_name': admin.display_name,
                            'email': admin.email
                        })
                subject = u'Join request approved for organisation ' + group_name
                email_data = {
                    'user_fullname': member_user.display_name,
                    'user_email': member_user.email,
                    'org_name': group_name,
                }
                hdx_mailer.mail_recipient(
                    admin_list,
                    subject,
                    email_data,
                    footer=member_user.email,
                    snippet=
                    'email/content/join_organization_approval_to_admins.html')

        else:
            subject = u'Denial of your request to join organisation ' + group_name
            email_data = {
                'user_fullname': member_user.display_name,
                'org_name': group_name,
            }
            hdx_mailer.mail_recipient(
                [{
                    'display_name': member_user.display_name,
                    'email': member_user.email
                }],
                subject,
                email_data,
                footer=member_user.email,
                snippet='email/content/join_organization_reject_to_user.html')
            admin_list = []
            if group_id:
                for admin in get_organization_admins(group_id):
                    admin_list.append({
                        'display_name': admin.display_name,
                        'email': admin.email
                    })
                subject = u'Join request denied for organisation ' + group_name
                email_data = {
                    'user_fullname': member_user.display_name,
                    'user_email': member_user.email,
                    'org_name': group_name,
                }
                hdx_mailer.mail_recipient(
                    admin_list,
                    subject,
                    email_data,
                    footer=member_user.email,
                    snippet=
                    'email/content/join_organization_reject_to_admins.html')

    except MailerException, e:
        log.error(e)
Example #16
0
def hdx_user_invite(context, data_dict):
    '''Invite a new user.

    You must be authorized to create group members.

    :param email: the email of the user to be invited to the group
    :type email: string
    :param group_id: the id or name of the group
    :type group_id: string
    :param role: role of the user in the group. One of ``member``, ``editor``,
        or ``admin``
    :type role: string

    :returns: the newly created user
    :rtype: dictionary
    '''
    import string
    _check_access('user_invite', context, data_dict)

    schema = context.get('schema', core_schema.default_user_invite_schema())
    data, errors = _validate(data_dict, schema, context)
    if errors:
        raise ValidationError(errors)

    model = context['model']
    group = model.Group.get(data['group_id'])
    if not group:
        raise NotFound()

    name = core_create._get_random_username_from_email(data['email'])
    # Choose a password. However it will not be used - the invitee will not be
    # told it - they will need to reset it
    while True:
        password = ''.join(random.SystemRandom().choice(
            string.ascii_lowercase + string.ascii_uppercase + string.digits)
            for _ in range(12))
        # Occasionally it won't meet the constraints, so check
        errors = {}
        logic.validators.user_password_validator(
            'password', {'password': password}, errors, None)
        if not errors:
            break

    data['name'] = name
    data['password'] = password
    data['state'] = core_model.State.PENDING
    user_dict = _get_action('user_create')(context, data)
    user = core_model.User.get(user_dict['id'])
    member_dict = {
        'username': user.id,
        'id': data['group_id'],
        'role': data['role']
    }

    if group.is_organization:
        _get_action('organization_member_create')(context, member_dict)
        group_dict = _get_action('organization_show')(context,
                                                      {'id': data['group_id']})
    else:
        _get_action('group_member_create')(context, member_dict)
        group_dict = _get_action('group_show')(context,
                                               {'id': data['group_id']})
    try:
        expiration_in_hours = int(config.get('hdx.password.invitation_reset_key.expiration_in_hours', 48))
        reset_password.create_reset_key(user, expiration_in_hours=expiration_in_hours)
        subject = u'HDX account creation'
        email_data = {
            'org_name': group_dict.get('display_name'),
            'capacity': data['role'],
            'user_fullname': c.userobj.display_name,
            'expiration_in_hours': expiration_in_hours,
            'user_reset_link': h.url_for(controller='user',
                                         action='perform_reset',
                                         id=user.id,
                                         key=user.reset_key,
                                         qualified=True)
        }
        hdx_mailer.mail_recipient([{'display_name': user.email, 'email': user.email}],
                                  subject, email_data,
                                  snippet='email/content/new_account_confirmation_to_user.html')

        subject = u'New HDX user confirmation'
        email_data = {
            'org_name': group_dict.get('display_name'),
            'capacity': data['role'],
            'user_username': user.name,
            'user_email': user.email,
        }
        admin_list = get_organization_admins(group_dict.get('id'), user.email)
        hdx_mailer.mail_recipient(admin_list,
                                  subject, email_data, footer='*****@*****.**',
                                  snippet='email/content/new_account_confirmation_to_admins.html')
    except (socket_error, Exception) as error:
        # Email could not be sent, delete the pending user
        _get_action('user_delete')(context, {'id': user.id})
        _err_str = 'Error sending the invite email, the user was not created: {0}'.format(error)
        msg = _(_err_str)
        raise ValidationError({'message': msg}, error_summary=msg)

    return model_dictize.user_dictize(user, context)
Example #17
0
        except exceptions.Exception, e:
            error_summary = e.error or str(e)
            return self.error_message(error_summary)

        try:
            subject = u'HDX contact form submission (COVID-19 data responsibility)'
            email_data = {
                'user_display_name': fullname,
                'user_email': email,
                'msg': msg,
            }
            hdx_mailer.mail_recipient(
                [{
                    'display_name': 'Humanitarian Data Exchange (HDX)',
                    'email': hdx_email
                }],
                subject,
                email_data,
                sender_name=fullname,
                sender_email=email,
                snippet='email/content/data_responsability_faq_request.html')

            subject = u'Confirmation of your contact form submission (COVID-19 data responsibility)'
            email_data = {
                'user_fullname': fullname,
                'msg': msg,
            }
            hdx_mailer.mail_recipient(
                [{
                    'display_name': fullname,
                    'email': email
                }],
Example #18
0
def hdx_send_mail_contributor(context, data_dict):
    _check_access('hdx_send_mail_contributor', context, data_dict)

    subject = u'[HDX] {fullname} {topic} for \"[Dataset] {pkg_title}\"'.format(
        fullname=data_dict.get('fullname'),
        topic=data_dict.get('topic'),
        pkg_title=data_dict.get('pkg_title'))
    requester_body_html = __create_body_for_contributor(data_dict, False)

    admins_body_html = __create_body_for_contributor(data_dict, True)

    recipients_list = []
    org_members = get_action("hdx_member_list")(
        context, {
            'org_id': data_dict.get('pkg_owner_org')
        })
    if org_members:
        admins = org_members.get('admins')
        for admin in admins:
            context['keep_email'] = True
            user = get_action("user_show")(context, {'id': admin})
            if user.get('email'):
                recipients_list.append({
                    'email': user.get('email'),
                    'display_name': user.get('display_name')
                })

    pkg_dict = get_action("package_show")(context, {
        'id': data_dict.get('pkg_id')
    })
    maintainer = pkg_dict.get("maintainer")
    if maintainer:
        m_user = get_action("user_show")(context, {'id': maintainer})
        if not any(r['email'] == m_user.get('email') for r in recipients_list):
            recipients_list.append({
                'email': m_user.get('email'),
                'display_name': m_user.get('display_name')
            })

    org_dict = get_action('hdx_light_group_show')(
        context, {
            'id': data_dict.get('pkg_owner_org')
        })
    subject = u'HDX dataset inquiry'
    email_data = {
        'org_name': org_dict.get('title'),
        'user_fullname': data_dict.get('fullname'),
        'user_email': data_dict.get('email'),
        'pkg_url': data_dict.get('pkg_url'),
        'pkg_title': data_dict.get('pkg_title'),
        'topic': data_dict.get('topic'),
        'msg': data_dict.get('msg'),
    }
    cc_recipients_list = [{
        'email': data_dict.get('hdx_email'),
        'display_name': 'HDX'
    }]
    hdx_mailer.mail_recipient(
        recipients_list,
        subject,
        email_data,
        sender_name=data_dict.get('fullname'),
        sender_email=data_dict.get('email'),
        cc_recipients_list=cc_recipients_list,
        footer='*****@*****.**',
        snippet='email/content/contact_contributor_request.html')

    subject = u'HDX dataset inquiry'
    email_data = {
        'user_fullname': data_dict.get('fullname'),
        'pkg_url': data_dict.get('pkg_url'),
        'pkg_title': data_dict.get('pkg_title'),
        'topic': data_dict.get('topic'),
        'msg': data_dict.get('msg'),
    }
    recipients_list = [{
        'email': data_dict.get('email'),
        'display_name': data_dict.get('fullname')
    }]
    hdx_mailer.mail_recipient(
        recipients_list,
        subject,
        email_data,
        footer=data_dict.get('email'),
        snippet=
        'email/content/contact_contributor_request_confirmation_to_user.html')

    return None
Example #19
0
    def handle_new_request_action(self, username, request_action):
        '''Handles sending email to the person who created the request, as well
        as updating the state of the request depending on the data sent.

        :param username: The user's name.
        :type username: string

        :param request_action: The current action. Can be either reply or
        reject
        :type request_action: string

        :rtype: json

        '''

        data = dict(toolkit.request.POST)

        if request_action == 'reply':
            reply_email = data.get('email')

            try:
                validate_email(reply_email)
            except Exception:
                error = {
                    'success': False,
                    'error': {
                        'fields': {
                            'email': 'The email you provided is invalid.'
                        }
                    }
                }

                return json.dumps(error)

        counters_data_dict = {'package_id': data['package_id'], 'flag': ''}
        if 'rejected' in data:
            data['rejected'] = asbool(data['rejected'])
            counters_data_dict['flag'] = 'declined'
        elif 'data_shared' in data:
            counters_data_dict['flag'] = 'shared and replied'
        else:
            counters_data_dict['flag'] = 'replied'

        # self._get_email_content(data, request_action)
        message_content = data.get('message_content')
        if message_content is None or message_content == '':
            payload = {
                'success': False,
                'error': {
                    'message_content': 'Missing value'
                }
            }
            return json.dumps(payload)

        try:
            _get_action('requestdata_request_patch', data)
        except NotAuthorized:
            abort(403, _('Not authorized to use this action.'))
        except ValidationError as e:
            error = {'success': False, 'error': {'fields': e.error_dict}}
            return json.dumps(error)

        # to = self._get_email_to(data, request_action)
        #
        # subject = self._get_email_subject(data, request_action)
        #
        # file = data.get('file_upload')
        #
        # response = send_email(message_content, to, subject, file=file)
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj
        }
        if request_action == _REQUESTDATA_REJECT:
            try:
                subject = u'Request for access to HDX "metadata-only" dataset denied'
                pkg_dict = get_action('package_show')(
                    context, {
                        'id': data.get('package_id')
                    })
                org_dict = get_action('organization_show')(
                    context, {
                        'id': pkg_dict.get('owner_org')
                    })
                email_data = {
                    'user_fullname':
                    data.get('requested_by'),
                    'org_name':
                    org_dict.get('title'),
                    'dataset_link':
                    h.url_for('dataset_read',
                              id=data.get('package_id'),
                              qualified=True),
                    'dataset_title':
                    data.get('package_name'),
                    'msg':
                    data.get('message_content'),
                }
                hdx_mailer.mail_recipient(
                    [{
                        'display_name': data.get('requested_by'),
                        'email': data.get('send_to')
                    }],
                    subject,
                    email_data,
                    footer=data.get('send_to'),
                    snippet='email/content/request_data_rejection_to_user.html'
                )

                subject = u'Request for access to HDX "metadata only" dataset denied'
                maintainer_obj = model.User.get(pkg_dict.get('maintainer'))
                email_data = {
                    'user_fullname':
                    data.get('requested_by'),
                    'user_email':
                    data.get('send_to'),
                    'dataset_link':
                    h.url_for('dataset_read',
                              id=data.get('package_id'),
                              qualified=True),
                    'dataset_title':
                    data.get('package_name'),
                    'user_admin_fullname':
                    c.userobj.fullname,
                }
                hdx_mailer.mail_recipient(
                    [{
                        'display_name': maintainer_obj.fullname,
                        'email': maintainer_obj.email
                    }],
                    subject,
                    email_data,
                    footer=maintainer_obj.email,
                    snippet=
                    'email/content/request_data_rejection_to_admins.html')
            except Exception, ex:
                error = {
                    'success': False,
                    'error': {
                        'fields': {
                            'email': str(ex)
                        }
                    }
                }

                return json.dumps(error)
Example #20
0
            if configuration.config.get(
                    'hdx.onboarding.send_confirmation_email') == 'true':
                link = config['ckan.site_url'] + '/login'
                full_name = data_dict.get('fullname')
                subject = u'Thank you for joining the HDX community!'
                email_data = {
                    'user_first_name': first_name,
                    'username': data_dict.get('name'),
                }
                hdx_mailer.mail_recipient(
                    [{
                        'display_name': full_name,
                        'email': data_dict.get('email')
                    }],
                    subject,
                    email_data,
                    footer=data_dict.get('email'),
                    snippet=
                    'email/content/onboarding_confirmation_of_registration.html'
                )

        except NotAuthorized:
            return OnbNotAuth
        except NotFound, e:
            return OnbUserNotFound
        except DataError:
            return OnbIntegrityErr
        except ValidationError, e:
            error_summary = ''
            if 'Name' in e.error_summary:
Example #21
0
                    <br/>
                    <p>You can learn more about HDX in our {faq_link}. Look out for a couple more emails from us in the coming days -- we will be offering tips on making the most of the platform. </p>
                    <br/>
                    <p>Best wishes,</p>
                    <p>The HDX team</p>
                  </body>
                </html>
                """.format(username=data_dict.get('name'),
                           link=link,
                           faq_link=faq_link,
                           first_name=first_name)
                if configuration.config.get(
                        'hdx.onboarding.send_confirmation_email',
                        'false') == 'true':
                    hdx_mailer.mail_recipient([{
                        'display_name': full_name,
                        'email': data_dict.get('email')
                    }], subject, html)

        except NotAuthorized:
            return OnbNotAuth
        except NotFound, e:
            return OnbUserNotFound
        except DataError:
            return OnbIntegrityErr
        except ValidationError, e:
            error_summary = ''
            if 'Name' in e.error_summary:
                error_summary += str(e.error_summary.get('Name'))
            if 'Password' in e.error_summary:
                error_summary += str(e.error_summary.get('Password'))
            return self.error_message(error_summary or e.error_summary)
Example #22
0
    def send_request(self):
        '''Send mail to resource owner.

        :param data: Contact form data.
        :type data: object

        :rtype: json
        '''
        context = {'model': model, 'session': model.Session,
                   'user': c.user, 'auth_user_obj': c.userobj}
        try:
            if p.toolkit.request.method == 'POST':
                data = dict(toolkit.request.POST)
                _get_action('requestdata_request_create', data)
        except NotAuthorized:
            abort(403, _('Unauthorized to update this dataset.'))
        except ValidationError as e:
            error = {
                'success': False,
                'error': {
                    'fields': e.error_dict
                }
            }

            return json.dumps(error)

        data_dict = {'id': data['package_id']}
        package = _get_action('package_show', data_dict)
        sender_name = data.get('sender_name', '')
        user_obj = context['auth_user_obj']
        data_dict = {
            'id': user_obj.id,
            'permission': 'read'
        }

        organizations = _get_action('hdx_organization_list_for_user', data_dict)

        orgs = []
        for i in organizations:
                orgs.append(i['display_name'])
        org = ','.join(orgs)
        dataset_name = package['name']
        dataset_title = package['title']
        email = user_obj.email
        message = data['message_content']
        creator_user_id = package['creator_user_id']
        data_owner =\
            _get_action('user_show', {'id': creator_user_id}).get('name')
        if len(get_sysadmins()) > 0:
            sysadmin = get_sysadmins()[0].name
            context_sysadmin = {
                'model': model,
                'session': model.Session,
                'user': sysadmin,
                'auth_user_obj': c.userobj
            }
            to = package['maintainer']
            if to is None:
                message = {
                    'success': False,
                    'error': {
                        'fields': {
                            'email': 'Dataset maintainer email not found.'
                        }
                    }
                }

                return json.dumps(message)
            maintainers = to.split(',')
            data_dict = {
                'users': []
            }
            users_email = []
            only_org_admins = False
            data_maintainers = []
            data_maintainers_ids = []
            # Get users objects from maintainers list
            user={}
            for id in maintainers:
                try:
                    user =\
                        toolkit.get_action('user_show')(context_sysadmin,
                                                        {'id': id})
                    data_dict['users'].append(user)
                    users_email.append({'display_name': user.get('fullname'), 'email': user.get('email')})
                    data_maintainers.append(user['fullname'] or user['name'])
                    data_maintainers_ids.append(user['name'] or user['id'])
                except NotFound:
                    pass
            mail_subject =\
                config.get('ckan.site_title') + ': New data request "'\
                                                + dataset_title + '"'

            if len(users_email) == 0:
                admins = self._org_admins_for_dataset(dataset_name)
                # admins=og_create.get_organization_admins(package.get('owner_org'))

                for admin in admins:
                    users_email.append({'display_name': admin.get('fullname'), 'email': admin.get('email')})
                    data_maintainers.append(admin.get('fullname'))
                    data_maintainers_ids.append(admin.get('name') or admin.get('id'))
                only_org_admins = True

            # content = _get_email_configuration(
            #     sender_name, data_owner, dataset_name, email,
            #     message, org, data_maintainers,
            #     data_maintainers_ids=data_maintainers_ids,
            #     only_org_admins=only_org_admins)

            # response_message = \
            #     emailer.send_email(content, users_email, mail_subject)
            subject = sender_name + u' has requested access to one of your datasets'
            email_data = {
                'user_fullname': sender_name,
                'user_email': email,
                'msg': message,
                'org_name': package.get('organization').get('title'),
                'dataset_link': h.url_for('dataset_read', id=dataset_name, qualified=True),
                'dataset_title': dataset_title,
                'maintainer_fullname': user.get('display_name') or user.get('fullname') if user else 'HDX user',
                 'requestdata_org_url': h.url_for('requestdata_organization_requests', id=package.get('owner_org'),
                                                 qualified=True)
            }
            hdx_mailer.mail_recipient(users_email, subject, email_data, footer='*****@*****.**',
                                      snippet='email/content/request_data_to_admins.html')

            subject = u'Request for access to metadata-only dataset'
            email_data = {
                'user_fullname': sender_name,
                'msg': message,
                'org_name': package.get('organization').get('title'),
                'dataset_link': h.url_for('dataset_read', id=dataset_name, qualified=True),
                'dataset_title': dataset_title,
            }
            hdx_mailer.mail_recipient(users_email, subject, email_data, footer=email,
                                      snippet='email/content/request_data_to_user.html')

            # notify package creator that new data request was made
            _get_action('requestdata_notification_create', data_dict)
            data_dict = {
                'package_id': data['package_id'],
                'flag': 'request'
            }

            action_name = 'requestdata_increment_request_data_counters'
            _get_action(action_name, data_dict)
            response_dict = {
                'success': True,
                'message': 'Email message was successfully sent.'
            }
            return json.dumps(response_dict)
        else:
            message = {
                'success': True,
                'message': 'Request sent, but email message was not sent.'
            }

            return json.dumps(message)
Example #23
0
def hdx_send_new_org_request(context, data_dict):
    _check_access('hdx_send_new_org_request', context, data_dict)

    email = config.get('hdx.orgrequest.email', None)
    if not email:
        email = '*****@*****.**'
    display_name = 'HDX Feedback'

    ckan_username = c.user
    ckan_email = ''
    if c.userobj:
        ckan_email = c.userobj.email
    if configuration.config.get('hdx.onboarding.send_confirmation_email', 'false') == 'true':

        # body = _('<h3>New organisation request </h3><br/>' \
        #          'Organisation Name: {org_name}<br/>' \
        #          'Organisation Description: {org_description}<br/>' \
        #          'Organisation Data Description: {org_description_data}<br/>' \
        #          'Work email: {org_work_email}<br/>' \
        #          'Organisation URL: {org_url}<br/>' \
        #          'Organisation Type: {hdx_org_type}<br/>' \
        #          'Organisation Acronym: {org_acronym}<br/>' \
        #          'Person requesting: {person_name}<br/>' \
        #          'Person\'s email: {person_email}<br/>' \
        #          'Person\'s ckan username: {ckan_username}<br/>' \
        #          'Person\'s ckan email: {ckan_email}<br/>' \
        #          'Request time: {request_time}<br/>' \
        #          '(This is an automated mail)<br/><br/>' \
        #          '').format(org_name=data_dict.get('name',''), org_description=data_dict.get('description',''),
        #                     org_description_data=data_dict.get('description_data',''),
        #                     org_work_email=data_dict.get('work_email', ''),
        #                     org_url=data_dict.get('org_url',''), org_acronym=data_dict.get('acronym',''),
        #                     hdx_org_type=data_dict.get('org_type',''),
        #                     person_name=data_dict.get('your_name',''),
        #                     person_email=data_dict.get('your_email',''),
        #                     ckan_username=ckan_username, ckan_email=ckan_email,
        #                     request_time=datetime.datetime.now().isoformat())
        hdx_email = configuration.config.get('hdx.faqrequest.email', '*****@*****.**')
        subject = u'Request to create a new organisation on HDX'
        email_data = {
            'org_name': data_dict.get('name', ''),
            'org_acronym': data_dict.get('acronym', ''),
            'org_description': data_dict.get('description', ''),
            'org_type': data_dict.get('org_type', ''),
            'org_website': data_dict.get('org_url', ''),
            'data_description': data_dict.get('description_data', ''),
            'requestor_work_email': data_dict.get('work_email', ''),
            'requestor_hdx_username': ckan_username,
            'requestor_hdx_email': ckan_email,
            'request_time': datetime.datetime.now().isoformat(),
            'user_fullname': data_dict.get('your_name', ''),
        }
        hdx_mailer.mail_recipient([{'display_name': 'Humanitarian Data Exchange (HDX)', 'email': hdx_email}],
                                  subject, email_data, sender_name=data_dict.get('your_name', ''),
                                  sender_email=ckan_email,
                                  snippet='email/content/new_org_request_hdx_team_notification.html')

        subject = u'Confirmation of your request to create a new organisation on HDX'
        email_data = {
            'org_name': data_dict.get('name', ''),
            # 'org_acronym': data_dict.get('acronym', ''),
            # 'org_description': data_dict.get('description', ''),
            # 'org_type': data_dict.get('org_type', ''),
            # 'org_website': data_dict.get('org_url', ''),
            # 'data_description': data_dict.get('description_data', ''),
            # 'requestor_work_email': data_dict.get('work_email', ''),
            # 'requestor_hdx_username': ckan_username,
            # 'requestor_hdx_email': ckan_email,
            # 'request_time': datetime.datetime.now().isoformat(),
            'user_fullname': data_dict.get('your_name', ''),
        }
        hdx_mailer.mail_recipient([{'display_name': data_dict.get('your_name', ''), 'email': ckan_email}],
                                  subject, email_data, footer=ckan_email,
                                  snippet='email/content/new_org_request_confirmation_to_user.html')