def _notify_error_admin(batch_job, email_admin=invenio.config.CFG_SITE_ADMIN_EMAIL): """Sends a notification email to the specified address, containing admin-only information. Is called by process_batch_job() if an error occured during the processing. @param email_admin: email address of the admin @type email_admin: string """ if not email_admin: return template = ("BibEncode batch processing has reported an error during the" "execution of a job within the batch description <br/><br/>" "This is the batch description: <br/><br/>" "%(batch_description)s <br/><br/>" "This is the message log: <br/><br/>" "%(message_log)s") html_text = template % { "batch_description": pformat(batch_job).replace("\n", "<br/>"), "message_log": "\n".join(_MSG_HISTORY) } text = html_text.replace("<br/>", "\n") send_email(fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL, toaddr=email_admin, subject="Error during BibEncode batch processing", content=text, html_content=html_text)
def Send_Modify_Mail(parameters, curdir, form, user_info=None): """ This function sends an email to warn people a document has been modified and the user his modifications have been taken into account.. Parameters: * addressesMBI: email addresses of the people who will receive this email (comma separated list). * fieldnameMBI: name of the file containing the modified fields. * sourceDoc: Long name for the type of document. This name will be displayed in the mail. * emailfile: name of the file in which the email of the modifier will be found. """ FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME, CFG_SITE_SUPPORT_EMAIL) global sysno, rn if parameters['emailFile'] is not None and parameters[ 'emailFile'] != "" and os.path.exists( "%s/%s" % (curdir, parameters['emailFile'])): fp = open("%s/%s" % (curdir, parameters['emailFile']), "r") sub = fp.read() fp.close() sub = sub.replace("\n", "") else: sub = "" # Copy mail to: addresses = parameters['addressesMBI'] addresses = addresses.strip() m_fields = parameters['fieldnameMBI'] type = parameters['sourceDoc'] rn = re.sub("[\n\r ]+", "", rn) if os.path.exists("%s/%s" % (curdir, m_fields)): fp = open("%s/%s" % (curdir, m_fields), "r") fields = fp.read() fp.close() fields = fields.replace("\n", " | ") fields = re.sub("[| \n\r]+$", "", fields) else: fields = "" email_txt = "Dear Sir or Madam, \n%s %s has just been modified.\nModified fields: %s\n\n" % ( type, rn, fields) if CFG_SITE_URL != "" and sysno != "": email_txt += "You can check the modified document here:\n" email_txt += "<%s/%s/%s>\n\n" % (CFG_SITE_URL, CFG_SITE_RECORD, sysno) email_txt += "Please note that the modifications will be taken into account in a couple of minutes.\n\nBest regards,\nThe %s Server support Team" % CFG_SITE_NAME # send the mail if any recipients or copy to admin if sub or CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN: send_email(FROMADDR, sub, "%s modified" % rn, email_txt, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN) return ""
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 send_pending_linkbacks_notification(linkback_type): """ Send notification emails to all linkback moderators for all pending linkbacks @param linkback_type: of CFG_WEBLINKBACK_LIST_TYPE """ pending_linkbacks = get_all_linkbacks( linkback_type=CFG_WEBLINKBACK_TYPE['TRACKBACK'], status=CFG_WEBLINKBACK_STATUS['PENDING']) if pending_linkbacks: pending_count = len(pending_linkbacks) cutoff_text = '' if pending_count > CFG_WEBLINKBACK_MAX_LINKBACKS_IN_EMAIL: cutoff_text = ' (Printing only the first %s requests)' % CFG_WEBLINKBACK_MAX_LINKBACKS_IN_EMAIL content = """There are %(count)s new %(linkback_type)s requests which you should approve or reject%(cutoff)s: """ % { 'count': pending_count, 'linkback_type': linkback_type, 'cutoff': cutoff_text } for pending_linkback in pending_linkbacks[ 0:CFG_WEBLINKBACK_MAX_LINKBACKS_IN_EMAIL]: content += """ For %(recordURL)s from %(origin_url)s. """ % { 'recordURL': generate_redirect_url(pending_linkback[2]), 'origin_url': pending_linkback[1] } for email in acc_get_authorized_emails('moderatelinkbacks'): send_email(CFG_SITE_ADMIN_EMAIL, email, 'Pending ' + linkback_type + ' requests', content)
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_simple_email_header(self): """ Test simple email header. """ from invenio.config import CFG_SITE_ADMIN_EMAIL 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_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 openaire_upload_notification(recid): """ Send a notification to all user collections. """ ctx = { 'record': get_record(recid), } ucolls = Community.from_recid(recid, provisional=True) for c in ucolls: try: if c.owner.email: ctx.update({ 'community': c, }) content = render_template_to_string( "communities/new_upload_email.html", **ctx) send_email( CFG_SITE_SUPPORT_EMAIL, c.owner.email.encode('utf8'), "[%s] New upload to %s" % ( CFG_SITE_NAME, c.title.encode('utf8') ), content=content.encode('utf8') ) logger.info("Sent email for new record %s to %s." % (recid, c.owner.email.encode('utf8'))) except AttributeError: pass
def test_cc_bcc_headers(self): """ Test that no Cc and Bcc headers are sent. """ from invenio.config import CFG_SITE_ADMIN_EMAIL 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_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 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 send_pending_linkbacks_notification(linkback_type): """ Send notification emails to all linkback moderators for all pending linkbacks @param linkback_type: of CFG_WEBLINKBACK_LIST_TYPE """ pending_linkbacks = get_all_linkbacks(linkback_type=CFG_WEBLINKBACK_TYPE['TRACKBACK'], status=CFG_WEBLINKBACK_STATUS['PENDING']) if pending_linkbacks: pending_count = len(pending_linkbacks) cutoff_text = '' if pending_count > CFG_WEBLINKBACK_MAX_LINKBACKS_IN_EMAIL: cutoff_text = ' (Printing only the first %s requests)' % CFG_WEBLINKBACK_MAX_LINKBACKS_IN_EMAIL content = """There are %(count)s new %(linkback_type)s requests which you should approve or reject%(cutoff)s: """ % {'count': pending_count, 'linkback_type': linkback_type, 'cutoff': cutoff_text} for pending_linkback in pending_linkbacks[0:CFG_WEBLINKBACK_MAX_LINKBACKS_IN_EMAIL]: content += """ For %(recordURL)s from %(origin_url)s. """ % {'recordURL': generate_redirect_url(pending_linkback[2]), 'origin_url': pending_linkback[1]} for email in acc_get_authorized_emails('moderatelinkbacks'): send_email(CFG_SITE_ADMIN_EMAIL, email, 'Pending ' + linkback_type + ' requests', content)
def send_account_activation_email(user): """Send an account activation email.""" from invenio.modules.access.mailcookie import \ mail_cookie_create_mail_activation expires_in = cfg.get('CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS') address_activation_key = mail_cookie_create_mail_activation( user.email, cookie_timeout=timedelta(days=expires_in) ) # 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']), 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 _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 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", []) 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) else: from invenio.config import CFG_SITE_ADMIN_EMAIL from invenio.ext.email import send_email from invenio.config import CFG_SITE_SUPPORT_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_SITE_SUPPORT_EMAIL, CFG_SITE_ADMIN_EMAIL, 'BATCHUPLOAD ERROR', body ) return jsonify({"result": status})
def _notify_error_admin(batch_job, email_admin=invenio.config.CFG_SITE_ADMIN_EMAIL): """Sends a notification email to the specified address, containing admin-only information. Is called by process_batch_job() if an error occured during the processing. @param email_admin: email address of the admin @type email_admin: string """ if not email_admin: return template = ( "BibEncode batch processing has reported an error during the" "execution of a job within the batch description <br/><br/>" "This is the batch description: <br/><br/>" "%(batch_description)s <br/><br/>" "This is the message log: <br/><br/>" "%(message_log)s" ) html_text = template % { "batch_description": pformat(batch_job).replace("\n", "<br/>"), "message_log": "\n".join(_MSG_HISTORY), } text = html_text.replace("<br/>", "\n") send_email( fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL, toaddr=email_admin, subject="Error during BibEncode batch processing", content=text, html_content=html_text, )
def _warn_admin_counterlimit_approaching(db, lastsys, maxsys): mailfrom_addr = '%s Submission Engine <%s>' % (CFG_SITE_NAME, CFG_SITE_SUPPORT_EMAIL) mailtxt = """WARNING: The maxmimum ALEPH SYS value for the [%s] database is approaching!\n"""\ """The last SYS allocated was [%d]; The maximum SYS allowed is [%d].\n\n"""\ """You should be thinking about allocating a new range of SYS now!\n"""\ % (db, lastsys, maxsys) send_email(fromaddr=mailfrom_addr, toaddr=CFG_SITE_ADMIN_EMAIL, subject="WebSubmit WARNING - MAXIMUM SYS IN [%s] APPROACHING!" % db, content=mailtxt)
def _send_notification(to, subject, template, **ctx): """Render a template and send as email.""" send_email( cfg.get('CFG_SITE_SUPPORT_EMAIL'), to, subject, render_template(template, **ctx), )
def _mail_admin_because_lockfile_not_removeable(lockfilename, extramsg=""): mailfrom_addr = '%s Submission Engine <%s>' % (CFG_SITE_NAME, CFG_SITE_SUPPORT_EMAIL) mailtxt = """ERROR: When trying to allocate an ALEPH SYS for a record, it was not possible to remove the lockfile [%s]!"""\ """ This means that all attempted new submissions to that database will be blocked and fail, as it is not"""\ """ possible to allocate them a SYS in ALEPH. Please investigate and remove the lockfile ASAP.\n\n"""\ % (lockfilename,) mailtxt += extramsg send_email(fromaddr=mailfrom_addr, toaddr=CFG_SITE_ADMIN_EMAIL, subject="WebSubmit ERROR - CANNOT REMOVE ALEPH SYS LOCKFILE!", content=mailtxt)
def Mail_Approval_Request_to_Committee_Chair(parameters, curdir, form, user_info=None): """ This function sends a confirmation email to the Committee Chair when approval for a document is requested. """ FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME, CFG_SITE_SUPPORT_EMAIL) # retrieve useful information from webSubmit configuration res = run_sql("select * from sbmCPLXAPPROVAL where rn=%s", (rn, )) categ = res[0][1] pubcomchair_address = "" # Try to retrieve the committee chair's email from the referee's database for user in acc_get_role_users( acc_get_role_id("pubcomchair_%s_%s" % (res[0][0], categ))): pubcomchair_address += user[1] #Get the document details from the repository - use the function in publiline.py item_details = get_brief_doc_details_from_repository(rn) #Generate the author list authors = "" for element in item_details['authors']: authors += element + ", " message = """ The document %s has been published as a Communication. Please select an appropriate referee for this document. Title: %s Author(s): %s To access the document(s), select the file(s) from the location: <%s/%s/%s> To select a referee, please go to: <%s/publiline.py?flow=cplx&doctype=%s&categ=%s&apptype=%s&RN=%s&ln=en> --------------------------------------------- Best regards. The submission team.""" % ( rn, item_details['title'], authors, CFG_SITE_URL, CFG_SITE_RECORD, sysno, CFG_SITE_URL, res[0][0], res[0][1], res[0][3], rn) # send the mail send_email(FROMADDR, pubcomchair_address, "Request for Referee Selection : Document %s" % rn, message, footer="") return ""
def Send_SRV_Mail(parameters, curdir, form, user_info=None): """ This function sends an email to warn people a revision has been carried out. Parameters: * notefile: name of the file in which the note can be found * emailfile: name of the file containing the submitter's email * addressesSRV: email addresses of the people who will receive this email (comma separated list). this parameter may contain the <CATEG> string. In which case the variable computed from the [categformatDAM] parameter replaces this string. eg.:"<CATEG>[email protected]" * categformatDAM: contains a regular expression used to compute the category of the document given the reference of the document. eg.: if [categformatAFP]="TEST-<CATEG>-.*" and the reference of the document is "TEST-CATEGORY1-2001-001", then the computed category equals "CATEGORY1" """ global rn,doctype,sysno # variables declaration FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL) addresses = parameters['addressesSRV'] addresses = addresses.strip() if parameters['emailFile'] is not None and parameters['emailFile']!="" and os.path.exists("%s/%s" % (curdir,parameters['emailFile'])): fp = open("%s/%s" % (curdir,parameters['emailFile']), "r") SuE = fp.read() fp.close() else: SuE = "" SuE = SuE.replace("\n",",") if parameters['noteFile'] is not None and parameters['noteFile']!= "" and os.path.exists("%s/%s" % (curdir,parameters['noteFile'])): fp = open("%s/%s" % (curdir,parameters['noteFile']), "r") note = fp.read() fp.close() else: note = "" title = Get_Field("245__a",sysno) author = Get_Field('100__a',sysno) author += Get_Field('700__a',sysno) # create message message = "A revised version of document %s has been submitted.\n\nTitle: %s\nAuthor(s): %s\nURL: <%s/%s/%s>%s" % (rn,title,author,CFG_SITE_URL,CFG_SITE_RECORD,sysno,note) # send the email send_email(FROMADDR, SuE, "%s revised" % rn, message, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN) return ""
def Send_Modify_Mail (parameters, curdir, form, user_info=None): """ This function sends an email to warn people a document has been modified and the user his modifications have been taken into account.. Parameters: * addressesMBI: email addresses of the people who will receive this email (comma separated list). * fieldnameMBI: name of the file containing the modified fields. * sourceDoc: Long name for the type of document. This name will be displayed in the mail. * emailfile: name of the file in which the email of the modifier will be found. """ FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL) global sysno,rn if parameters['emailFile'] is not None and parameters['emailFile']!= "" and os.path.exists("%s/%s" % (curdir,parameters['emailFile'])): fp = open("%s/%s" % (curdir,parameters['emailFile']),"r") sub = fp.read() fp.close() sub = sub.replace ("\n","") else: sub = "" # Copy mail to: addresses = parameters['addressesMBI'] addresses = addresses.strip() m_fields = parameters['fieldnameMBI'] type = parameters['sourceDoc'] rn = re.sub("[\n\r ]+","",rn) if os.path.exists("%s/%s" % (curdir,m_fields)): fp = open("%s/%s" % (curdir,m_fields),"r") fields = fp.read() fp.close() fields = fields.replace ("\n"," | ") fields = re.sub("[| \n\r]+$","",fields) else: fields = "" email_txt = "Dear Sir or Madam, \n%s %s has just been modified.\nModified fields: %s\n\n" % (type,rn,fields) if CFG_SITE_URL != "" and sysno != "": email_txt += "You can check the modified document here:\n" email_txt += "<%s/%s/%s>\n\n" % (CFG_SITE_URL,CFG_SITE_RECORD,sysno) email_txt += "Please note that the modifications will be taken into account in a couple of minutes.\n\nBest regards,\nThe %s Server support Team" % CFG_SITE_NAME # send the mail if any recipients or copy to admin if sub or CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN: send_email(FROMADDR,sub,"%s modified" % rn,email_txt,copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN) return ""
def _notify_error_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG): """Sends an error notification to the specified address of the user. Is called by process_batch_job() if an error occured during the processing. @param email_user: email address of the user @type email_user: string @param email_admin: email address of the admin @type email_admin: string """ if not email_user: return uid = emailUnique(email_user) if uid != -1 and uid != 0: language = getval(get_user_preferences(uid), "language") if language: ln = language _ = gettext_set_language(ln) rec_url = invenio.config.CFG_SITE_URL + "/record/" + str(recid) template = ( "<br/>" + _("We are sorry, a problem has occured during the processing of" " your video upload%(submission_title)s.") + "<br/><br/>" + _("The file you uploaded was %(input_filename)s.") + "<br/><br/>" + _("Your video might not be fully available until intervention.") + "<br/>" + _("You can check the status of your video here: %(record_url)s.") + "<br/>" + _("You might want to take a look at " " %(guidelines_url)s" " and modify or redo your submission.")) text = template % { "input_filename": "%s" % original_filename, "submission_title": " %s" % submission_title, "record_url": "%s" % rec_url, "guidelines_url": "localhost" } text = text.replace("<br/>", "\n") html_text = template % { "input_filename": "<strong>%s</strong>" % original_filename, "submission_title": " <strong>%s</strong>" % submission_title, "record_url": "<a href=\"%s\">%s</a>" % (rec_url, rec_url), "guidelines_url": "<a href=\"locahost\">%s</a>" % _("the video guidelines") } send_email(fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL, toaddr=email_user, subject="Problem during the processing of your video", content=text, html_content=html_text)
def inform_submitter(obj, eng): """Send a mail to submitter with the outcome of the submission.""" from invenio.modules.access.control import acc_get_user_email from invenio.ext.email import send_email d = Deposition(obj) id_user = d.workflow_object.id_user email = acc_get_user_email(id_user) if was_approved(obj, eng): body = 'Accepted: ' extra_data = d.workflow_object.get_extra_data() body += extra_data.get('url', '') else: body = 'Rejected' send_email(CFG_SITE_SUPPORT_EMAIL, email, 'Subject', body, header='header')
def send_error_report_to_admin(header, url, time_msg, browser, client, error, sys_error, traceback_msg): """ Sends an email to the admin with client info and tracestack """ from invenio.base.globals import cfg from invenio.ext.email import send_email from_addr = '%s Alert Engine <%s>' % ( cfg['CFG_SITE_NAME'], cfg['CFG_WEBALERT_ALERT_ENGINE_EMAIL']) to_addr = cfg['CFG_SITE_ADMIN_EMAIL'] body = """ The following error was seen by a user and sent to you. %(contact)s %(header)s %(url)s %(time)s %(browser)s %(client)s %(error)s %(sys_error)s %(traceback)s Please see the %(logdir)s/invenio.err for traceback details.""" % { 'header': header, 'url': url, 'time': time_msg, 'browser': browser, 'client': client, 'error': error, 'sys_error': sys_error, 'traceback': traceback_msg, 'logdir': cfg['CFG_LOGDIR'], 'contact': "Please contact %s quoting the following information:" % (cfg['CFG_SITE_SUPPORT_EMAIL'], ) } send_email(from_addr, to_addr, subject="Error notification", content=body)
def _notify_error_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG): """Sends an error notification to the specified address of the user. Is called by process_batch_job() if an error occured during the processing. @param email_user: email address of the user @type email_user: string @param email_admin: email address of the admin @type email_admin: string """ if not email_user: return uid = emailUnique(email_user) if uid != -1 and uid != 0: language = getval(get_user_preferences(uid), "language") if language: ln = language _ = gettext_set_language(ln) rec_url = invenio.config.CFG_SITE_URL + "/record/" + str(recid) template = ( "<br/>" + _("We are sorry, a problem has occured during the processing of" " your video upload%(submission_title)s.") + "<br/><br/>" + _("The file you uploaded was %(input_filename)s.") + "<br/><br/>" + _("Your video might not be fully available until intervention.") + "<br/>" + _("You can check the status of your video here: %(record_url)s.") + "<br/>" + _("You might want to take a look at " " %(guidelines_url)s" " and modify or redo your submission.") ) text = template % { "input_filename": "%s" % original_filename, "submission_title": " %s" % submission_title, "record_url": "%s" % rec_url, "guidelines_url": "localhost", } text = text.replace("<br/>", "\n") html_text = template % { "input_filename": "<strong>%s</strong>" % original_filename, "submission_title": " <strong>%s</strong>" % submission_title, "record_url": '<a href="%s">%s</a>' % (rec_url, rec_url), "guidelines_url": '<a href="locahost">%s</a>' % _("the video guidelines"), } send_email( fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL, toaddr=email_user, subject="Problem during the processing of your video", content=text, html_content=html_text, )
def _notify_success_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG): """Sends an success notification to the specified address of the user. Is called by process_batch_job() if the processing was successful. @param email_user: email address of the user @type email_user: string @param email_admin: email address of the admin @type email_admin: string """ uid = emailUnique(email_user) if uid != -1 and uid != 0: language = getval(get_user_preferences(uid), "language") if language: ln = language _ = gettext_set_language(ln) rec_url = invenio.config.CFG_SITE_URL + "/record/" + str(recid) template = ( "<br/>" + _("Your video submission%(submission_title)s was successfully processed.") + "<br/><br/>" + _("The file you uploaded was %(input_filename)s.") + "<br/><br/>" + _("Your video is now available here: %(record_url)s.") + "<br/>" + _( "If the videos quality is not as expected, you might want to take " "a look at %(guidelines_url)s" " and modify or redo your submission." ) ) text = template % { "input_filename": "%s" % original_filename, "submission_title": " %s" % submission_title, "record_url": "%s" % rec_url, "guidelines_url": "localhost", } text = text.replace("<br/>", "\n") html_text = template % { "input_filename": "<strong>%s</strong>" % original_filename, "submission_title": " <strong>%s</strong>" % submission_title, "record_url": '<a href="%s">%s</a>' % (rec_url, rec_url), "guidelines_url": '<a href="locahost">%s</a>' % _("the video guidelines"), } send_email( fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL, toaddr=email_user, subject="Your video submission is now complete", content=text, html_content=html_text, )
def reset_password(email, ln=None): """Reset user password.""" from datetime import timedelta from invenio.config import CFG_SITE_SUPPORT_EMAIL, CFG_SITE_NAME, \ CFG_SITE_NAME_INTL, CFG_WEBSESSION_RESET_PASSWORD_EXPIRE_IN_DAYS # create the reset key if ln is None: ln = g.ln from invenio.modules.access.mailcookie import mail_cookie_create_pw_reset reset_key = mail_cookie_create_pw_reset(email, cookie_timeout=timedelta( days=CFG_WEBSESSION_RESET_PASSWORD_EXPIRE_IN_DAYS)) if reset_key is None: return False # reset key could not be created # load the email template import invenio.legacy.template websession_templates = invenio.legacy.template.load('websession') # finally send the email from invenio.ext.email import send_email from invenio.base.i18n import _ if not send_email(CFG_SITE_SUPPORT_EMAIL, email, "%s %s" % (_("Password reset request for"), CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)), websession_templates. tmpl_account_reset_password_email_body( email, reset_key, request.remote_addr, ln)): return False # mail could not be sent return True # password reset email send successfully
def _task_email_logs(): """ In case this was requested, emails the logs. """ email_logs_to = task_get_task_param('email_logs_to') if not email_logs_to: return status = task_read_status() task_name = task_get_task_param('task_name') task_specific_name = task_get_task_param('task_specific_name') if task_specific_name: task_name += ':' + task_specific_name runtime = task_get_task_param('runtime') title = "Execution of %s: %s" % (task_name, status) body = """ Attached you can find the stdout and stderr logs of the execution of name: %s id: %s runtime: %s options: %s status: %s """ % (task_name, _TASK_PARAMS['task_id'], runtime, _OPTIONS, status) err_file = os.path.join(CFG_LOGDIR, 'bibsched_task_%d.err' % _TASK_PARAMS['task_id']) log_file = os.path.join(CFG_LOGDIR, 'bibsched_task_%d.log' % _TASK_PARAMS['task_id']) return send_email(CFG_SITE_SUPPORT_EMAIL, email_logs_to, title, body, attachments=[(log_file, 'text/plain'), (err_file, 'text/plain')])
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 _notify_success_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG): """Sends an success notification to the specified address of the user. Is called by process_batch_job() if the processing was successful. @param email_user: email address of the user @type email_user: string @param email_admin: email address of the admin @type email_admin: string """ uid = emailUnique(email_user) if uid != -1 and uid != 0: language = getval(get_user_preferences(uid), "language") if language: ln = language _ = gettext_set_language(ln) rec_url = invenio.config.CFG_SITE_URL + "/record/" + str(recid) template = ( "<br/>" + _("Your video submission%(submission_title)s was successfully processed." ) + "<br/><br/>" + _("The file you uploaded was %(input_filename)s.") + "<br/><br/>" + _("Your video is now available here: %(record_url)s.") + "<br/>" + _("If the videos quality is not as expected, you might want to take " "a look at %(guidelines_url)s" " and modify or redo your submission.")) text = template % { "input_filename": "%s" % original_filename, "submission_title": " %s" % submission_title, "record_url": "%s" % rec_url, "guidelines_url": "localhost" } text = text.replace("<br/>", "\n") html_text = template % { "input_filename": "<strong>%s</strong>" % original_filename, "submission_title": " <strong>%s</strong>" % submission_title, "record_url": "<a href=\"%s\">%s</a>" % (rec_url, rec_url), "guidelines_url": "<a href=\"locahost\">%s</a>" % _("the video guidelines") } send_email(fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL, toaddr=email_user, subject="Your video submission is now complete", content=text, html_content=html_text)
def Mail_Approval_Request_to_Committee_Chair(parameters, curdir, form, user_info=None): """ This function sends a confirmation email to the Committee Chair when approval for a document is requested. """ FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL) # retrieve useful information from webSubmit configuration res = run_sql("select * from sbmCPLXAPPROVAL where rn=%s", (rn, )) categ = res[0][1] pubcomchair_address = "" # Try to retrieve the committee chair's email from the referee's database for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_%s" % (res[0][0],categ))): pubcomchair_address += user[1] #Get the document details from the repository - use the function in publiline.py item_details = get_brief_doc_details_from_repository(rn) #Generate the author list authors = "" for element in item_details['authors']: authors += element + ", " message = """ The document %s has been published as a Communication. Please select an appropriate referee for this document. Title: %s Author(s): %s To access the document(s), select the file(s) from the location: <%s/%s/%s> To select a referee, please go to: <%s/publiline.py?flow=cplx&doctype=%s&categ=%s&apptype=%s&RN=%s&ln=en> --------------------------------------------- Best regards. The submission team.""" % (rn,item_details['title'],authors,CFG_SITE_URL,CFG_SITE_RECORD,sysno,CFG_SITE_URL,res[0][0],res[0][1],res[0][3],rn) # send the mail send_email(FROMADDR,pubcomchair_address,"Request for Referee Selection : Document %s" % rn, message,footer="") return ""
def large_file_notification(sender, deposition=None, deposition_file=None, **kwargs): """ Send notification on large file uploads """ if deposition_file and deposition_file.size > 10485760: current_app.logger.info(deposition_file.__getstate__()) send_email(cfg['CFG_SITE_SUPPORT_EMAIL'], cfg['CFG_SITE_ADMIN_EMAIL'], subject="%s: %s file uploaded" % (cfg['CFG_SITE_NAME'], nice_size(deposition_file.size)), content=render_template_to_string( "deposit/email_large_file.html", deposition=deposition, deposition_file=deposition_file, ))
def ticket_set_attribute(self, uid, ticketid, attribute, new_value): """ Request to set attribute to new value on ticket with given ticketid""" subjectset = 'ticket #' + ticketid + ' - Attribute Update ...' textset = '...\n\n*Please modify attribute:' + attribute + ' to:' + new_value + ' on ticket:' + ticketid ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, header='Hello,\n\n', content=textset) if ok: return 1 return 0
def ticket_assign(self, uid, ticketid, to_user): """ Re-assign existing ticket with given ticketid to user to_user""" subjectset = 'ticket #' + ticketid + ' - Re-assign ...' textset = '...\n\n*Please re-assigning ticket #' + ticketid + ' to ' + to_user ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, header='Hello,\n\n', content=textset) if ok: return 1 return 0
def ticket_comment(self, uid, ticketid, comment): """ Comment on ticket with given ticketid""" subjectset = 'ticket #' + ticketid + ' - Comment ...' textset = '...\n\n*Comment on ticket #' + ticketid + '\nComment:' + comment ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, header='Hello,\n\n', content=textset) if ok: return 1 return 0
def ticket_submit(self, uid=None, subject="", recordid=-1, text="", queue="", priority="", owner="", requestor=""): """creates a ticket. Returns ticket_id on success, otherwise None""" if not EMAIL_SUBMIT_CONFIGURED: register_exception( stream='warning', subject='bibcatalog email not configured', prefix= "please configure bibcatalog email sending in CFG_BIBCATALOG_SYSTEM and CFG_BIBCATALOG_SYSTEM_EMAIL_ADDRESS" ) ticket_id = self._get_ticket_id() priorityset = "" queueset = "" requestorset = "" ownerset = "" recidset = " cf-recordID: %s\n" % recordid textset = "" subjectset = "" if subject: subjectset = 'ticket #%s - %s' % (ticket_id, subject) if priority: priorityset = " priority: %s\n" % priority if queue: queueset = " queue: %s\n" % queue if requestor: requestorset = " requestor: %s\n" % requestor if owner: from invenio.modules.accounts.models import User user = User.query.filter_by(nickname=owner).first() if user: ownerprefs = invenio.legacy.webuser.get_user_preferences( user.id) if "bibcatalog_username" in ownerprefs: owner = ownerprefs["bibcatalog_username"] ownerset = " owner: %s\n" % owner textset += ownerset + requestorset + recidset + queueset + priorityset + '\n' textset += text + '\n' ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, content=textset) if ok: return ticket_id return None
def bst_send_email(fromaddr, toaddr, subject="", content="", header=None, footer=None, copy_to_admin=0, attempt_times=1, attempt_sleeptime=10, replytoaddr="", bccaddr="", ): """ Send a forged email to TOADDR from FROMADDR with message created from subjet, content and possibly header and footer. @param fromaddr: sender @type fromaddr: string @param toaddr: comma-separated list of receivers @type toaddr: string @param subject: subject of the email @type subject: string @param content: content of the email @type content: string @param header: header to add, None for the Default @type header: string @param footer: footer to add, None for the Default @type footer: string @param copy_to_admin: if 1 add CFG_SITE_ADMIN_EMAIL in receivers @type copy_to_admin: int @param attempt_times: number of tries @type attempt_times: int @param attempt_sleeptime: seconds in between tries @type attempt_sleeptime: int @param replytoaddr: comma-separated list of emails to add as reply-to header @type replytoaddr: string @param bccaddr: comma-separated list of emails to add as bcc header @type bccaddr: string If sending fails, try to send it ATTEMPT_TIMES, and wait for ATTEMPT_SLEEPTIME seconds in between tries. """ copy_to_admin = int(copy_to_admin) attempt_times = int(attempt_times) attempt_sleeptime = int(attempt_sleeptime) return send_email(fromaddr=fromaddr, toaddr=toaddr, subject=subject, content=content, header=header, footer=footer, copy_to_admin=copy_to_admin, attempt_times=attempt_times, attempt_sleeptime=attempt_sleeptime, replytoaddr=replytoaddr, bccaddr=bccaddr, )
def large_file_notification(sender, deposition=None, deposition_file=None, **kwargs): """ Send notification on large file uploads """ if deposition_file and deposition_file.size > 10485760: current_app.logger.info(deposition_file.__getstate__()) send_email( cfg['CFG_SITE_SUPPORT_EMAIL'], cfg['CFG_SITE_ADMIN_EMAIL'], subject="%s: %s file uploaded" % ( cfg['CFG_SITE_NAME'], nice_size(deposition_file.size) ), content=render_template_to_string( "deposit/email_large_file.html", deposition=deposition, deposition_file=deposition_file, ) )
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_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 send_new_admin_account_warning(new_account_email, send_to, ln=CFG_SITE_LANG): """Send an email to the address given by send_to about the new account new_account_email.""" _ = gettext_set_language(ln) sub = _("New account on") + " '%s'" % CFG_SITE_NAME if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1: sub += " - " + _("PLEASE ACTIVATE") body = _("A new account has been created on") + " '%s'" % CFG_SITE_NAME if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1: body += _(" and is awaiting activation") body += ":\n\n" body += _(" Username/Email") + ": %s\n\n" % new_account_email body += _("You can approve or reject this account request at") + ": %s/admin/webaccess/webaccessadmin.py/manageaccounts\n" % CFG_SITE_URL return send_email(CFG_SITE_SUPPORT_EMAIL, send_to, subject=sub, 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 )