def test_mail_recipient(self): user = factories.User() msgs = self.get_smtp_messages() assert_equal(msgs, []) # send email test_email = {'recipient_name': 'Bob', 'recipient_email': user['email'], 'subject': 'Meeting', 'body': 'The meeting is cancelled.', 'headers': {'header1': 'value1'}} mailer.mail_recipient(**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], [test_email['recipient_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'], test_email['recipient_name']) assert_in(expected_body, msg[3])
def restricted_mail_allowed_user(user_id, resource): log.debug('restricted_mail_allowed_user: Notifying "{}"'.format(user_id)) try: # Get user information context = {} context['ignore_auth'] = True context['keep_email'] = True user = toolkit.get_action('user_show')(context, {'id': user_id}) user_email = user['email'] user_name = user.get('name', user['name']) resource_name = resource.get('name', resource['id']) # maybe check user[activity_streams_email_notifications]==True mail_body = restricted_allowed_user_mail_body(resource, user) mail_subject = _('Αποδοχή αιτήματος πρόσβασης στον πόρο {}').format( resource_name) # Send mail to user mailer.mail_recipient(user_name, user_email, mail_subject, mail_body) # Send copy to admin (temporarily disabled) #mailer.mail_recipient( # 'CKAN Admin', config.get('email_to'), # 'Fwd: {}'.format(mail_subject), mail_body) except Exception as e: log.warning(('restricted_mail_allowed_user: '******'Failed to send mail to "{0}": {1}').format(user_id, e))
def callback(self): user = model.User.get('admin') context = { 'model': model, 'user': '******', 'session': model.Session, 'for_view': True } cid = request.params.get('comment_id') comment = request.params.get('comment') id = request.params.get('pkg_id') if id != "": data_dict = {} data_dict["id"] = id pkg = logic.get_action('package_show')(context, data_dict) callback_field = config.get('disqus.callback.field', "None") mail_sent = 0 if callback_field in pkg and pkg.get(callback_field) <> None: url = request.host_url + toolkit.url_for( controller='package', action='read', id=id) msg = u'Zum Datensatz mit der ID %s - "%s"\r\n wurde ein neuer Kommentar mit folgendem Inhalt abgegeben:\r\n\r\n"%s"\r\n\r\nLink zum Datensatz: %s\r\n\r\nHinweis: Sie erhalten diese Email, weil Ihre Email-Adresse beim Datensatz "%s" als Kontaktmöglichkeit angegeben wurde. Wenn Sie dies ändern möchten, kontaktieren Sie bitte Ihre Open-Data-Koordinierungsstelle. ' % ( id, pkg["title"], comment, url, pkg["title"]) mailer.mail_recipient('Datenverantwortliche/r', pkg.get(callback_field, ""), 'Neuer Kommentar zum Datensatz', msg) mail_sent = 1 data = {'comment_id': cid, 'pkg_id': id, 'mail_sent': mail_sent} return render('disqus_callback.html', data)
def handle_submit(self, id): data = clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.params)))) data['dataset_url'] = toolkit.url_for( controller='package', action='read', id=id, qualified=True ) package = get_action('package_show')(None, {'id': id}) self.fail_if_private(package, data['dataset_url']) # Comma separated config var to_addrs = config['ckanext.ands.support_emails'].split(',') subject = 'DataPortal Support: Request to publish dataset' body = base.render( 'package/doi_email.text', extra_vars=data) for email in to_addrs: mail_recipient('Dataportal support', email, subject, body) data['package_id'] = package['id'] data['user_id'] = c.userobj.id doi_request = DoiRequest(**data) Session.add(doi_request) Session.commit() h.flash_success("DOI Request sent") return toolkit.redirect_to(data['dataset_url'])
def send_email(to_name, to_email, subject, content): """ This function sends e-mail """ content = """\ <html> <head></head> <body> """ + content + """ </body> </html> """ try: ckan_mailer.mail_recipient( to_name, to_email, subject, content, headers={'Content-Type': 'text/html; charset=utf-8'}) return { 'success': True, 'message': _('Email message was successfully sent.') } except Exception as e: log.exception(e) return { 'success': False, 'message': _('An error occured while sending the email. Try again.') }
def unpublish_dataset(context, pkg, data={}): reason = data.get('reason', 'Not defined') subject = 'SEED dataset was unpublished' author = model.User.get(pkg['creator_user_id']) message = ("The SEED dataset {title} ({dataset_url})" " has been unpublished by {admin}.\n" "Reason:\n" "{reason}") try: if author is None: raise Exception('User <{0}> not found'.format( pkg['creator_user_id'])) if not author.email: raise Exception('User <{0}> has no email'.format(author.name)) mailer.mail_recipient( author.fullname or author.name, author.email, subject, message.format(title=pkg['title'], dataset_url=helpers.url_for('dataset_read', id=pkg['id'], qualified=True), admin=context['user'], reason=reason)) except Exception as e: log.error('[workflow email] {0}'.format(e))
def test_mail_recipient(self, mail_server): user = factories.User() msgs = mail_server.get_smtp_messages() assert msgs == [] # send email test_email = { "recipient_name": "Bob", "recipient_email": user["email"], "subject": "Meeting", "body": "The meeting is cancelled.\n", "headers": { "header1": "value1" }, } mailer.mail_recipient(**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] == [test_email["recipient_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] assert msg[3].startswith('Content-Type: text/plain'), msg[3] expected_body = self.mime_encode(test_email["body"], test_email["recipient_name"]) assert expected_body in msg[3]
def _save_new_pending(self, context): params = request.params password = str(binascii.b2a_hex(os.urandom(15))) data = dict( fullname = params['fullname'], name = params['name'], password1 = password, password2 = password, state = model.State.PENDING, email = params['email'], organization_request = params['organization-for-request'], reason_to_access = params['reason-to-access'] ) organization = model.Group.get(data['organization_request']) try: user_dict = logic.get_action('user_create')(context, data) context1 = { 'user': model.Session.query(model.User).filter_by(sysadmin=True).first().name } msg = "Dear Admin,\n\nA request for a new user account has been submitted:\nUsername: "******"\nName: " + data['fullname'] + "\nEmail: " + data['email'] + "\nOrganisation: " + organization.display_name + "\nReason for access: " + data['reason_to_access'] + "\n\nThis request can be approved or rejected at " + g.site_url + h.url_for(controller='ckanext.accessrequests.controller:AccessRequestsController', action='account_requests') mailer.mail_recipient('Admin', config.get('ckanext.accessrequests.approver_email'), 'Account request', msg) h.flash_success('Your request for access to the {0} has been submitted.'.format(config.get('ckan.site_title'))) except ValidationError, e: # return validation failures to the form errors = e.error_dict error_summary = e.error_summary return self.request_account(data, errors, error_summary)
def test_from_field_format(self, mail_server): msgs = mail_server.get_smtp_messages() assert msgs == [] # send email test_email = { "recipient_name": "Bob", "recipient_email": "*****@*****.**", "subject": "Meeting", "body": "The meeting is cancelled.", "headers": { "header1": "value1" }, } mailer.mail_recipient(**test_email) # check it went to the mock smtp server msgs = mail_server.get_smtp_messages() msg = msgs[0] expected_from_header = "{0} <{1}>".format( config.get("ckan.site_title"), config.get("smtp.mail_from")) assert expected_from_header in msg[3]
def handle_submit(self, id): data = clean_dict( dict_fns.unflatten(tuplize_dict(parse_params(request.params)))) data['dataset_url'] = toolkit.url_for(controller='package', action='read', id=id, qualified=True) package = get_action('package_show')(None, {'id': id}) self.fail_if_private(package, data['dataset_url']) # Comma separated config var to_addrs = config['ckanext.ands.support_emails'].split(',') subject = 'DataPortal Support: Request to publish dataset' body = base.render('package/doi_email.text', extra_vars=data) for email in to_addrs: mail_recipient('Dataportal support', email, subject, body) data['package_id'] = package['id'] data['user_id'] = c.userobj.id doi_request = DoiRequest(**data) Session.add(doi_request) Session.commit() h.flash_success("DOI Request sent") return toolkit.redirect_to(data['dataset_url'])
def send_email(request, zip_name): ''' Sends an email to the email address in the passed request informing them that a download has completed and providing them with a link to go get it from. :param request: the DownloadRequest object :param zip_name: the name of the zip file that has been created ''' download_url = u'{}/downloads/{}'.format(toolkit.config.get(u'ckan.site_url'), zip_name) # create the default download email body using the url body = default_body.format(url=download_url) # allow plugins to override the middle section of the email with any additional details extras = [] for plugin in PluginImplementations(IVersionedDatastoreDownloads): extra_body = plugin.download_add_to_email_body(request) if extra_body: extras.append(extra_body) if extras: body = body.format(extras=u'\n{}\n'.format(u'\n\n'.join(extras))) else: # this is necessary as it removes the {extras} placeholder in the default body text body = body.format(extras=u'') mailer.mail_recipient(recipient_email=request.email_address, recipient_name=u'Downloader', subject=u'Data download', body=body)
def send_notifications(): ''' Sends notification emails to site users of dataset changes The user needs to subscribe to the dataset to receive emails ''' subscribed_users = Reminder.get_subscribed_users() for subscriber in subscribed_users: updated_packages = get_updated_packages_for_user( subscriber.id, subscriber.as_dict()['previous_reminder_sent']) stringified_updated_packages_list = '' for package in updated_packages: stringified_updated_packages_list += config.get( 'ckanext.reminder.site_url') + '/dataset/' + package.get( 'name') + '\n' if len(updated_packages) > 0: message_body = _('The following datasets have been updated') + ':\n' + stringified_updated_packages_list + \ '\nUnsubscribe from this newsletter: ' + config.get('ckanext.reminder.site_url') + '/reminder/' + \ subscriber.subscriber_email + '/unsubscribe/' + subscriber.unsubscribe_token mail_recipient("", subscriber.subscriber_email, _('Dataset has been updated'), message_body) Reminder.update_previous_reminder_sent(subscriber.subscriber_email) log.info("Notification emails sent")
def restricted_mail_allowed_user(user_id, resource): log.debug('restricted_mail_allowed_user notifying {0}'.format(user_id)) try: # Get user information context = {} context['ignore_auth'] = True context['keep_email'] = True user = toolkit.get_action('user_show')(context, {'id': user_id}) user_email = user['email'] user_name = user.get('display_name', user['name']) resource_name = resource.get('name', resource['id']) # maybe check user[activity_streams_email_notifications]==True mail_body = restricted_allowed_user_mail_body(user, resource) mail_subject = 'Access granted to resource {0}'.format(resource_name) # Send mail to user mailer.mail_recipient(user_name, user_email, mail_subject, mail_body) # Sendo copy to admin mailer.mail_recipient('CKAN Admin', config.get('email_to'), 'Fwd: ' + mail_subject, mail_body) except: log.warning( 'restricted_mail_allowed_user: Failed to send mail to "{0}"'. format(user_id))
def send_email(request, zip_name): ''' Sends an email to the email address in the passed request informing them that a download has completed and providing them with a link to go get it from. :param request: the DownloadRequest object :param zip_name: the name of the zip file that has been created ''' # get the templates as strings templates = (default_body, default_html_body) for plugin in PluginImplementations(IVersionedDatastoreDownloads): templates = plugin.download_modify_email_templates(*templates) site_url = toolkit.config.get('ckan.site_url') context = { 'site_url': site_url, 'download_url': f'{site_url}/downloads/{zip_name}', } # allow plugins to modify the context passed to the templates for plugin in PluginImplementations(IVersionedDatastoreDownloads): context = plugin.download_modify_email_template_context( request, context) # render both templates body, body_html = (Template(template).render(**context) for template in templates) # vend mailer.mail_recipient(recipient_email=request.email_address, recipient_name='Downloader', subject='Data download', body=body, body_html=body_html)
def send_reminders(): ''' Sends reminder emails to site admin of datasets which have a reminder date set ''' items = get_datasets_with_reminders() try: recipient_email_default = config.get('ckanext.reminder.email') email_field_name = config.get('ckanext.reminder.email_field') if (items['results']): log.debug('Number of datasets with reminders found: ' + str(len(items['results']))) else: log.debug('No datasets found with reminder set to current date') for item in items['results']: if (email_field_name in item and item[email_field_name] != ""): recipient_email = item[email_field_name] else: recipient_email = recipient_email_default message_body = _( 'This is a reminder of a dataset expiration' ) + ': ' + config.get( 'ckanext.reminder.site_url') + '/dataset/' + item['name'] try: mail_recipient(recipient_email, recipient_email, _('CKAN reminder'), message_body) except MailerException, ex: log.error( "There was an error with sending email to the following address: " + recipient_email) log.exception(ex) log.debug("Reminder emails processed")
def feedbackProv1(self): # assert type(['*****@*****.**'])==list requestHandler = config.get( 'ckan.feedback.request_email', "*****@*****.**" ) # this should read from config file or send email to default senderEmail = config.get( 'ckan.feedback.sender_email', "*****@*****.**" ) # this should read from config file or send email from default msg = MIMEMultipart() msg['From'] = senderEmail msg['To'] = requestHandler msg['Date'] = formatdate(localtime=True) msg['Subject'] = "Dataset Request for " + request.params['datasetName'] dataRequest = "User Name: " + request.params[ 'name'] + "\nUser Email: " + request.params[ 'email'] + "\nOrganization Name: " + request.params[ 'organization'] + "\nDataset Name: " + request.params[ 'datasetName'] + "\nDataset Description: " + request.params[ 'description'] msg.attach(MIMEText(dataRequest)) email_subject = "Dataset Request for " + request.params['datasetName'] email_name = request.params['name'] email_body = msg.as_string() try: mailer.mail_recipient(email_name, requestHandler, email_subject, email_body) except mailer.MailerException: raise return p.toolkit.render('feedbackProv.html')
def _send_suggestion(self, context): try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.suggest_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["suggestion"] == ''): errors['suggestion'] = [u'Missing Value'] error_summary['suggestion'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. mail_to = config.get('email_to') recipient_name = 'CKAN Surrey' subject = 'CKAN - Dataset suggestion' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) if (data_dict["category"] != ''): body += 'Category: %s' % data_dict["category"] body += 'Request: %s' % data_dict["suggestion"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('suggest/suggest_success.html')
def _send_notification(self, dataset_url, dataset_update_url, dataset_title, user): subject = u'CKAN: Потсетување за ажурирање на податочниот сет „{title}“ | '\ u'Kujtesë për përditësimin e të dhënave "{title}" | '\ u'Reminder to update dataset "{title}"'.format(title=dataset_title) try: body = _load_resource_from_path( 'ckanext.datagovmk:templates/datagovmk/outdated_dataset_email.html' ).format( **{ 'username': user['username'], 'dataset_url': dataset_url, 'dataset_title': dataset_title, 'dataset_update_url': dataset_update_url, 'site_title': config.get('ckan.site_title', 'CKAN') }) ckan_mailer.mail_recipient(user['email'], user['email'], subject, body, headers={ 'Content-Type': 'text/html; charset=UTF-8', }) except ckan_mailer.MailerException as e: log.error( 'Failed to send notification message for updating the obsolete dataset %s: %s', dataset_title, e)
def test_from_field_format(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) # send email test_email = { 'recipient_name': 'Bob', 'recipient_email': '*****@*****.**', 'subject': 'Meeting', 'body': 'The meeting is cancelled.', 'headers': { 'header1': 'value1' } } mailer.mail_recipient(**test_email) # check it went to the mock smtp server msgs = self.get_smtp_messages() msg = msgs[0] expected_from_header = '{0} <{1}>'.format( config.get('ckan.site_title'), config.get('smtp.mail_from')) assert_in(expected_from_header, msg[3])
def request_validation(admin, admin_email, resource_url): ''' Send request to specific user for data resource validation :param admin: The admin username :type admin: string :param admin_email: The admin email :type admin_email: string :param resource_url: The full URL to the resource :type resource_url: string ''' if not admin: raise MailerException(_('Admin username not provided')) if not admin_email: raise MailerException(_('Admin email not provided')) if not resource_url: raise MailerException(_('Resource URL not provided')) site_title = config.get('ckan.site_title') body = render_jinja2('emails/request_access_body.txt', { 'resource_url': resource_url, 'site_title': site_title, 'user_name': admin }) subject = render_jinja2('emails/request_access_subject.txt', {'site_title': site_title}) subject = subject.split('\n')[0] mailer.mail_recipient(admin, admin_email, subject, body, headers={})
def notify_users(context, pkg_dict, harvester_type="mimu"): """ :param context: :param pkg_dict: :param harvester_type: :return: """ _users_to_notify = get_users_for_group(context, pkg_dict.get('owner_org')) try: pkg_title = json.loads(pkg_dict.get('title_translated', {})).get('en', 'NA') except Exception as e: log.error(e) pkg_title = "NA" for user in _users_to_notify: if user['capacity'] in _roles_to_send_email: _user_object = model.User.get(user['id']) user_fullname = _user_object.fullname user_email = _user_object.email email_dict = get_email_dict(harvester_type, user_fullname, pkg_title, pkg_dict['id']) mail_recipient( user_fullname, user_email, email_dict['subject'].strip(), email_dict['body'].strip() ) return None
def test_mail_recipient(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) # send email test_email = {'recipient_name': 'Bob', 'recipient_email':'*****@*****.**', 'subject': 'Meeting', 'body': 'The meeting is cancelled.', 'headers': {'header1': 'value1'}} mail_recipient(**test_email) time.sleep(0.1) # 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['ckan.mail_from']) assert_equal(msg[2], [test_email['recipient_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'], test_email['recipient_name']) assert expected_body in msg[3], '%r not in %r' % (expected_body, msg[3])
def _send_comment_notification_mail(recipient_name, recipient_email, data, lang="en"): ''' A helper function to send notification emails to given recipients ''' current_locale = get_lang() if lang: set_lang(lang) from ckanext.datarequests import email_template # recreate the request url url = str(g.site_url) + tk.url_for( controller= 'ckanext.datarequests.controllers.ui_controller:DataRequestsUI', action='show', id=data.get("request_id")) data["link"] = url # fill out the email template subject = email_template.subject.format(**data) message = email_template.message.format(**data) # Finally mail the user and reset locale try: mail_recipient(recipient_name, recipient_email, subject, message) except MailerException, e: log.error(e)
def _save_on_fail(self, data): """ Handle a failure to create an issue by emailing the details to the configured email address """ from ckan.lib.mailer import mail_recipient addresses = config.get('ckanext.redmine.error_email', '').split(',') if not addresses: log.error("No backup email address to save data: {0}".format(data)) return email_msg = """ REDMINE server not available Sender: {0} Email: {1} Subject: {2} Message: {3} """.format(data.get('name'), data.get('email'),data.get('subject'), data.get('message')) for recipient in addresses: mail_recipient(recipient, recipient, "ckanext-redmine failure", email_msg)
def _approval_preparation(context, pkg, message, data={}): reason = data.get('reason', 'Not defined') subject = data.get('subject', '') author = model.User.get(pkg['creator_user_id']) type = 'SEED dataset' if workflow_helpers.get_original_dataset_id_from_package(pkg): type = 'revision for SEED dataset' if 'dataset_url' not in data: dataset_url = helpers.url_for('dataset_read', id=pkg['id'], qualified=True) else: dataset_url = data['dataset_url'] try: if author is None: raise Exception('User <{0}> not found'.format( pkg['creator_user_id'])) if not author.email: raise Exception('User <{0}> has no email'.format(author.name)) mailer.mail_recipient( author.fullname or author.name, author.email, subject, message.format(type=type, title=pkg['title'], dataset_url=dataset_url, admin=context['user'], reason=reason)) except Exception as e: log.error('[workflow email] {0}'.format(e))
def restricted_mail_allowed_user(user_id, resource): # Get user information context = {} context['ignore_auth'] = True context['keep_email'] = True user = toolkit.get_action('user_show')(context, {'id': user_id}) user_email = user['email'] user_name = Header(u'"{}"'.format(user.get('display_name', user['name'])), 'utf-8').encode('utf-8') resource_name = resource.get('name', resource['id']) mail_body = restricted_allowed_user_mail_body(user, resource) mail_subject = ( 'Access granted to resource {}'.format(resource_name).encode('utf-8')) admin_email = config.get('email_to') try: # Send mail to user mailer.mail_recipient(user_name, user_email, mail_subject, mail_body, headers={'Reply-To': admin_email}) except: log.error('Failed to send mail to "{}"'.format(user_email)) try: # Send a copy to admin mailer.mail_recipient('CKAN Admin', admin_email, 'Fwd: {}'.format(mail_subject), mail_body) except: log.error('Failed to send mail to "{}"'.format(admin_email))
def test_mail_recipient(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) # send email test_email = { "recipient_name": "Bob", "recipient_email": "*****@*****.**", "subject": "Meeting", "body": "The meeting is cancelled.", "headers": {"header1": "value1"}, } mailer.mail_recipient(**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], [test_email["recipient_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"], test_email["recipient_name"]) assert expected_body in msg[3], "%r not in %r" % (expected_body, msg[3])
def send_email(to, subject, body): """ Use CKAN mailer logic to send an email to an individual email address :param to: string :param subject: string :param body: string :return: """ import ckan.lib.mailer as mailer # Attempt to send mail. mail_dict = { 'recipient_email': to, 'recipient_name': to, 'subject': subject, 'body': body, 'headers': { 'reply-to': config.get('smtp.mail_from') } } try: mailer.mail_recipient(**mail_dict) except mailer.MailerException: log.error(u'Cannot send email notification to %s.', to, exc_info=1)
def _send_comment_notification_mail(recipient_name, recipient_email, data, lang="en"): ''' A helper function to send notification emails to given recipients ''' current_locale = get_lang() if lang: set_lang(lang) from ckanext.datarequests import email_template # recreate the request url url = str(g.site_url) + tk.url_for(controller='ckanext.datarequests.controllers.ui_controller:DataRequestsUI', action='show', id=data.get("request_id")) data["link"] = url # fill out the email template subject = email_template.subject.format(**data) message = email_template.message.format(**data) # Finally mail the user and reset locale try: mail_recipient(recipient_name, recipient_email, subject, message) except MailerException, e: log.error(e)
def test_reply_to(self, mail_server): msgs = mail_server.get_smtp_messages() assert msgs == [] # send email test_email = { "recipient_name": "Bob", "recipient_email": "*****@*****.**", "subject": "Meeting", "body": "The meeting is cancelled.", "headers": { "header1": "value1" }, } mailer.mail_recipient(**test_email) # check it went to the mock smtp server msgs = mail_server.get_smtp_messages() msg = msgs[0] expected_from_header = "Reply-to: {}".format( config.get_value("smtp.reply_to")) assert expected_from_header in msg[3]
def _save_new_pending(self, context): params = request.params password = str(binascii.b2a_hex(os.urandom(15))) data = dict(fullname=params['fullname'], name=params['name'], password1=password, password2=password, state=model.State.PENDING, email=params['email'], organization_request=params['organization-for-request'], reason_to_access=params['reason-to-access']) organization = model.Group.get(data['organization_request']) try: user_dict = logic.get_action('user_create')(context, data) msg = "A request for a new user account has been submitted:\nUsername: "******"\nName: " + data['fullname'] + "\nEmail: " + data[ 'email'] + "\nOrganisation: " + organization.display_name + "\nReason for access: " + data[ 'reason_to_access'] + "\n\nThis request can be approved or rejected at " + g.site_url + h.url_for( controller= 'ckanext.accessrequests.controller:AccessRequestsController', action='account_requests') mailer.mail_recipient( 'Admin', config.get('ckanext.accessrequests.approver_email'), 'Account request', msg) h.flash_success( 'Your request for access to the {0} has been submitted.'. format(config.get('ckan.site_title'))) except ValidationError, e: # return validation failures to the form errors = e.error_dict error_summary = e.error_summary return self.request_account(data, errors, error_summary)
def test_mail_recipient(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) # send email test_email = { 'recipient_name': 'Bob', 'recipient_email': '*****@*****.**', 'subject': 'Meeting', 'body': 'The meeting is cancelled.', 'headers': { 'header1': 'value1' } } mail_recipient(**test_email) time.sleep(0.1) # 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['ckan.mail_from']) assert_equal(msg[2], [test_email['recipient_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'], test_email['recipient_name']) assert expected_body in msg[3], '%r not in %r' % (expected_body, msg[3])
def _send_application( self, group, reason ): from ckan.logic.action import error_summary from ckan.lib.mailer import mail_recipient from genshi.template.text import NewTextTemplate from pylons import config if not reason: h.flash_error(_("There was a problem with your submission, \ please correct it and try again")) errors = {"reason": ["No reason was supplied"]} return self.apply(group.id, errors=errors, error_summary=error_summary(errors)) # look for publisher admins up the tree recipients = [] recipient_publisher = None for publisher in go_up_tree(group): admins = publisher.members_of_type(model.User, 'admin').all() if admins: recipients = [(u.fullname,u.email) for u in admins] recipient_publisher = publisher.title break if not recipients: if not config.get('dgu.admin.email'): log.error('User "%s" prevented from applying for publisher access for "%s" ' 'because: dgu.admin.email is not setup in CKAN config.', c.user, group.name) h.flash_error(_("There is a problem with the system configuration")) errors = {"reason": ["%s does not have an administrator user to contact" % group.name]} return self.apply(group.id, data=data, errors=errors, error_summary=error_summary(errors)) recipients = [(config.get('dgu.admin.name', "DGU Admin"), config['dgu.admin.email'])] recipient_publisher = 'data.gov.uk admin' log.debug('User "%s" requested publisher access for "%s" which was sent to admin %s (%r) with reason: %r', c.user, group.name, recipient_publisher, recipients, reason) extra_vars = { 'group' : group, 'requester': c.userobj, 'reason' : reason } email_msg = render("email/join_publisher_request.txt", extra_vars=extra_vars, loader_class=NewTextTemplate) try: for (name,recipient) in recipients: mail_recipient(name, recipient, "Publisher request", email_msg) except Exception, e: h.flash_error(_("There is a problem with the system configuration")) errors = {"reason": ["No mail server was found"]} log.error('User "%s" prevented from applying for publisher access for "%s" because of mail configuration error: %s', c.user, group.name, e) return self.apply(group.id, errors=errors, error_summary=error_summary(errors))
def mail_user(self, recipient, subject, body, headers={}): if (recipient['email'] is None) or not len(recipient['email']): raise MailerException(_("No recipient email address available!")) mailer.mail_recipient(recipient['display_name'], recipient['email'], subject, body, headers=headers)
def send_activate_user_notification(): # TODO @palcu: remove hardcoded value recipient_name = 'CKAN Gov Admin' recipient_email = '*****@*****.**' subject = 'Activate CKAN User' # TODO @palcu: i18n and remove hardcoded stuff body = "Please go an activate the new users: {0}.".format('http://data.local.gov.ro:5000/inventory/admin') mailer.mail_recipient(recipient_name, recipient_email, subject, body)
def account_requests_management(self): ''' Approve or reject an account request ''' action = request.params['action'] user_id = request.params['id'] user_name = request.params['name'] user = model.User.get(user_id) #user_email = logic.get_action('user_show')({},{'id': user_id}) context1 = { 'user': model.Session.query(model.User).filter_by(sysadmin=True).first().name } org = logic.get_action('organization_list_for_user')({'user': user_name}, {'permission': 'read'}) if org: user_delete = { 'id': org[0]['name'], 'object': user_name, 'object_type': 'user' } context = { 'model': model, 'user': c.user, 'session': model.Session, } activity_create_context = { 'model': model, 'user': user_name, 'defer_commit': True, 'ignore_auth': True, 'session': model.Session } activity_dict = { 'user_id': c.userobj.id, 'object_id': user_id } if action == 'forbid': object_id_validators['reject new user'] = user_id_exists activity_dict['activity_type'] = 'reject new user' logic.get_action('activity_create')(activity_create_context, activity_dict) # remove user, {{'user_email': user_email}} logic.get_action('user_delete')(context1, {'id':user_id}) mailer.mail_recipient(user.name, user.email, 'Account request', 'Your account request has been denied.') elif action == 'approve': object_id_validators['approve new user'] = user_id_exists activity_dict['activity_type'] = 'approve new user' logic.get_action('activity_create')(activity_create_context, activity_dict) # Send invitation to complete registration try: mailer.send_invite(user) except Exception as e: log.error('Error emailing invite to user: %s', e) abort(500, _('Error: couldn''t email invite to user')) response.status = 200 return render('admin/account_requests_management.html')
def send_inactive_users_email(context, data_dict): '''Sends the inactive users list to all site system administrators''' # Remove hours, minutes, and seconds from dates def format_dates(date): date = datetime.strptime( date, '%Y-%m-%dT%H:%M:%S.%f') date = '{}-{}-{}'.format( date.year, date.month, date.day) return date user_list = ckan.logic.get_action('user_list')(context, data_dict) admin_list = [user for user in user_list if user['sysadmin'] is True] inactive_users = ckan.logic.get_action( 'inactive_users')(context, data_dict) number_of_users = len(inactive_users) if not inactive_users: inactive_users_email = \ 'Hello {},\n\nThere are no inactive users to report this week.' else: inactive_users_email = \ 'Hello {},\n\nThere are currently {} inactive users:\n\n' # Format the inactive users list for better readability in an email for user in inactive_users: inactive_users_email += """ Profile URL: {} Last activity date: {} Account creation date: {} Full name: {} Email address: {}\n """.format( '{}/user/{}'.format(config.get('ckan.site_url'), user['name']), format_dates(user['last_activity']), format_dates(user['created']), user['fullname'], user['email']) for admin in admin_list: email = admin['email'] # Check names available - since some of these might be None, # we go in order of preference name_options = [ name for name in [ admin['fullname'], admin['display_name'], admin['name']] if name not in [None, '']] if email: mailer.mail_recipient( name_options[0], email, 'Inactive users list - weekly update', inactive_users_email.format(name_options[0], number_of_users))
def _send_suggestion(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) # return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.suggest_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["suggestion"] == ''): errors['suggestion'] = [u'Missing Value'] error_summary['suggestion'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. mail_to = config.get('email_to') recipient_name = 'CKAN Surrey' subject = 'CKAN - Dataset suggestion' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) if (data_dict["category"] != ''): body += 'Category: %s' % data_dict["category"] body += 'Request: %s' % data_dict["suggestion"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('suggest/suggest_success.html')
def _send_contact(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.contact_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["content"] == ''): errors['content'] = [u'Missing Value'] error_summary['content'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: mail_to = config.get('email_to') recipient_name = 'CKAN' subject = 'CKAN - Contact/Question from visitor' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) body += 'Request: %s' % data_dict["content"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('contact/success.html')
def _notify(issue): # Depending on configuration, and availability of data we # should email the admin and the publisher/ notify_admin = config.get("ckanext.issues.notify_admin", False) notify_owner = config.get("ckanext.issues.notify_owner", False) if not notify_admin and not notify_owner: return from ckan.lib.mailer import mail_recipient from genshi.template.text import NewTextTemplate admin_address = config.get('email_to') # from_address = config.get('ckanext.issues.from_address', # '*****@*****.**') publisher = issue.package.get_groups('publisher')[0] if 'contact-address' in issue.package.extras: contact_name = issue.package.extras.get('contact-name') contact_address = issue.package.extras.get('contact-email') else: contact_name = publisher.extras.get('contact-name', 'Publisher') contact_address = publisher.extras.get('contact-email') # Send to admin if no contact address, and only cc admin if # they are not also in the TO field. to_address = contact_address or admin_address cc_address = admin_address if contact_address else None extra_vars = { 'issue': issue, 'username': issue.reporter.fullname or issue.reporter.name, 'site_url': h.url_for( controller='ckanext.issues.controller:IssueController', action='issue_page', package_id=issue.package.name, qualified=True ) } email_msg = render("issues/email/new_issue.txt", extra_vars=extra_vars, loader_class=NewTextTemplate) headers = {} if cc_address: headers['CC'] = cc_address try: if not contact_name: contact_name = publisher.title mail_recipient(contact_name, to_address, "Dataset issue", email_msg, headers=headers) except Exception: log.error('Failed to send an email message for issue notification')
def email_log(log_type, msg): import ckan.lib.mailer as mailer email_address = config.get('email_to') email = {'recipient_name': email_address, 'recipient_email': email_address, 'subject': log_type + ' Log', 'body': msg, } try: mailer.mail_recipient(**email) except Exception: pass
def _submit(context): try: data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) errors = {} error_summary = {} if data_dict["email"] == '': errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if data_dict["name"] == '': errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if data_dict["content"] == '': errors['content'] = [u'Missing Value'] error_summary['content'] = u'Missing value' if len(errors) == 0: body = '%s' % data_dict["content"] body += '\n\nSent by:\nName:%s\nEmail: %s\n' % (data_dict["name"], data_dict["email"]) mail_dict = { 'recipient_email': config.get("ckanext.contact.mail_to", config.get('email_to')), 'recipient_name': config.get("ckanext.contact.recipient_name", config.get('ckan.site_title')), 'subject': config.get("ckanext.contact.subject", 'Contact/Question from visitor'), 'body': body, 'headers': {'reply-to': data_dict["email"]} } # Allow other plugins to modify the mail_dict for plugin in p.PluginImplementations(IContact): plugin.mail_alter(mail_dict, data_dict) try: mailer.mail_recipient(**mail_dict) except (mailer.MailerException, socket.error): h.flash_error(_(u'Sorry, there was an error sending the email. Please try again later')) else: data_dict['success'] = True return data_dict, errors, error_summary
def send_mail(recipients, subject, body): if recipients and len(recipients) > 0: 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: for recipient in recipients: mailer.mail_recipient(recipient['display_name'], recipient['email'], 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 ')
def test_basic(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) test_email = {'recipient_name': 'Bob', 'recipient_email':'*****@*****.**', 'subject': 'Meeting', 'body': 'The meeting is cancelled.', 'headers': {'header1': 'value1'}} mail_recipient(**test_email) time.sleep(0.1) msgs = self.get_smtp_messages() assert_equal(len(msgs), 1)
def email_log(log_type, msg): import ckan.lib.mailer as mailer email_address = config.get("email_to") email = { "recipient_name": email_address, "recipient_email": email_address, "subject": log_type + " Log", "body": msg, } try: mailer.mail_recipient(**email) except Exception: pass
def send_comment_notification_mail(recipient_name, recipient_email, dataset, comment): from ckanext.ytp_comments import email_template # Fill out the message template url = str(g.site_url) + toolkit.url_for(controller='package', action='read', id=dataset.id) if comment.user_id: userobj = model.User.get(comment.user_id) commenter_email = userobj.email commenter_name = userobj.name subject_vars = { 'dataset': dataset.title } subject = email_template.subject.format(**subject_vars) message_vars = { 'user': commenter_name, 'email': commenter_email, 'dataset': dataset.title, 'link': url, 'comment_subject': helpers.markdown_extract(comment.subject).strip(), 'comment': helpers.markdown_extract(comment.comment).strip() } message = email_template.message.format(**message_vars) log.debug(subject) log.debug(message) # Locale fix current_locale = get_lang() locale = _get_safe_locale() if locale == 'en': _reset_lang() else: set_lang(locale) # Finally mail the user and reset locale try: log.debug("LOCALE: " + str(locale)) log.debug(subject) log.debug(message) mail_recipient(recipient_name, recipient_email, subject, message) except MailerException, e: log.error(e)
def send_mail(name, email, org, reason = ''): ''' The functionality of sending emails with new user requests has been deprecated. Deprecated since 13.08.2014 - hdx 0.3.6 ''' body = 'New user registration request\n' \ 'Full Name: {fn}\n' \ 'Email: {mail}\n' \ 'Organisation: {org}\n' \ 'Reason: {reason}\n' \ '(This is an automated mail)' \ ''.format(fn=name, mail=email, org=org, reason=reason) mailer.mail_recipient("HDX Registration", "*****@*****.**", "New user registration", body) return
def _submit(self): ''' Take the data in the request params and send an email using them. If the data is invalid or a recaptcha is setup and it fails, don't send the email. :return: a dict of details ''' # this variable holds the status of sending the email email_success = True # pull out the data from the request data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params( request.params)))) # validate the request params errors, error_summary, recaptcha_error = self._validate(data_dict) # if there are not errors and no recaptcha error, attempt to send the email if len(errors) == 0 and recaptcha_error is None: body = u'{}\n\nSent by:\nName: {}\nEmail: {}\n'.format(data_dict[u'content'], data_dict[u'name'], data_dict[u'email']) mail_dict = { u'recipient_email': config.get(u'ckanext.contact.mail_to', config.get(u'email_to')), u'recipient_name': config.get(u'ckanext.contact.recipient_name', config.get(u'ckan.site_title')), u'subject': config.get(u'ckanext.contact.subject', _(u'Contact/Question from visitor')), u'body': body, u'headers': {u'reply-to': data_dict[u'email']} } # allow other plugins to modify the mail_dict for plugin in p.PluginImplementations(IContact): plugin.mail_alter(mail_dict, data_dict) try: mailer.mail_recipient(**mail_dict) except (mailer.MailerException, socket.error): email_success = False return { u'success': recaptcha_error is None and len(errors) == 0 and email_success, u'data': data_dict, u'errors': errors, u'error_summary': error_summary, u'recaptcha_error': recaptcha_error, }
def test_basic(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) test_email = { "recipient_name": "Bob", "recipient_email": "*****@*****.**", "subject": "Meeting", "body": "The meeting is cancelled.", "headers": {"header1": "value1"}, } mail_recipient(**test_email) time.sleep(0.1) msgs = self.get_smtp_messages() assert_equal(len(msgs), 1)
def send_email(contact_name,contact_email,email_msg): log.debug("send_email to %s %s",contact_name,contact_email) headers = {} # if cc_email: # headers['CC'] = cc_email try: mail_recipient(contact_name, contact_email,"Dataset issue",email_msg, headers=headers) except Exception: traceback.print_exc() log.error('Failed to send an email message for issue notification')
def _send_application( self, group, reason ): from genshi.template.text import NewTextTemplate if not reason: h.flash_error(_("There was a problem with your submission, \ please correct it and try again")) errors = {"reason": ["No reason was supplied"]} return self.apply(group.id, errors=errors, error_summary=action.error_summary(errors)) admins = group.members_of_type( model.User, 'admin' ).all() recipients = [(u.fullname,u.email) for u in admins] if admins else \ [(config.get('ckan.admin.name', "CKAN Administrator"), config.get('ckan.admin.email', None), )] if not recipients: h.flash_error(_("There is a problem with the system configuration")) errors = {"reason": ["No group administrator exists"]} return self.apply(group.id, data=data, errors=errors, error_summary=action.error_summary(errors)) extra_vars = { 'group' : group, 'requester': c.userobj, 'reason' : reason } email_msg = render("organizations/email/join_publisher_request.txt", extra_vars=extra_vars, loader_class=NewTextTemplate) try: for (name,recipient) in recipients: mailer.mail_recipient(name, recipient, "Publisher request", email_msg) except: h.flash_error(_("There is a problem with the system configuration")) errors = {"reason": ["No mail server was found"]} return self.apply(group.id, errors=errors, error_summary=action.error_summary(errors)) h.flash_success(_("Your application has been submitted")) h.redirect_to( 'publisher_read', id=group.name)
def email_requestors(dataset_id): requests = Session.query(DoiRequest).filter_by(package_id=dataset_id) subject = 'DataPortal DOI Request approved' data = { 'dataset_url': toolkit.url_for( controller='package', action='read', id=dataset_id, qualified=True) } body = base.render( 'package/doi_request_completed.text', extra_vars=data) for request in requests: user = toolkit.get_action('user_show')(None, {'id': request.user_id}) if user['email']: mail_recipient(user['display_name'], user['email'], subject, body)
def register(self): context = {'model':model,'user': c.user or c.author} self._setup_template_variables(context) log.debug("group: %s" % request.params.get('organization')) log.debug("name: %s" % request.params.get('name')) log.debug("phone: %s" % request.params.get('phone')) log.debug("email: %s" % request.params.get('email')) log.debug("api: %s" % request.params.get('api')) log.debug("sent: %s" % request.params.get('sent')) log.debug("comment: %s" % request.params.get('comment')) if request.params.get('sent'): c.sent = request.params.get('sent') msg = "" msg += u"%s meldet eine api für %s unter: %s!\r\n" % (request.params.get('name'), request.params.get('organization'), request.params.get('api')) msg += u"Kontakt unter: %s und %s\r\n" % (request.params.get('phone'), request.params.get('email')) msg += u"Anmerkungen: %s" % request.params.get('comments') mailer.mail_recipient('data','*****@*****.**','API Request',msg) else: c.sent = 0 return render('home/register_api.html')
def test_from_field_format(self): msgs = self.get_smtp_messages() assert_equal(msgs, []) # send email test_email = {'recipient_name': 'Bob', 'recipient_email': '*****@*****.**', 'subject': 'Meeting', 'body': 'The meeting is cancelled.', 'headers': {'header1': 'value1'}} mailer.mail_recipient(**test_email) # check it went to the mock smtp server msgs = self.get_smtp_messages() msg = msgs[0] expected_from_header = '{0} <{1}>'.format( config.get('ckan.site_title'), config.get('smtp.mail_from') ) assert_in(expected_from_header, msg[3])
def callback(self): user = model.User.get('admin') context = { 'model':model,'user': '******','session':model.Session, 'for_view': True } cid = request.params.get('comment_id') comment = request.params.get('comment') id = request.params.get('pkg_id') if id != "": data_dict = {} data_dict["id"] = id pkg = logic.get_action('package_show')(context, data_dict) callback_field = config.get('disqus.callback.field', "None") mail_sent = 0 if callback_field in pkg and pkg.get(callback_field) <> None: url = request.host_url + toolkit.url_for(controller='package', action='read', id=id) msg = u'Zum Datensatz mit der ID %s - "%s"\r\n wurde ein neuer Kommentar mit folgendem Inhalt abgegeben:\r\n\r\n"%s"\r\n\r\nLink zum Datensatz: %s\r\n\r\nHinweis: Sie erhalten diese Email, weil Ihre Email-Adresse beim Datensatz "%s" als Kontaktmöglichkeit angegeben wurde. Wenn Sie dies ändern möchten, kontaktieren Sie bitte Ihre Open-Data-Koordinierungsstelle. ' % (id, pkg["title"], comment, url, pkg["title"]) mailer.mail_recipient('Datenverantwortliche/r', pkg.get(callback_field, ""), 'Neuer Kommentar zum Datensatz', msg) mail_sent = 1 data = {'comment_id' : cid, 'pkg_id': id, 'mail_sent': mail_sent} return render('disqus_callback.html', data)
def _send_suggestion(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Vous n\'êtes pas autorisé à accéder à cette page')) except captcha.CaptchaError: error_msg = _(u'Mauvais code captcha. Essayez de nouveau') h.flash_error(error_msg) return self.suggest_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Valeur manquante'] error_summary['email'] = u'Valeur manquante' if (data_dict["name"] == ''): errors['name'] = [u'Valeur manquante'] error_summary['name'] = u'Valeur manquante' if (data_dict["suggestion"] == ''): errors['suggestion'] = [u'Valeur manquante'] error_summary['suggestion'] = u'Valeur manquante' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. if data_dict['organization'] == 'all': mail_to = config.get('email_to') else: mail_to = logic.get_action('organization_show')( {}, {'id': data_dict['organization']})['email'] recipient_name = 'Données Quebec'.decode('utf8') subject = 'Suggestion de jeu de données'.decode('utf8') body = 'Soumis par %s (%s)\n' % (data_dict["name"], data_dict["email"]) if (data_dict["category"] != ''): body += 'Catégorie de données: %s'.decode('utf8') % data_dict["category"] body += 'Nature de la demande: %s'.decode('utf8') % data_dict["suggestion"] if (data_dict["usage"] != ''): body += 'Utilisation visée: %s'.decode('utf8') % data_dict["usage"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('suggest/suggest_success.html')
def _send_contact(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Vous n\'êtes pas autorisé à accéder à cette page')) except captcha.CaptchaError: error_msg = _(u'Mauvais code captcha. Veuillez réessayer.') h.flash_error(error_msg) return self.contact_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Valeur manquante'] error_summary['email'] = u'Valeur manquante' if (data_dict["name"] == ''): errors['name'] = [u'Valeur manquante'] error_summary['name'] = u'Valeur manquante' if (data_dict["content"] == ''): errors['content'] = [u'Valeur manquante'] error_summary['content'] = u'Valeur manquante' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: if data_dict['organization'] == 'all': mail_to = config.get('email_to') else: mail_to = logic.get_action('organization_show')( {}, {'id': data_dict['organization']})['email'] recipient_name = 'Données Québec'.decode('utf8') subject = 'Question/commentaire d\'un visiteur'.decode('utf8') body = 'Soumis par %s (%s)\n'.decode('utf8') % (data_dict["name"], data_dict["email"]) body += 'Demande: %s'.decode('utf8') % data_dict["content"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('contact/success.html')