コード例 #1
0
def mail_process_status(locale, member_user, approve, group_name, capacity):
    current_locale = get_lang()
    if locale == 'en':
        _reset_lang()
    else:
        set_lang(locale)

    role_name = _(capacity)

    subject_template = _SUBJECT_MEMBERSHIP_APPROVED(
    ) if approve else _SUBJECT_MEMBERSHIP_REJECTED()
    message_template = _MESSAGE_MEMBERSHIP_APPROVED(
    ) if approve else _MESSAGE_MEMBERSHIP_REJECTED()

    subject = subject_template % {
        'organization': group_name
    }
    message = message_template % {
        'role': role_name,
        'organization': group_name
    }

    try:
        mail_user(member_user, subject, message)
    except Exception:
        log.exception("Mail could not be sent")
        # raise MailerException("Mail could not be sent")
    finally:
        set_lang(current_locale)
コード例 #2
0
ファイル: test_mailer.py プロジェクト: MrkGrgsn/ckan
    def test_mail_user(self):

        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        msgs = self.get_smtp_messages()
        assert_equal(msgs, [])

        # send email
        test_email = {'recipient': user_obj,
                      'subject': 'Meeting',
                      'body': 'The meeting is cancelled.',
                      'headers': {'header1': 'value1'}}
        mailer.mail_user(**test_email)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config['smtp.mail_from'])
        assert_equal(msg[2], [user['email']])
        assert test_email['headers'].keys()[0] in msg[3], msg[3]
        assert test_email['headers'].values()[0] in msg[3], msg[3]
        assert test_email['subject'] in msg[3], msg[3]
        expected_body = self.mime_encode(test_email['body'],
                                         user['name'])

        assert_in(expected_body, msg[3])
コード例 #3
0
ファイル: action.py プロジェクト: ckan/ckanext-issues
def issue_comment_create(context, data_dict):
    '''Add a new issue comment.

    You must provide your API key in the Authorization header.

    :param comment: the comment text
    :type comment: string
    :param issue_number: the number of the issue the comment belongs to
    :type issue_number: integer
    :param dataset_id: the dataset name or id of the issue the comment belongs to
    :type dataset_id: unicode

    :returns: the newly created issue comment
    :rtype: dictionary
    '''
    p.toolkit.check_access('issue_comment_create', context, data_dict)
    user = context['user']
    user_obj = model.User.get(user)

    issue = issuemodel.Issue.get_by_name_or_id_and_number(
        dataset_name_or_id=data_dict['dataset_id'],
        issue_number=data_dict['issue_number'],
        session=context['session']
    )

    comment_dict = data_dict.copy()
    del comment_dict['dataset_id']
    del comment_dict['issue_number']
    comment_dict.update({
        'user_id': user_obj.id,
        'issue_id': issue.id,
    })

    issue_comment = issuemodel.IssueComment(**comment_dict)
    model.Session.add(issue_comment)
    model.Session.commit()

    notifications = p.toolkit.asbool(
        config.get('ckanext.issues.send_email_notifications')
    )

    if notifications:
        dataset = model.Package.get(data_dict['dataset_id'])
        recipients = _get_recipients(context, dataset)
        subject = get_issue_subject(issue.as_dict())

        for recipient in recipients:
            body = _get_comment_email_body(
                issue_comment, subject, user_obj, recipient)

            user_obj = model.User.get(recipient['user_id'])
            try:
                mailer.mail_user(user_obj, subject, body)
            except (mailer.MailerException, TypeError), e:
                # TypeError occurs when we're running command from ckanapi
                log.debug(e.message)
コード例 #4
0
ファイル: action.py プロジェクト: ckan/ckanext-issues
def issue_create(context, data_dict):
    '''Add a new issue.

    You must provide your API key in the Authorization header.

    :param title: the title of the issue
    :type title: string
    :param description: the description of the issue item (optional)
    :type description: string
    :param dataset_id: the name or id of the dataset that the issue item
        belongs to (optional)
    :type dataset_id: string

    :returns: the newly created issue item
    :rtype: dictionary
    '''
    p.toolkit.check_access('issue_create', context, data_dict)

    user = context['user']
    user_obj = model.User.get(user)
    data_dict['user_id'] = user_obj.id

    dataset = model.Package.get(data_dict['dataset_id'])
    del data_dict['dataset_id']

    issue = issuemodel.Issue(**data_dict)
    issue.dataset_id = dataset.id
    session = context['session']
    issue.number = _get_next_issue_number(session, dataset.id)

    session.add(issue)
    session.commit()

    notifications = p.toolkit.asbool(
        config.get('ckanext.issues.send_email_notifications')
    )

    if notifications:
        recipients = _get_recipients(context, dataset)
        subject = get_issue_subject(issue.as_dict())

        for i, recipient in enumerate(recipients):
            body = _get_issue_email_body(issue, subject, user_obj, recipient)
            user_obj = model.User.get(recipient['user_id'])
            if i == 0:
                log.debug('Mailing to %s (and %s others):\n%s',
                          user_obj.email, len(recipients) - 1, body)
            try:
                mailer.mail_user(user_obj, subject, body)
            except (mailer.MailerException, TypeError), e:
                # TypeError occurs when we're running command from ckanapi
                log.debug(e.message)
コード例 #5
0
def mail_notification_to_collaborator(dataset_id, user_id, capacity, event):
    user = core_model.User.get(user_id)
    dataset = core_model.Package.get(dataset_id)

    try:
        subj = _compose_email_subj(dataset)
        body = _compose_email_body(user, dataset, capacity, event)
        mail_user(user,
                  subj,
                  body,
                  headers={'Content-Type': 'text/html; charset=UTF-8'})
    except MailerException as exception:
        log.exception(exception)
コード例 #6
0
ファイル: action.py プロジェクト: rhabbachi/ckanext-issues
def issue_create(context, data_dict):
    '''Add a new issue.

    You must provide your API key in the Authorization header.

    :param title: the title of the issue
    :type title: string
    :param description: the description of the issue item (optional)
    :type description: string
    :param dataset_id: the name or id of the dataset that the issue item
        belongs to (optional)
    :type dataset_id: string

    :returns: the newly created issue item
    :rtype: dictionary
    '''
    p.toolkit.check_access('issue_create', context, data_dict)

    user = context['user']
    user_obj = model.User.get(user)
    data_dict['user_id'] = user_obj.id

    dataset = model.Package.get(data_dict['dataset_id'])
    del data_dict['dataset_id']

    issue = issuemodel.Issue(**data_dict)
    issue.dataset_id = dataset.id
    session = context['session']
    issue.number = _get_next_issue_number(session, dataset.id)

    session.add(issue)
    session.commit()

    notifications = p.toolkit.asbool(
        config.get('ckanext.issues.send_email_notifications'))

    if notifications:
        recipients = _get_recipients(context, dataset)
        subject = get_issue_subject(issue.as_dict())

        for i, recipient in enumerate(recipients):
            body = _get_issue_email_body(issue, subject, user_obj, recipient)
            user_obj = model.User.get(recipient['user_id'])
            if i == 0:
                log.debug('Mailing to %s (and %s others):\n%s', user_obj.email,
                          len(recipients) - 1, body)
            try:
                mailer.mail_user(user_obj, subject, body)
            except (mailer.MailerException, TypeError), e:
                # TypeError occurs when we're running command from ckanapi
                log.debug(e.message)
コード例 #7
0
ファイル: mailer.py プロジェクト: starsinmypockets/ckanext-ed
def mail_package_publish_update_to_user(
                            context, pkg_dict, event='approval', feedback=None):
    '''
    Sends an email to user who published the dataset about approbal state.
    One of approved or rejected
    '''
    context.setdefault('model', model)
    user = model.User.get(pkg_dict['creator_user_id'])
    if user and user.email:
        subj = _compose_email_subj(pkg_dict, event=event)
        body = _compose_email_body(pkg_dict, user, event=event, feedback=feedback)
        header = {'Content-Type': 'text/html; charset=UTF-8'}
        mail_user(user, subj, body, headers=header)
        log.debug('[email] Data container update email sent to {0}'.format(user.name))
コード例 #8
0
def broken_links_report(recepients=[]):
    broken_count = 0
    resources = model.Session.query(model.Resource).join(
        model.Package,
        model.Package.id == model.Resource.package_id).outerjoin(
            model.PackageExtra,
            (model.Package.id == model.PackageExtra.package_id) &
            (model.PackageExtra.key == 'harvest_url')).filter(
                model.Resource.state == 'active',
                model.PackageExtra.key.is_(None))
    total = resources.count()
    file = open(config['spc.report.broken_links_filepath'], 'wb')
    report = csv.writer(file)
    report.writerow(['Page', 'Broken URL', 'HTTP Code', 'Reason'])
    for i, res in enumerate(resources, 1):
        logger.debug('Processing %s of %s. Broken links: %s', i, total,
                     broken_count)

        sys.stdout.flush()
        try:
            resp = requests.head(res.url, timeout=5)
            if resp.ok:
                continue
            code, reason = resp.status_code, resp.reason
            # it's likely incorrect request to service endpoint
            if 400 == code:
                continue
        except (exc.ConnectTimeout, exc.ReadTimeout):
            code, reason = 504, 'Request timeout'
        except exc.ConnectionError:
            code, reason = 520, 'Connection Error'
        except (exc.MissingSchema, exc.InvalidSchema):
            continue
        except exc.InvalidURL:
            code, reason = 520, 'Invalid URL'

        page = h.url_for('resource.read',
                         id=res.package_id,
                         resource_id=res.id,
                         qualified=True)

        report.writerow([page, res.url.encode('utf-8'), code, reason])
        broken_count += 1
    file.close()
    users = model.Session.query(model.User).filter(
        model.User.name.in_(recepients), ~model.User.email.is_(None))
    url = h.url_for('spc_admin.broken_links', qualified=True)
    message = u'There is new report available at {}'.format(url)
    for user in users:
        mail_user(user, 'Broken links report', message)
コード例 #9
0
    def test_mail_user_without_email(self):
        # send email
        mary = model.User(name="mary", email=None)
        # model.Session.add(mary)
        # model.Session.commit()

        test_email = {
            "recipient": mary,
            "subject": "Meeting",
            "body": "The meeting is cancelled.",
            "headers": {"header1": "value1"},
        }
        with pytest.raises(mailer.MailerException):
            mailer.mail_user(**test_email)
コード例 #10
0
    def crawl(self):
        site_url = config.get('ckan.site_url')
        crawl_url_blacklist_regex = re.compile(r'/activity/')
        crawl_content_type_whitelist_regex = re.compile(r'text/html')
        url_regex = re.compile(
            r'href="((http[s]?://|/)(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)"'
        )
        site_map = {}
        to_crawl = [site_url]
        while to_crawl:
            next_crawl = to_crawl.pop(0)
            new_crawl = crawl(next_crawl, site_url, site_map,
                              crawl_url_blacklist_regex,
                              crawl_content_type_whitelist_regex, url_regex)
            to_crawl += new_crawl

        external_urls = get_external_children(site_url, site_map)
        url_errors = {}
        for url in sorted(external_urls):
            try:
                urlopen(url)
            except HTTPError as e:
                referrers = find_referrers(url, site_map)
                url_errors[url] = referrers
            except URLError as e:
                referrers = find_referrers(url, site_map)
                url_errors[url] = referrers

        for url, referrers in url_errors.iteritems():
            result = LinkValidationResult()
            result.type = u'error'
            result.url = url
            result.referrers = []

            for referrer_url in referrers:
                referrer = LinkValidationReferrer()
                referrer.result_id = result.id
                referrer.url = referrer_url
                result.referrers.append(referrer)

            model.Session.add(result)
        model.Session.commit()

        if url_errors:
            from ckan.model.user import User
            admin = User.get('admin')
            mailer.mail_user(
                admin, 'URL errors',
                '\n\n'.join('%s\n%s' % (u, '\n'.join('  - %s' % r for r in rs))
                            for u, rs in url_errors.iteritems()))
コード例 #11
0
def assign(dataset_id, issue_number):
    dataset = _before_dataset(dataset_id)
    if request.method == 'POST':
        try:
            assignee_id = request.form.get('assignee')
            assignee = toolkit.get_action('user_show')(data_dict={
                'id': assignee_id
            })
        except toolkit.ObjectNotFound:
            h.flash_error(_('User {0} does not exist'.format(assignee_id)))
            return p.toolkit.redirect_to('issues.show_issue',
                                         issue_number=issue_number,
                                         dataset_id=dataset_id)

        try:
            issue = toolkit.get_action('issue_update')(
                data_dict={
                    'issue_number': issue_number,
                    'assignee_id': assignee['id'],
                    'dataset_id': dataset_id,
                    'assignee': assignee_id
                })

            notifications = p.toolkit.asbool(
                config.get('ckanext.issues.send_email_notifications'))

            if notifications:
                subject = get_issue_subject(issue)
                body = u'Доделено на {user}.\n\n---\nCaktuar për {user}.\n\n---\nAssigned to {user}.'.format(
                    user=assignee['display_name'])

                user_obj = model.User.get(assignee_id)
                try:
                    mailer.mail_user(user_obj, subject, body)
                except mailer.MailerException as e:
                    log.debug(e.message)

        except toolkit.NotAuthorized:
            msg = _(
                'Unauthorized to assign users to issue'.format(issue_number))
            toolkit.abort(401, msg)
        except toolkit.ObjectNotFound as e:
            toolkit.abort(404)
        except toolkit.ValidationError as e:
            toolkit.abort(404)

        return p.toolkit.redirect_to('issues.show_issue',
                                     issue_number=issue_number,
                                     dataset_id=dataset_id)
コード例 #12
0
def mail_new_membership_request(locale, admin, group_name, url, user_name,
                                user_email):

    subject = _SUBJECT_MEMBERSHIP_REQUEST() % {'organization': group_name}
    message = _MESSAGE_MEMBERSHIP_REQUEST() % {
        'user': user_name,
        'email': user_email,
        'organization': group_name,
        'link': url
    }

    try:
        mail_user(admin, subject, message)
    except Exception:
        log.exception("Mail could not be sent")
コード例 #13
0
    def test_mail_user_with_attachments(self, mail_server):

        user = factories.User()
        user_obj = model.User.by_name(user["name"])

        msgs = mail_server.get_smtp_messages()
        assert msgs == []

        # send email
        test_email = {
            "recipient":
            user_obj,
            "subject":
            "Meeting",
            "body":
            "The meeting is cancelled.\n",
            "headers": {
                "header1": "value1"
            },
            "attachments": [
                ("strategy.pdf", io.BytesIO(b'Some fake pdf'),
                 'application/pdf'),
                ("goals.png", io.BytesIO(b'Some fake png'), 'image/png'),
            ]
        }
        mailer.mail_user(**test_email)

        # check it went to the mock smtp server
        msgs = mail_server.get_smtp_messages()
        assert len(msgs) == 1
        msg = msgs[0]
        assert msg[1] == config["smtp.mail_from"]
        assert msg[2] == [user["email"]]
        assert list(test_email["headers"].keys())[0] in msg[3], msg[3]
        assert list(test_email["headers"].values())[0] in msg[3], msg[3]
        assert test_email["subject"] in msg[3], msg[3]

        for item in [
                "strategy.pdf",
                base64.b64encode(b'Some fake pdf').decode(),
                "application/pdf",
                "goals.png",
                base64.b64encode(b'Some fake png').decode(),
                "image/png",
        ]:
            assert item in msg[3]
コード例 #14
0
def mail_welcome_email(user, site_name, site_email, site_url):
    subject = _SUBJECT_WELCOME_EMAIL()
    message = _MESSAGE_WELCOME_EMAIL() % {
        "user": user.display_name,
        "username": user.username,
        "email": user.email,
        "siteurl": site_url,
        "sitename": site_name,
        "siteemail": site_email,
    }
    headers = {
        "Reply-To": "{} <{}>".format(site_name, site_email),
    }

    try:
        mail_user(user, subject, message, headers)
    except Exception:
        log.exception("Mail could not be sent")
コード例 #15
0
def _send_mail(user_ids, action_type, datarequest):

    for user_id in user_ids:
        try:
            user_data = model.User.get(user_id)
            extra_vars = {
                'datarequest': datarequest,
                'user': user_data,
                'site_title': config.get('ckan.site_title'),
                'site_url': config.get('ckan.site_url')
            }

            subject = base.render_jinja2('emails/subjects/{0}.txt'.format(action_type), extra_vars)
            body = base.render_jinja2('emails/bodies/{0}.txt'.format(action_type), extra_vars)

            mailer.mail_user(user_data, subject, body)

        except Exception:
            logging.exception("Error sending notification to {0}".format(user_id))
コード例 #16
0
ファイル: membership.py プロジェクト: etalab/ckanext-youckan
    def send_mail(self, user, subject, template, extra=None):
        from ckan.lib.mailer import mail_user

        if not user.email:
            return

        org_url = urljoin(g.site_url, toolkit.url_for(
            controller='organization',
            action='read',
            id=self.organization.name,
        ))
        body = toolkit.render(template, {
            'membership': self,
            'user': user,
            'org_url': org_url,
            'site_title': g.site_title,
            'site_url': g.site_url,
        })
        mail_user(user, subject, body)
コード例 #17
0
def _send_mail(user_ids, action_type, datarequest):

    for user_id in user_ids:
        try:
            user_data = model.User.get(user_id)
            extra_vars = {
                'datarequest': datarequest,
                'user': user_data,
                'site_title': config.get('ckan.site_title'),
                'site_url': config.get('ckan.site_url')
            }

            subject = base.render_jinja2('emails/subjects/{0}.txt'.format(action_type), extra_vars)
            body = base.render_jinja2('emails/bodies/{0}.txt'.format(action_type), extra_vars)

            mailer.mail_user(user_data, subject, body)

        except Exception:
            logging.exception("Error sending notification to {0}".format(user_id))
コード例 #18
0
    def assign(self, dataset_id, issue_number):
        dataset = self._before_dataset(dataset_id)
        if request.method == 'POST':
            try:
                assignee_id = request.POST.get('assignee')
                assignee = toolkit.get_action('user_show')(
                    data_dict={'id': assignee_id})
            except toolkit.ObjectNotFound:
                h.flash_error(_('User {0} does not exist'.format(assignee_id)))
                return p.toolkit.redirect_to('issues_show',
                                             issue_number=issue_number,
                                             dataset_id=dataset_id)

            try:
                issue = toolkit.get_action('issue_update')(
                    data_dict={
                        'issue_number': issue_number,
                        'assignee_id': assignee['id'],
                        'dataset_id': dataset_id
                    }
                )

                notifications = p.toolkit.asbool(
                    config.get('ckanext.issues.send_email_notifications')
                )

                if notifications:
                    subject = get_issue_subject(issue)
                    body = toolkit._('Assigned to {user}'.format(
                        user=assignee['display_name']))

                    user_obj = model.User.get(assignee_id)
                    try:
                        mailer.mail_user(user_obj, subject, body)
                    except mailer.MailerException, e:
                        log.debug(e.message)

            except toolkit.NotAuthorized:
                msg = _('Unauthorized to assign users to issue'.format(
                    issue_number))
                toolkit.abort(401, msg)
            except toolkit.ValidationError, e:
                toolkit.abort(404)
コード例 #19
0
    def assign(self, dataset_id, issue_number):
        dataset = self._before_dataset(dataset_id)
        if request.method == 'POST':
            try:
                assignee_id = request.POST.get('assignee')
                assignee = toolkit.get_action('user_show')(data_dict={
                    'id': assignee_id
                })
            except toolkit.ObjectNotFound:
                h.flash_error(
                    _(u'User {0} does not exist').format(assignee_id))
                return p.toolkit.redirect_to('issues_show',
                                             issue_number=issue_number,
                                             dataset_id=dataset_id)

            try:
                issue = toolkit.get_action('issue_update')(
                    data_dict={
                        'issue_number': issue_number,
                        'assignee_id': assignee['id'],
                        'dataset_id': dataset_id
                    })

                notifications = p.toolkit.asbool(
                    config.get('ckanext.issues.send_email_notifications'))

                if notifications:
                    subject = get_issue_subject(issue)
                    msg = toolkit._("Assigned to %s")
                    body = msg % assignee['display_name']

                    user_obj = model.User.get(assignee_id)
                    try:
                        mailer.mail_user(user_obj, subject, body)
                    except mailer.MailerException, e:
                        log.debug(e.message)

            except toolkit.NotAuthorized:
                msg = _(u'Unauthorized to assign users to issue')
                toolkit.abort(401, msg)
            except toolkit.ValidationError, e:
                toolkit.abort(404)
コード例 #20
0
ファイル: mailer.py プロジェクト: starsinmypockets/ckanext-ed
def mail_package_publish_request_to_admins(
                        context, data_dict, event='approval', feedback=None):
    '''
    Sends an email to organization admin with request to publish dataset

    Note: Not used ATM
    '''
    members = core_member_list(
        context=context,
        data_dict={'id': data_dict.get('owner_org')}
    )
    admin_ids = [i[0] for i in members if i[2] == 'Admin']
    for admin_id in admin_ids:
        user = model.User.get(admin_id)
        if user.email:
            subj = _compose_email_subj(data_dict, event='request')
            body = _compose_email_body(data_dict, user, event='request')
            header = {'Content-Type': 'text/html; charset=UTF-8'}
            mail_user(user, subj, body, headers=header)
            log.debug('[email] Pakcage publishing request email sent to {0}'.format(user.name))
コード例 #21
0
def mail_new_membership_request(locale, admin, group_name, url, user_name,
                                user_email):
    # TODO: Set admin locale. Admin/user locale is stored at drupal database so may be a bit challenging to fetch it. We default to finnish for the time being
    current_locale = get_lang()
    i18n.set_lang("fi")

    subject = _SUBJECT_MEMBERSHIP_REQUEST() % {'organization': group_name}
    message = _MESSAGE_MEMBERSHIP_REQUEST() % {
        'user': user_name,
        'email': user_email,
        'organization': group_name,
        'link': url
    }

    try:
        mail_user(admin, subject, message)
    except Exception:
        log.exception("Mail could not be sent")
    finally:
        set_lang(current_locale)
コード例 #22
0
def notify_user(user, state, extra_vars):
    """
    Notifies the user about changes in the status of his request
    """
    messages = {
        'approved': 'access/email/spc_request_approved.txt',
        'rejected': 'access/email/spc_request_rejected.txt'
    }
    extra_vars['request_timeout'] = int(
        config.get('spc.access_request.request_timeout_days', 3))
    try:
        mailer.mail_user(
            user,
            "Access request",
            tk.render(messages[state], extra_vars),
        )
    except mailer.MailerException as e:
        logger.error(e)
    except SMTPServerDisconnected as e:
        logger.error(e)
コード例 #23
0
ファイル: logic.py プロジェクト: haphut/ytp
def _mail_new_membership_request(locale, admin, group_name, url, user_name, user_email):
    current_locale = get_lang()

    if locale == 'en':
        _reset_lang()
    else:
        set_lang(locale)
    subject = _SUBJECT_MEMBERSHIP_REQUEST() % {
        'organization': group_name
    }
    message = _MESSAGE_MEMBERSHIP_REQUEST() % {
        'user': user_name,
        'email': user_email,
        'organization': group_name,
        'link': url
    }

    try:
        mail_user(admin, subject, message)
    except MailerException, e:
        log.error(e)
コード例 #24
0
def _send_mail(user_ids, action_type, datarequest):

    for user_id in user_ids:
        try:
            user_data = model.User.get(user_id)
            extra_vars = {
                "datarequest": datarequest,
                "user": user_data,
                "site_title": config.get("ckan.site_title"),
                "site_url": config.get("ckan.site_url"),
            }

            subject = base.render_jinja2(f"emails/subjects/{action_type}.txt",
                                         extra_vars)
            body = base.render_jinja2(f"emails/bodies/{action_type}.txt",
                                      extra_vars)

            mailer.mail_user(user_data, subject, body)

        except Exception:
            logging.exception(f"Error sending notification to {user_id}")
コード例 #25
0
def mail_new_membership_request(locale, admin, group_name, url, user_name, user_email):
    # TODO: Set admin locale. Admin/user locale is stored at drupal database so may be a bit challenging to fetch it. We default to finnish for the time being
    current_locale = get_lang()
    i18n.set_lang("fi")

    subject = _SUBJECT_MEMBERSHIP_REQUEST() % {
        'organization': group_name
    }
    message = _MESSAGE_MEMBERSHIP_REQUEST() % {
        'user': user_name,
        'email': user_email,
        'organization': group_name,
        'link': url
    }

    try:
        mail_user(admin, subject, message)
    except Exception:
        log.exception("Mail could not be sent")
    finally:
        set_lang(current_locale)
コード例 #26
0
ファイル: alert.py プロジェクト: etalab/ckanext-youckan
    def send_mail(self, user, subject, template, extra=None):
        from ckan.lib.mailer import mail_user

        if not user.email:
            return

        dataset_url = urljoin(g.site_url, toolkit.url_for(
            controller='package',
            action='read',
            id=self.dataset.name,
        ))
        body = toolkit.render(template, {
            'alert': self,
            'user': user,
            'dataset_url': dataset_url,
            'site_title': g.site_title,
            'site_url': g.site_url,
            'names': ALERT_TYPE_NAMES,
            'organization': model.Group.get(self.dataset.owner_org) if self.dataset.owner_org else None,
        })

        mail_user(user, subject, body)
コード例 #27
0
    def test_mail_user_with_attachments_no_media_type_provided(
            self, mail_server):

        user = factories.User()
        user_obj = model.User.by_name(user["name"])

        msgs = mail_server.get_smtp_messages()
        assert msgs == []

        # send email
        test_email = {
            "recipient":
            user_obj,
            "subject":
            "Meeting",
            "body":
            "The meeting is cancelled.\n",
            "headers": {
                "header1": "value1"
            },
            "attachments": [
                ("strategy.pdf", io.BytesIO(b'Some fake pdf')),
                ("goals.png", io.BytesIO(b'Some fake png')),
            ]
        }
        mailer.mail_user(**test_email)

        # check it went to the mock smtp server
        msgs = mail_server.get_smtp_messages()
        assert len(msgs) == 1
        msg = msgs[0]

        for item in [
                "strategy.pdf",
                "application/pdf",
                "goals.png",
                "image/png",
        ]:
            assert item in msg[3]
コード例 #28
0
ファイル: test_mailer.py プロジェクト: Accela-Inc/ckan
    def test_mail_user(self):
        msgs = self.get_smtp_messages()
        assert_equal(msgs, [])

        # send email
        test_email = {'recipient': model.User.by_name(u'bob'),
                      'subject': 'Meeting', 
                      'body': 'The meeting is cancelled.',
                      'headers': {'header1': 'value1'}}
        mailer.mail_user(**test_email)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config['smtp.mail_from'])
        assert_equal(msg[2], [model.User.by_name(u'bob').email])
        assert test_email['headers'].keys()[0] in msg[3], msg[3]
        assert test_email['headers'].values()[0] in msg[3], msg[3]
        assert test_email['subject'] in msg[3], msg[3]
        expected_body = self.mime_encode(test_email['body'],
                                         'bob')
        assert expected_body in msg[3], '%r not in %r' % (expected_body, msg[3])
コード例 #29
0
ファイル: test_mailer.py プロジェクト: BigOpenData/ckan
    def test_mail_user(self):
        msgs = self.get_smtp_messages()
        assert_equal(msgs, [])

        # send email
        test_email = {
            "recipient": model.User.by_name(u"bob"),
            "subject": "Meeting",
            "body": "The meeting is cancelled.",
            "headers": {"header1": "value1"},
        }
        mailer.mail_user(**test_email)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config["smtp.mail_from"])
        assert_equal(msg[2], [model.User.by_name(u"bob").email])
        assert test_email["headers"].keys()[0] in msg[3], msg[3]
        assert test_email["headers"].values()[0] in msg[3], msg[3]
        assert test_email["subject"] in msg[3], msg[3]
        expected_body = self.mime_encode(test_email["body"], "bob")
        assert expected_body in msg[3], "%r not in %r" % (expected_body, msg[3])
コード例 #30
0
ファイル: actions.py プロジェクト: mehulsbhatt/ckanext-sweden
def 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 yser
    :rtype: dictionary
    '''
    toolkit.check_access('user_invite', context, data_dict)

    schema = context.get('schema',
                         logic.schema.default_user_invite_schema())
    data, errors = toolkit.navl_validate(data_dict, schema, context)
    if errors:
        raise toolkit.ValidationError(errors)

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

    name = logic.action.create._get_random_username_from_email(data['email'])
    password = str(random.SystemRandom().random())
    data['name'] = name
    data['password'] = password
    data['state'] = model.State.PENDING
    user_dict = toolkit.get_action('user_create')(context, data)
    user = model.User.get(user_dict['id'])
    member_dict = {
        'username': user.id,
        'id': data['group_id'],
        'role': data['role']
    }
    toolkit.get_action('group_member_create')(context, member_dict)

    if group.is_organization:
        group_dict = toolkit.get_action('organization_show')(context,
            {'id': data['group_id']})
    else:
        group_dict = toolkit.get_action('group_show')(context,
            {'id': data['group_id']})

    mailer.create_reset_key(user)

    # Email body
    group_type = (toolkit._('organization') if group_dict['is_organization']
                  else toolkit._('group'))
    role = data['role']
    extra_vars = {
        'reset_link': mailer.get_reset_link(user),
        'site_title': config.get('ckan.site_title'),
        'site_url': config.get('ckan.site_url'),
        'user_name': user.name,
        'role_name': authz.roles_trans().get(role, toolkit._(role)),
        'group_type': group_type,
        'group_title': group_dict.get('title'),
    }

    # NOTE: This template is translated
    body = render_jinja2('emails/invite_user.txt', extra_vars)
    subject = toolkit._('Invite for {site_title}').format(
        site_title=config.get('ckan.site_title'))

    mailer.mail_user(user, subject, body)

    return model_dictize.user_dictize(user, context)
コード例 #31
0
def mail_user(user, subj, body, headers={}):
    try:
        headers.setdefault('Content-Type', 'text/html; charset=UTF-8')
        core_mailer.mail_user(user, subj, body, headers=headers)
    except Exception as exception:
        log.exception(exception)
コード例 #32
0
ファイル: action.py プロジェクト: rhabbachi/ckanext-issues
def issue_comment_create(context, data_dict):
    '''Add a new issue comment.

    You must provide your API key in the Authorization header.

    :param comment: the comment text
    :type comment: string
    :param issue_number: the number of the issue the comment belongs to
    :type issue_number: integer
    :param dataset_id: the dataset name or id of the issue the comment belongs to
    :type dataset_id: unicode

    :returns: the newly created issue comment
    :rtype: dictionary
    '''
    p.toolkit.check_access('issue_comment_create', context, data_dict)
    user = context['user']
    user_obj = model.User.get(user)

    issue = issuemodel.Issue.get_by_name_or_id_and_number(
        dataset_name_or_id=data_dict['dataset_id'],
        issue_number=data_dict['issue_number'],
        session=context['session'])

    comment_dict = data_dict.copy()
    del comment_dict['dataset_id']
    del comment_dict['issue_number']
    comment_dict.update({
        'user_id': user_obj.id,
        'issue_id': issue.id,
    })

    issue_comment = issuemodel.IssueComment(**comment_dict)
    model.Session.add(issue_comment)
    model.Session.commit()

    notifications = p.toolkit.asbool(
        config.get('ckanext.issues.send_email_notifications'))

    if notifications:
        dataset = model.Package.get(data_dict['dataset_id'])
        recipients = _get_recipients(context, dataset)
        # subject = get_issue_subject(issue.as_dict())
        subject = issue.title

        for recipient in recipients:
            body = _get_comment_email_body(issue_comment, subject, user_obj,
                                           recipient)

            user_recipient = model.User.get(recipient['user_id'])
            try:
                mailer.mail_user(user_recipient, subject, body)
            except (mailer.MailerException, TypeError), e:
                # TypeError occurs when we're running command from ckanapi
                log.debug(e.message)

        # Sending email to author
        if user_obj.id != issue.user.id:
            body = _get_comment_email_body(issue_comment, subject, user_obj,
                                           {})
            try:
                mailer.mail_user(issue.user, subject, body)
            except (mailer.MailerException, TypeError), e:
                # TypeError occurs when we're running command from ckanapi
                log.debug(e.message)
コード例 #33
0
def send_rejected_info(user, package_id, notes):
    body = get_moderation_rejected_link_body(package_id, notes)
    subject = _('Package rejected info from {site_title}').format(
        site_title=g.site_title)
    mail_user(user, subject, body)
コード例 #34
0
ファイル: moderation.py プロジェクト: kchod/ckanext-ceon
def send_rejected_info(user, package_id, notes):
    body = get_moderation_rejected_link_body(package_id, notes)
    subject = _('Package rejected info from {site_title}').format(site_title=g.site_title)
    mail_user(user, subject, body)
コード例 #35
0
ファイル: moderation.py プロジェクト: kchod/ckanext-ceon
def send_moderation_request(user, package_id):
    body = get_moderation_link_body(package_id)
    subject = _('Moderation request from {site_title}').format(site_title=g.site_title)
    mail_user(user, subject, body)
コード例 #36
0
def send_moderation_request(user, package_id):
    body = get_moderation_link_body(package_id)
    subject = _('Moderation request from {site_title}').format(
        site_title=g.site_title)
    mail_user(user, subject, body)