def share(): current_user = get_user(required=True) data = get_json_or_400() assert data.get('users') assert data.get('items') topic = get_entity_or_404(data.get('items')['_id'], 'topics') for user_id in data['users']: user = get_resource_service('users').find_one(req=None, _id=user_id) if not user or not user.get('email'): continue template_kwargs = { 'recipient': user, 'sender': current_user, 'topic': topic, 'url': get_topic_url(topic), 'message': data.get('message'), 'app_name': app.config['SITE_NAME'], } send_email( [user['email']], gettext('From %s: %s' % (app.config['SITE_NAME'], topic['label'])), render_template('share_topic.txt', **template_kwargs), ) return jsonify(), 201
def share(): current_user = get_user(required=True) data = get_json_or_400() assert data.get('users') assert data.get('items') topic = get_entity_or_404(data.get('items')[0]['_id'], 'topics') with app.mail.connect() as connection: for user_id in data['users']: user = get_resource_service('users').find_one(req=None, _id=user_id) if not user or not user.get('email'): continue template_kwargs = { 'recipient': user, 'sender': current_user, 'topic': topic, 'url': '{}/?q={}'.format(app.config['CLIENT_URL'], parse.quote(topic['query'])), 'message': data.get('message'), 'app_name': app.config['SITE_NAME'], } send_email( [user['email']], gettext('From %s: %s' % (app.config['SITE_NAME'], topic['label'])), render_template('share_topic.txt', **template_kwargs), sender=current_user['email'], connection=connection ) return jsonify(), 201
def share(): current_user = get_user(required=True) data = get_json_or_400() assert data.get('users') assert data.get('items') items = [get_entity_or_404(_id, 'items') for _id in data.get('items')] with app.mail.connect() as connection: for user_id in data['users']: user = superdesk.get_resource_service('users').find_one( req=None, _id=user_id) if not user or not user.get('email'): continue template_kwargs = { 'recipient': user, 'sender': current_user, 'items': items, 'message': data.get('message'), } send_email( [user['email']], gettext('From %s: %s' % (app.config['SITE_NAME'], items[0]['headline'])), flask.render_template('share_item.txt', **template_kwargs), sender=current_user['email'], connection=connection) update_action_list(data.get('items'), 'shares') return flask.jsonify(), 201
def send_agenda_notification_email(user, agenda, message, subject, original_agenda, coverage_updates, related_planning_removed, coverage_updated, time_updated): if agenda and user.get('receive_email'): kwargs = dict( message=message, agenda=agenda, dateString=get_agenda_dates( agenda if agenda.get('dates') else original_agenda, date_paranthesis=True), location=get_location_string(agenda), contacts=get_public_contacts(agenda), links=get_links(agenda), is_admin=is_admin_or_internal(user), original_agenda=original_agenda, coverage_updates=coverage_updates, related_planning_removed=related_planning_removed, coverage_updated=coverage_updated, time_updated=time_updated, ) send_email(to=[user['email']], subject=subject, text_body=render_template('agenda_updated_email.txt', **kwargs), html_body=render_template('agenda_updated_email.html', **kwargs))
def send_coverage_request_email(user, message, item): """ Forms and sends coverage request email :param user: User that makes the request :param message: Request message :param item: agenda item that request is made against :return: """ recipients = current_app.config['COVERAGE_REQUEST_RECIPIENTS'].split(',') assert recipients assert isinstance(recipients, list) url = url_for('agenda.item', _id=item, _external=True) name = '{} {}'.format(user.get('first_name'), user.get('last_name')) email = user.get('email') subject = gettext('A new coverage request') text_body = render_template('coverage_request_email.txt', name=name, email=email, message=message, url=url) html_body = render_template('coverage_request_email.html', name=name, email=email, message=message, url=url) send_email(to=recipients, subject=subject, text_body=text_body, html_body=html_body)
def send_coverage_notification_email(user, agenda, wire_item): if user.get('receive_email'): send_email( to=[user['email']], subject=gettext('New coverage'), text_body=render_template('agenda_new_coverage_email.txt', agenda=agenda, item=wire_item), html_body=render_template('agenda_new_coverage_email.html', agenda=agenda, item=wire_item) )
def send_agenda_notification_email(user, agenda, message, subject): if agenda and user.get('receive_email'): send_email( to=[user['email']], subject=subject, text_body=render_template('agenda_updated_email.txt', message=message, item=agenda), html_body=render_template('agenda_updated_email.html', message=message, item=agenda) )
def send_email_alert(self, items, subject, m, recipients): """ Send an email alert with the details in the body of the email. If a logo image is set in the monitoring_report_logo_path settings it will be attached to the email and can be referenced in the monitoring_export.html template as <img src="CID:logo" /> :param items: :param subject: :param m: :param recipients: :return: """ from newsroom.email import send_email general_settings = get_settings_collection().find_one( GENERAL_SETTINGS_LOOKUP) data = { 'date_items_dict': get_date_items_dict(items), 'monitoring_profile': m, 'current_date': utc_to_local(app.config['DEFAULT_TIMEZONE'], utcnow()).strftime('%d/%m/%Y'), 'monitoring_report_name': app.config.get('MONITORING_REPORT_NAME', 'Newsroom') } # Attach logo to email if defined logo = None if general_settings and general_settings['values'].get( 'monitoring_report_logo_path'): image_filename = general_settings['values'].get( 'monitoring_report_logo_path') if os.path.exists(image_filename): with open(image_filename, 'rb') as img: bts = base64.b64encode(img.read()) logo = [{ 'file': bts, 'file_name': 'logo{}'.format(os.path.splitext(image_filename)[1]), 'content_type': 'image/{}'.format( os.path.splitext(image_filename)[1].replace( '.', '')), 'headers': [('Content-ID', '<logo>')] }] send_email(recipients, subject, text_body=render_template('monitoring_export.txt', **data), html_body=render_template('monitoring_export.html', **data), attachments_info=logo)
def share(): current_user = get_user(required=True) item_type = get_type() data = get_json_or_400() assert data.get('users') assert data.get('items') items = get_items_for_user_action(data.get('items'), item_type) for user_id in data['users']: user = superdesk.get_resource_service('users').find_one(req=None, _id=user_id) subject = items[0].get('headline') # If it's an event, 'name' is the subject if items[0].get('event'): subject = items[0]['name'] if not user or not user.get('email'): continue template_kwargs = { 'recipient': user, 'sender': current_user, 'items': items, 'message': data.get('message'), 'section': request.args.get('type', 'wire') } if item_type == 'agenda': template_kwargs['maps'] = data.get('maps') template_kwargs['dateStrings'] = [ get_agenda_dates(item) for item in items ] template_kwargs['locations'] = [ get_location_string(item) for item in items ] template_kwargs['contactList'] = [ get_public_contacts(item) for item in items ] template_kwargs['linkList'] = [get_links(item) for item in items] template_kwargs['is_admin'] = is_admin_or_internal(user) send_email( [user['email']], gettext('From %s: %s' % (app.config['SITE_NAME'], subject)), text_body=flask.render_template('share_{}.txt'.format(item_type), **template_kwargs), html_body=flask.render_template('share_{}.html'.format(item_type), **template_kwargs), ) update_action_list(data.get('items'), 'shares', item_type=item_type) get_resource_service('history').create_history_record( items, 'share', current_user, request.args.get('type', 'wire')) return flask.jsonify(), 201
def worker(self): from newsroom.email import send_email # Check if there are any recipients general_settings = get_settings_collection().find_one(GENERAL_SETTINGS_LOOKUP) try: recipients = general_settings['values']['company_expiry_alert_recipients'].split(',') except KeyError: logger.warning('there are no alert expiry recipients') return expiry_time = (utcnow() + datetime.timedelta(days=7)).replace(hour=0, minute=0, second=0) companies_service = get_resource_service('companies') companies = list(companies_service.find({ 'expiry_date': {'$lte': expiry_time}, 'is_enabled': True })) if len(companies) > 0: # Send notifications to users who are nominated to receive expiry alerts for company in companies: users = get_resource_service('users').find({'company': company.get(config.ID_FIELD), 'expiry_alert': True}) if users.count() > 0: template_kwargs = {'expiry_date': company.get('expiry_date')} logger.info('{} Sending to following users of company {}: {}' .format(self.log_msg, company.get('name'), recipients)) send_email( [u['email'] for u in users], 'Your Company\'s account is expiring on {}'.format( company.get('expiry_date').strftime('%d-%m-%Y') ), text_body=render_template('company_expiry_alert_user.txt', **template_kwargs), html_body=render_template('company_expiry_alert_user.html', **template_kwargs), ) if not (general_settings.get('values') or {}).get('company_expiry_alert_recipients'): return # No one else to send template_kwargs = { 'companies': sorted(companies, key=lambda k: k['expiry_date']), 'expiry_date': expiry_time } logger.info('{} Sending to following expiry administrators: {}'.format(self.log_msg, recipients)) send_email( recipients, 'Companies expired or due to expire within the next 7 days ({})'.format( expiry_time.strftime('%d-%m-%Y') ), text_body=render_template('company_expiry_email.txt', **template_kwargs), html_body=render_template('company_expiry_email.html', **template_kwargs), )
def send_coverage_request_email(user, message, item): """ Forms and sends coverage request email :param user: User that makes the request :param message: Request message :param item: agenda item that request is made against :return: """ general_settings = get_settings_collection().find_one( GENERAL_SETTINGS_LOOKUP) if not general_settings: return recipients = general_settings.get('values').get( 'coverage_request_recipients').split(',') assert recipients assert isinstance(recipients, list) url = url_for_agenda({'_id': item['_id']}, _external=True) name = '{} {}'.format(user.get('first_name'), user.get('last_name')) email = user.get('email') item_name = item.get('name') or item.get('slugline') subject = gettext('Coverage inquiry: {}'.format(item_name)) user_company = get_user_company(user) if user_company: user_company = user_company.get('name') text_body = render_template('coverage_request_email.txt', name=name, email=email, message=message, url=url, company=user_company, recipients=recipients, subject=subject, item_name=item_name) html_body = render_template('coverage_request_email.html', name=name, email=email, message=message, url=url, company=user_company, recipients=recipients, subject=subject, item_name=item_name) send_email(to=recipients, subject=subject, text_body=text_body, html_body=html_body)
def share(): data = get_json_or_400() assert data.get('users') assert data.get('items') assert data.get('monitoring_profile') current_user = get_user(required=True) monitoring_profile = get_entity_or_404(data.get('monitoring_profile'), 'monitoring') items = get_items_for_monitoring_report(data.get('items'), monitoring_profile) for user_id in data['users']: user = get_resource_service('users').find_one(req=None, _id=user_id) template_kwargs = { 'recipient': user, 'sender': current_user, 'message': data.get('message'), 'item_name': 'Monitoring Report', } formatter = app.download_formatters['monitoring_pdf']['formatter'] monitoring_profile['format_type'] = 'monitoring_pdf' _file = get_monitoring_file(monitoring_profile, items) attachment = base64.b64encode(_file.read()) send_email( [user['email']], gettext( 'From %s: %s' % (app.config['SITE_NAME'], monitoring_profile.get( 'subject', monitoring_profile['name']))), text_body=flask.render_template('share_items.txt', **template_kwargs), html_body=flask.render_template('share_items.html', **template_kwargs), attachments_info=[{ 'file': attachment, 'file_name': formatter.format_filename(None), 'content_type': 'application/{}'.format(formatter.FILE_EXTENSION), 'file_desc': 'Monitoring Report' }], ) update_action_list(data.get('items'), 'shares') get_resource_service('history').create_history_record( items, 'share', current_user, 'monitoring') return jsonify({'success': True}), 200
def send_agenda_notification_email(user, agenda, message, subject): if agenda and user.get('receive_email'): kwargs = dict( message=message, item=agenda, dateString=get_agenda_dates(agenda), location=get_location_string(agenda), contacts=get_public_contacts(agenda), links=get_links(agenda), is_admin=is_admin_or_internal(user), ) send_email(to=[user['email']], subject=subject, text_body=render_template('agenda_updated_email.txt', **kwargs), html_body=render_template('agenda_updated_email.html', **kwargs))
def send_coverage_request_email(user, message, item): """ Forms and sends coverage request email :param user: User that makes the request :param message: Request message :param item: agenda item that request is made against :return: """ general_settings = get_settings_collection().find_one( GENERAL_SETTINGS_LOOKUP) if not general_settings: return recipients = general_settings.get('values').get( 'coverage_request_recipients').split(',') assert recipients assert isinstance(recipients, list) url = url_for('agenda.item', _id=item, _external=True) name = '{} {}'.format(user.get('first_name'), user.get('last_name')) email = user.get('email') subject = gettext('A new coverage request') text_body = render_template('coverage_request_email.txt', name=name, email=email, message=message, url=url) html_body = render_template('coverage_request_email.html', name=name, email=email, message=message, url=url) send_email(to=recipients, subject=subject, text_body=text_body, html_body=html_body)
def send_alerts(self, monitoring_list, created_from, created_from_time, now): general_settings = get_settings_collection().find_one( GENERAL_SETTINGS_LOOKUP) error_recipients = [] if general_settings and general_settings['values'].get( 'system_alerts_recipients'): error_recipients = general_settings['values'][ 'system_alerts_recipients'].split(',') from newsroom.email import send_email for m in monitoring_list: if m.get('users'): internal_req = ParsedRequest() internal_req.args = { 'navigation': str(m['_id']), 'created_from': created_from, 'created_from_time': created_from_time, 'skip_user_validation': True } items = list( get_resource_service('monitoring_search').get( req=internal_req, lookup=None)) template_kwargs = {'profile': m} if items: company = get_entity_or_404(m['company'], 'companies') try: template_kwargs.update({ 'items': items, 'section': 'wire', }) truncate_article_body(items, m) _file = get_monitoring_file(m, items) attachment = base64.b64encode(_file.read()) formatter = app.download_formatters[ m['format_type']]['formatter'] # If there is only one story to send and the headline is to be used as the subject if m.get('headline_subject', False) and len(items) == 1: subject = items[0].get( 'headline', m.get('subject') or m['name']) else: subject = m.get('subject') or m['name'] send_email( [ u['email'] for u in get_items_by_id( [ObjectId(u) for u in m['users']], 'users') ], subject, text_body=render_template('monitoring_email.txt', **template_kwargs), html_body=render_template('monitoring_email.html', **template_kwargs), attachments_info=[{ 'file': attachment, 'file_name': formatter.format_filename(None), 'content_type': 'application/{}'.format( formatter.FILE_EXTENSION), 'file_desc': 'Monitoring Report for Celery monitoring alerts for profile: {}' .format(m['name']) }]) except Exception: logger.exception( '{0} Error processing monitoring profile {1} for company {2}.' .format(self.log_msg, m['name'], company['name'])) if error_recipients: # Send an email to admin template_kwargs = { 'name': m['name'], 'company': company['name'], 'run_time': now, } send_email( error_recipients, gettext( 'Error sending alerts for monitoring: {0}'. format(m['name'])), text_body=render_template( 'monitoring_error.txt', **template_kwargs), html_body=render_template( 'monitoring_error.html', **template_kwargs), ) elif m['schedule'].get('interval') != 'immediate' and m.get( 'always_send'): send_email( [ u['email'] for u in get_items_by_id( [ObjectId(u) for u in m['users']], 'users') ], m.get('subject') or m['name'], text_body=render_template( 'monitoring_email_no_updates.txt', **template_kwargs), html_body=render_template( 'monitoring_email_no_updates.html', **template_kwargs), ) get_resource_service('monitoring').patch(m['_id'], { 'last_run_time': local_to_utc(app.config['DEFAULT_TIMEZONE'], now) })
def send_alerts(self, monitoring_list, created_from, created_from_time, now): general_settings = get_settings_collection().find_one( GENERAL_SETTINGS_LOOKUP) error_recipients = [] if general_settings and general_settings['values'].get( 'system_alerts_recipients'): error_recipients = general_settings['values'][ 'system_alerts_recipients'].split(',') from newsroom.email import send_email for m in monitoring_list: # if immediate set the created from to the time of the last item sent, if available if m.get('schedule', {}).get('interval') == 'immediate' and m.get( 'last_run_time', False): created_from = m.get('last_run_time').strftime('%Y-%m-%d') created_from_time = m.get('last_run_time').strftime('%H:%M:%S') last_run_time = local_to_utc(app.config['DEFAULT_TIMEZONE'], now) company = get_entity_or_404(m['company'], 'companies') user_list = self.filter_users(m, company) if len(user_list) and company.get('is_enabled'): internal_req = ParsedRequest() internal_req.args = { 'navigation': str(m['_id']), 'created_from': created_from, 'created_from_time': created_from_time, 'skip_user_validation': True } items = list( get_resource_service('monitoring_search').get( req=internal_req, lookup=None)) items[:] = [ item for item in items if not self.already_sent(item, m) ] template_kwargs = {'profile': m} if items: try: template_kwargs.update({ 'items': items, 'section': 'wire', }) truncate_article_body(items, m) # If there is only one story to send and the headline is to be used as the subject if m.get('headline_subject', False) and len(items) == 1: subject = items[0].get( 'headline', m.get('subject') or m['name']) else: subject = m.get('subject') or m['name'] if m.get('format_type') == 'monitoring_email': self.send_email_alert(items, subject, m, user_list) else: _file = get_monitoring_file(m, items) attachment = base64.b64encode(_file.read()) formatter = app.download_formatters[ m['format_type']]['formatter'] send_email( user_list, subject, text_body=render_template( 'monitoring_email.txt', **template_kwargs), html_body=render_template( 'monitoring_email.html', **template_kwargs), attachments_info=[{ 'file': attachment, 'file_name': formatter.format_filename(None), 'content_type': 'application/{}'.format( formatter.FILE_EXTENSION), 'file_desc': 'Monitoring Report for Celery monitoring alerts for profile: {}' .format(m['name']) }]) get_resource_service('history').create_history_record( items, action='email', user={ '_id': None, 'company': m['company'] }, section='monitoring', monitoring=m['_id']) except Exception: logger.exception( '{0} Error processing monitoring profile {1} for company {2}.' .format(self.log_msg, m['name'], company['name'])) if error_recipients: # Send an email to admin template_kwargs = { 'name': m['name'], 'company': company['name'], 'run_time': now, } send_email( error_recipients, gettext( 'Error sending alerts for monitoring: {0}'. format(m['name'])), text_body=render_template( 'monitoring_error.txt', **template_kwargs), html_body=render_template( 'monitoring_error.html', **template_kwargs), ) elif m['schedule'].get('interval') != 'immediate' and m.get( 'always_send'): send_email( user_list, m.get('subject') or m['name'], text_body=render_template( 'monitoring_email_no_updates.txt', **template_kwargs), html_body=render_template( 'monitoring_email_no_updates.html', **template_kwargs), ) if m.get('schedule', {}).get('interval') == 'immediate' and len(items): # determine the version created time for the most recent item last_article_created = max( item.get('versioncreated') for item in items) # last run time is either the time of the last sent item or the last run time. last_run_time = last_article_created if last_article_created else last_run_time get_resource_service('monitoring').patch( m['_id'], {'last_run_time': last_run_time})