def test_bbc_undisclosed_recipients(self): """ Test that the email receivers are hidden. """ msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject From: [email protected] To: Undisclosed.Recipients:""" send_email('*****@*****.**', ['*****@*****.**', '*****@*****.**'], subject='Subject', content='Content') email = sys.stdout.getvalue() self.assertIn(msg_content, email) self.assertNotIn('Bcc: [email protected],[email protected]', email) self.flush_mailbox() send_email('*****@*****.**', '[email protected], [email protected]', subject='Subject', content='Content') email = sys.stdout.getvalue() self.assertIn(msg_content, email) self.assertNotIn('Bcc: [email protected],[email protected]', email) self.flush_mailbox()
def robotupload_callback(): """Handle callback from robotupload. If robotupload was successful caches the workflow object id that corresponds to the uploaded record, so the workflow can be resumed when webcoll finish processing that record. If robotupload encountered an error sends an email to site administrator informing him about the error.""" request_data = request.get_json() id_object = request_data.get("nonce", "") results = request_data.get("results", []) status = False for result in results: status = result.get('success', False) if status: recid = result.get('recid') pending_records = cache.get("pending_records") or dict() pending_records[str(recid)] = str(id_object) cache.set("pending_records", pending_records, timeout=cfg["PENDING_RECORDS_CACHE_TIMEOUT"]) else: from invenio_ext.email import send_email body = ("There was an error when uploading the " "submission with id: %s.\n" % id_object) body += "Error message:\n" body += result.get('error_message', '') send_email( cfg["CFG_SITE_SUPPORT_EMAIL"], cfg["CFG_SITE_ADMIN_EMAIL"], 'BATCHUPLOAD ERROR', body ) return jsonify({"result": status})
def test_cc_bcc_headers(self): """ Test that no Cc and Bcc headers are sent. """ from invenio_base.globals import cfg msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject From: [email protected] To: %s""" % (cfg['CFG_SITE_ADMIN_EMAIL'], ) send_email('*****@*****.**', ['*****@*****.**', '*****@*****.**'], subject='Subject', content='Content') email = self.stream.getvalue() self.assertIn(msg_content, email) self.assertIn(self.ADMIN_MESSAGE, email) self.assertIn('[email protected],[email protected]', email) self.assertNotIn('Bcc: [email protected],[email protected]', email) self.flush_mailbox() send_email('*****@*****.**', '[email protected], [email protected]', subject='Subject', content='Content') email = self.stream.getvalue() self.assertIn(msg_content, email) self.assertIn(self.ADMIN_MESSAGE, email) self.assertIn('[email protected],[email protected]', email) self.assertNotIn('Bcc: [email protected],[email protected]', email) self.flush_mailbox()
def send_account_activation_email(user): """Send an account activation email.""" expires_in = cfg.get('CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS') address_activation_key = EmailConfirmationSerializer(expires_in=timedelta( days=expires_in).total_seconds()).create_token(user.id, {'email': user.email}) # Render context. ctx = { "ip_address": None, "user": user, "email": user.email, "activation_link": url_for( 'webaccount.access', mailcookie=address_activation_key, _external=True, _scheme='https', ), "days": expires_in, } # Send email send_email( cfg.get('CFG_SITE_SUPPORT_EMAIL'), user.email, _("Account registration at %(sitename)s", sitename=cfg["CFG_SITE_NAME_INTL"].get( getattr(g, 'ln', cfg['CFG_SITE_LANG']), cfg['CFG_SITE_NAME'])), render_template("accounts/emails/activation.tpl", **ctx))
def _report_via_email(obj, eng): recipients = obj.extra_data["config"].get("recipients") if not recipients: obj.log.warning("No recipients") return collections = obj.data.get('collections', dict()) files_uploaded = [] for update_type, filename in collections.items(): count = len(obj.data.get(update_type, list())) files_uploaded.append((basename(filename), count)) harvesting_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") context = { "object": obj, "files_uploaded": files_uploaded, "args": obj.extra_data.get("args", dict()), "harvesting_date": harvesting_date } body = render_template( template, **context ) subject = "{0} harvest results: {1}".format( context.get("args").get("workflow"), harvesting_date ) send_email(fromaddr=cfg.get("CFG_SITE_SUPPORT_EMAIL"), toaddr=recipients, subject=subject, content=body)
def emit(self, record): # Set by invenio_ext.logging.wrappers.register_exception if hasattr(record, 'invenio_register_exception'): extra = record.invenio_register_exception exc_info = record.exc_info exc_name = exc_info[0].__name__ alert_admin = extra['alert_admin'] subject = extra['subject'] content = self.format(record) filename, line_no, function_name = _get_filename_and_line(exc_info) # let's log the exception and see whether we should report it. log = HstEXCEPTION.get_or_create(exc_name, filename, line_no) if log.exception_should_be_notified and ( cfg['CFG_SITE_ADMIN_EMAIL_EXCEPTIONS'] > 1 or (alert_admin and cfg['CFG_SITE_ADMIN_EMAIL_EXCEPTIONS'] > 0)): # Set subject of email if not subject: subject = 'Exception (%s:%s:%s)' % (filename, line_no, function_name) subject = '%s at %s' % (subject, cfg['CFG_SITE_URL']) # Set content of email content = "\n%s\n%s" % (log.pretty_notification_info, content) # Send the email from invenio_ext.email import send_email send_email(cfg['CFG_SITE_ADMIN_EMAIL'], cfg['CFG_SITE_ADMIN_EMAIL'], subject=subject, content=content)
def test_email_text_template(self): """ Test email text template engine. """ from invenio_ext.template import render_template_to_string contexts = { 'ctx1': {'content': 'Content 1'}, 'ctx2': {'content': 'Content 2', 'header': 'Header 2'}, 'ctx3': {'content': 'Content 3', 'footer': 'Footer 3'}, 'ctx4': {'content': 'Content 4', 'header': 'Header 4', 'footer': 'Footer 4'} } msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: %s From: [email protected] To: [email protected]""" for name, ctx in iteritems(contexts): msg = render_template_to_string('mail_text.tpl', **ctx) send_email('*****@*****.**', ['*****@*****.**'], subject=name, **ctx) email = sys.stdout.getvalue() self.assertIn(msg_content % name, email) self.assertIn(msg, email) self.flush_mailbox()
def report(self, user_readable_msg, location_tuple=None): if self.send_email in (SendEmail.always,): send_email( CFG_SITE_ADMIN_EMAIL, self.email, "CHECKER LOG - rule: %s logging" % (self.reporter.rule_name,), "%s\n %s" % (user_readable_msg, location_tuple) )
def send_account_activation_email(user): """Send an account activation email.""" expires_in = cfg.get('CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS') address_activation_key = EmailConfirmationSerializer( expires_in=timedelta(days=expires_in).total_seconds() ).create_token(user.id, {'email': user.email}) # Render context. ctx = { "ip_address": None, "user": user, "email": user.email, "activation_link": url_for( 'webaccount.access', mailcookie=address_activation_key, _external=True, _scheme='https', ), "days": expires_in, } # Send email send_email( cfg.get('CFG_SITE_SUPPORT_EMAIL'), user.email, _("Account registration at %(sitename)s", sitename=cfg["CFG_SITE_NAME_INTL"].get( getattr(g, 'ln', cfg['CFG_SITE_LANG']), cfg['CFG_SITE_NAME'])), render_template("accounts/emails/activation.tpl", **ctx) )
def test_email_html_template(self): """ Test email html template engine. """ from invenio_ext.template import render_template_to_string contexts = { 'ctx1': {'html_content': '<b>Content 1</b>'}, 'ctx2': {'html_content': '<b>Content 2</b>', 'html_header': '<h1>Header 2</h1>'}, 'ctx3': {'html_content': '<b>Content 3</b>', 'html_footer': '<i>Footer 3</i>'}, 'ctx4': {'html_content': '<b>Content 4</b>', 'html_header': '<h1>Header 4</h1>', 'html_footer': '<i>Footer 4</i>'} } def strip_html_key(ctx): return dict(map(lambda (k, v): (k[5:], v), iteritems(ctx))) for name, ctx in iteritems(contexts): msg = render_template_to_string('mail_html.tpl', **strip_html_key(ctx)) send_email('*****@*****.**', ['*****@*****.**'], subject=name, content='Content Text', **ctx) email = sys.stdout.getvalue() self.assertIn('Content-Type: multipart/alternative;', email) self.assertIn('Content Text', email) self.assertIn(msg, email) self.flush_mailbox()
def test_simple_email_header(self): """ Test simple email header. """ from invenio_base.globals import cfg from invenio_ext.template import render_template_to_string msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject From: [email protected] To: %s""" % (cfg['CFG_SITE_ADMIN_EMAIL'], ) msg = render_template_to_string('mail_text.tpl', content='Content') self.flush_mailbox() send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content') email = self.stream.getvalue() self.assertIn(msg_content, email) self.assertIn(self.ADMIN_MESSAGE, email) self.assertNotIn('Bcc:', email) self.assertIn(msg, email) self.flush_mailbox() send_email('*****@*****.**', '*****@*****.**', subject='Subject', content='Content') email = self.stream.getvalue() self.assertIn(msg_content, email) self.assertIn(self.ADMIN_MESSAGE, email) self.assertNotIn('Bcc:', email) self.assertIn(msg, email) self.flush_mailbox()
def report_exception(self, when, outrep_summary, location_tuple, formatted_exception=None, patches=None): if self.send_email in (SendEmail.always, SendEmail.on_failure): send_email( CFG_SITE_ADMIN_EMAIL, self.email, "CHECKER EXCEPTION - rule: %s raised exception" % (self.reporter.rule_name,), "%s\n %s\n %s\n %s\n %s" % (when, outrep_summary, location_tuple, formatted_exception, patches) )
def report_exception(self, when, outrep_summary, location_tuple, formatted_exception=None, patches=None): if self.send_email in (SendEmail.always, SendEmail.on_failure): send_email( CFG_SITE_ADMIN_EMAIL, self.email, "CHECKER EXCEPTION - rule: %s raised exception" % (self.reporter.rule_name, ), "%s\n %s\n %s\n %s\n %s" % (when, outrep_summary, location_tuple, formatted_exception, patches))
def postfeedback(): """Handler to create a ticket from user feedback.""" feedback = request.form.get('feedback') if feedback == '': response = jsonify(success=False) response.status_code = 400 return response replytoaddr = request.form.get('replytoaddr', None) if replytoaddr is None: replytoaddr = current_user.get('email') if replytoaddr == '': response = jsonify(success=False) response.status_code = 403 return response content = '''Feedback: {feedback}'''.format(feedback=feedback) if send_email(fromaddr=cfg['CFG_SITE_SUPPORT_EMAIL'], toaddr=cfg['INSPIRELABS_FEEDBACK_EMAIL'], subject='INSPIRE Labs feedback', content=content, replytoaddr=replytoaddr, attachments=[]): return jsonify(success=True) else: response = jsonify(success=False) response.status_code = 500 return response
def send_reset_password_email(email): """Reset password by sending a email with the unique link.""" expires_in = cfg.get('CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS') reset_key = EmailConfirmationSerializer( expires_in=timedelta(days=expires_in).total_seconds() ).create_token(email, {'email': email}) if not reset_key: raise AccountSecurityError( _('Something goes wrong when the cookie has been generated') ) email_text = render_template( 'accounts/email_reset_password.html', reset_key=reset_key, email=email ) return send_email( fromaddr=cfg['CFG_SITE_SUPPORT_EMAIL'], subject=_("Password reset request for %(website)s", website=cfg['CFG_SITE_URL']), toaddr=email, content=email_text )
def postfeedback(): """Handler to create a ticket for user feedback.""" subject = "INSPIRE Labs feedback" feedback = json.loads(request.form.get("data")) content = """ Feedback: {feedback} """.format(feedback=feedback) # fd, temp_path = mkstemp(suffix=".png") # fh = os.fdopen(fd, "wb") # fh.write("".join(feedback_data[1].split(",")[1:]).decode('base64')) # fh.close() # attachments = [temp_path] attachments = [] if send_email(fromaddr=cfg['CFG_SITE_SUPPORT_EMAIL'], toaddr=cfg['INSPIRELABS_FEEDBACK_EMAIL'], subject=subject, content=content, replytoaddr=current_user.get("email"), attachments=attachments): return json.dumps( {'success': True} ), 200, {'ContentType': 'application/json'} else: return json.dumps( {'success': False} ), 500, {'ContentType': 'application/json'}
def test_email_html_image(self): """ Test sending html message with an image. """ html_images = { 'img1': pkg_resources.resource_filename( 'invenio_base', os.path.join('static', 'img', 'journal_water_dog.gif') ) } send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content Text', html_content='<img src="cid:img1"/>', html_images=html_images) email = sys.stdout.getvalue() self.assertIn('Content Text', email) self.assertIn('<img src="cid:img1"/>', email) with open(html_images['img1'], 'r') as f: self.assertIn(encodestring(f.read()), email) self.flush_mailbox()
def test_console_send_email(self): """ Test that the console backend can be pointed at an arbitrary stream. """ msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject From: [email protected] To: [email protected]""" send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content') self.assertIn(msg_content, sys.stdout.getvalue()) self.flush_mailbox() send_email('*****@*****.**', '*****@*****.**', subject='Subject', content='Content') self.assertIn(msg_content, sys.stdout.getvalue()) self.flush_mailbox()
def test_email_text_template(self): """ Test email text template engine. """ from invenio_ext.template import render_template_to_string contexts = { 'ctx1': { 'content': 'Content 1' }, 'ctx2': { 'content': 'Content 2', 'header': 'Header 2' }, 'ctx3': { 'content': 'Content 3', 'footer': 'Footer 3' }, 'ctx4': { 'content': 'Content 4', 'header': 'Header 4', 'footer': 'Footer 4' } } msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: %s From: [email protected] To: [email protected]""" for name, ctx in iteritems(contexts): msg = render_template_to_string('mail_text.tpl', **ctx) send_email('*****@*****.**', ['*****@*****.**'], subject=name, **ctx) email = sys.stdout.getvalue() self.assertIn(msg_content % name, email) self.assertIn(msg, email) self.flush_mailbox()
def test_sending_attachment(self): """ Test sending email with an attachment. """ attachments = [ pkg_resources.resource_filename( 'invenio_base', os.path.join('static', 'img', 'journal_header.png')) ] send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content Text', attachments=attachments) email = sys.stdout.getvalue() self.assertIn('Content Text', email) # First attachemnt is image/png self.assertIn('Content-Type: image/png', email) for attachment in attachments: with open(attachment, 'r') as f: self.assertIn(encodestring(f.read()), email) self.flush_mailbox()
def test_sending_attachment(self): """ Test sending email with an attachment. """ attachments = [ pkg_resources.resource_filename( 'invenio_base', os.path.join('static', 'img', 'journal_header.png') ) ] send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content Text', attachments=attachments) email = sys.stdout.getvalue() self.assertIn('Content Text', email) # First attachemnt is image/png self.assertIn('Content-Type: image/png', email) for attachment in attachments: with open(attachment, 'r') as f: self.assertIn(encodestring(f.read()), email) self.flush_mailbox()
def test_email_html_image(self): """ Test sending html message with an image. """ html_images = { 'img1': pkg_resources.resource_filename( 'invenio_base', os.path.join('static', 'img', 'journal_water_dog.gif')) } send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content Text', html_content='<img src="cid:img1"/>', html_images=html_images) email = sys.stdout.getvalue() self.assertIn('Content Text', email) self.assertIn('<img src="cid:img1"/>', email) with open(html_images['img1'], 'r') as f: self.assertIn(encodestring(f.read()), email) self.flush_mailbox()
def test_email_html_template(self): """ Test email html template engine. """ from invenio_ext.template import render_template_to_string contexts = { 'ctx1': { 'html_content': '<b>Content 1</b>' }, 'ctx2': { 'html_content': '<b>Content 2</b>', 'html_header': '<h1>Header 2</h1>' }, 'ctx3': { 'html_content': '<b>Content 3</b>', 'html_footer': '<i>Footer 3</i>' }, 'ctx4': { 'html_content': '<b>Content 4</b>', 'html_header': '<h1>Header 4</h1>', 'html_footer': '<i>Footer 4</i>' } } def strip_html_key(ctx): return dict(map(lambda (k, v): (k[5:], v), iteritems(ctx))) for name, ctx in iteritems(contexts): msg = render_template_to_string('mail_html.tpl', **strip_html_key(ctx)) send_email('*****@*****.**', ['*****@*****.**'], subject=name, content='Content Text', **ctx) email = sys.stdout.getvalue() self.assertIn('Content-Type: multipart/alternative;', email) self.assertIn('Content Text', email) self.assertIn(msg, email) self.flush_mailbox()
def test_single_recipient(self): """ Test that the email receivers are hidden. """ msg_content = """Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject From: [email protected] To: [email protected]""" send_email('*****@*****.**', ['*****@*****.**'], subject='Subject', content='Content') email = sys.stdout.getvalue() self.assertIn(msg_content, email) self.flush_mailbox() send_email('*****@*****.**', '*****@*****.**', subject='Subject', content='Content') email = sys.stdout.getvalue() self.assertIn(msg_content, email) self.flush_mailbox()
def emit(self, record): # Set by invenio_ext.logging.wrappers.register_exception if hasattr(record, 'invenio_register_exception'): extra = record.invenio_register_exception exc_info = record.exc_info exc_name = exc_info[0].__name__ alert_admin = extra['alert_admin'] subject = extra['subject'] content = self.format(record) filename, line_no, function_name = _get_filename_and_line(exc_info) # let's log the exception and see whether we should report it. log = HstEXCEPTION.get_or_create(exc_name, filename, line_no) if log.exception_should_be_notified and ( cfg['CFG_SITE_ADMIN_EMAIL_EXCEPTIONS'] > 1 or (alert_admin and cfg['CFG_SITE_ADMIN_EMAIL_EXCEPTIONS'] > 0)): # Set subject of email if not subject: subject = 'Exception (%s:%s:%s)' % ( filename, line_no, function_name ) subject = '%s at %s' % (subject, cfg['CFG_SITE_URL']) # Set content of email content = "\n%s\n%s" % ( log.pretty_notification_info, content ) # Send the email from invenio_ext.email import send_email send_email( cfg['CFG_SITE_ADMIN_EMAIL'], cfg['CFG_SITE_ADMIN_EMAIL'], subject=subject, content=content )
def send_reset_password_email(email): """Reset password by sending a email with the unique link.""" expires_in = cfg.get('CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS') reset_key = EmailConfirmationSerializer(expires_in=timedelta( days=expires_in).total_seconds()).create_token(email, {'email': email}) if not reset_key: raise AccountSecurityError( _('Something goes wrong when the cookie has been generated')) email_text = render_template('accounts/email_reset_password.html', reset_key=reset_key, email=email) return send_email(fromaddr=cfg['CFG_SITE_SUPPORT_EMAIL'], subject=_("Password reset request for %(website)s", website=cfg['CFG_SITE_URL']), toaddr=email, content=email_text)
def report(self, user_readable_msg, location_tuple=None): if self.send_email in (SendEmail.always, ): send_email( CFG_SITE_ADMIN_EMAIL, self.email, "CHECKER LOG - rule: %s logging" % (self.reporter.rule_name, ), "%s\n %s" % (user_readable_msg, location_tuple))