Пример #1
0
def insert_inst_into_980(curdir,uid):
	"""collection handling for institutes"""
	user_groups = get_usergroups(uid)
	if check_field_exists(curdir,"hgf_9201_"):
		if read_file(curdir,"hgf_9201_") == "[]": remove_file(curdir,"hgf_9201_") # delete file in case of empty sequence! TODO: this should not happen and has to be fixed in hgfInstitutes.js

	if not check_field_exists(curdir,"hgf_9201_"): #make sure that we have at least one institute
		if str(uid) == "1": return #do not add institutes for admin
		user_insts = extract_user_institutes("0",user_groups)
		if user_insts == []:
			email_txt = "%s is not assigned to any institute. This email was generated from Covert_hgf_fields and function insert_inst_into_980" %get_recordid(curdir)
			send_email(CFG_SITE_ADMIN_EMAIL, CFG_SITE_ADMIN_EMAIL, "ERROR: no institute assigned", email_txt,header="",html_header="")
			return #this should not happen!
		jsondict = user_insts   #add institute even if no institute chosen to be inserted into 980
	else:
		jsondict = read_json(curdir,"hgf_9201_")
	inst_list = []
	list_980 = read_json(curdir,"hgf_980__")
	
	for inst in jsondict:
		if {"a":inst["0"]} in list_980: continue
		inst_list.append({"a":inst["0"]})
	if inst_list == []: return
	list_980 += inst_list

	#check if users institut in 980, if not take it from user_info
	if str(uid) == "1": pass # no adding of institutes into 980  for admin
	else:
		str_list_980 = [str(i) for i in list_980] #convert list with dicts into list with str(dicts), because python sets use list with strings
		intersection_groups = set(str_list_980) & set(user_groups) # user institute not in 980 yet
		intersection_vdb = set(["{'a': 'VDB'}", "{'a': 'VDBRELEVANT'}","{'a': 'VDBINPRINT'}"]) & set(str_list_980) # not vdb_relevant

		if intersection_groups == set([]) and  intersection_vdb == set([]): # # prevent submitting vdb irrelevant stuff for another institute
			list_980 += extract_user_institutes("a",user_groups)
	write_json(curdir,"hgf_980__",list_980)
Пример #2
0
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)
Пример #3
0
    def test_simple_email_header(self):
        """
        Test simple email header.
        """
        from invenio.config import CFG_SITE_ADMIN_EMAIL
        from invenio.jinja2utils 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')

        send_email('*****@*****.**', ['*****@*****.**'], subject='Subject',
                   content='Content')
        email = sys.stdout.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 = sys.stdout.getvalue()
        self.assertIn(msg_content, email)
        self.assertIn(self.ADMIN_MESSAGE, email)
        self.assertNotIn('Bcc:', email)
        self.assertIn(msg, email)
        self.flush_mailbox()
Пример #4
0
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)
Пример #5
0
    def test_email_html_template(self):
        """
        Test email html template engine.
        """
        from invenio.jinja2utils 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), ctx.iteritems()))

        for name, ctx in contexts.iteritems():
            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()
Пример #6
0
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_addr = "%s Alert Engine <%s>" % (CFG_SITE_NAME, CFG_WEBALERT_ALERT_ENGINE_EMAIL)
    to_addr = 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_LOGDIR,
        "contact": "Please contact %s quoting the following information:" % (CFG_SITE_SUPPORT_EMAIL,),
    }
    from invenio.mailutils import send_email

    send_email(from_addr, to_addr, subject="Error notification", content=body)
Пример #7
0
    def test_email_text_template(self):
        """
        Test email text template engine.
        """
        from invenio.jinja2utils 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 contexts.iteritems():
            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()
Пример #8
0
    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 = sys.stdout.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 = sys.stdout.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()
Пример #9
0
def openaire_upload_notification(recid):
    """
    Send a notification to all user collections.
    """
    ctx = {
        'record': get_record(recid),
    }

    ucolls = UserCollection.from_recid(recid, provisional=True)
    for c in ucolls:
        try:
            if c.owner.email:
                ctx.update({
                    'usercollection': c,
                })
                content = render_template_to_string(
                    "usercollection_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
Пример #10
0
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,
    )
Пример #11
0
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)
Пример #12
0
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 ""
Пример #13
0
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
    send_email(FROMADDR,
               sub,
               "%s modified" % rn,
               email_txt,
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
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 _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)
Пример #16
0
def send_notification_email(dois, log_dir, count_total, count_new, skip_results):
    """Notify on errors by mail.

    If any issues occured during the DOI update, this function
    notifies the appropriate authorities with details of the error
    Parameters:
     * dois - a dictionary with three categories of problem DOIs
     * log_dir - the directory where the logs are stored

    """
    msg_html = """<p>Message from BibTasklet %s:</p>

<p>Problems have occurred while updating the DOIs of records. In total %d DOIs were
processed, of which %d were processed succesfully.</p>

<p>Further details on these errors can be found in the log files, they should be
available here: '%s/'</p>
""" % (
        SCRIPT_NAME,
        count_total,
        count_new,
        log_dir,
    )

    categories = [cat for cat in CATEGORIES if not cat[0] in skip_results]

    for cid, title, desc, structure in categories:
        str1, str2, str3 = structure.split(", ")
        if len(dois[cid]) > 0 and not cid in skip_results:
            msg_html += """
<h3>%s</h3>
<p>%s:</p>
<table>
    <tr>
        <td><p><strong>%s</strong></p></td>
        <td><p><strong>%s</strong></p></td>
        <td><p><strong>%s</strong></p></td>
    </tr>
""" % (
                title,
                desc,
                str1,
                str2,
                str3,
            )
            for doi, arxiv, data in dois[cid]:
                msg_html += """<tr>
                            <td><p>%s</p></td>
                            <td><p>%s</p></td>
                            <td><p>%s</p></td>
                          </tr>""" % (
                    doi,
                    arxiv,
                    str(data),
                )
            msg_html += "</table>"

    send_email(CFG_SITE_ADMIN_EMAIL, CFG_SITE_ADMIN_EMAIL, "Issues during ArXiv DOI Update", html_content=msg_html)
Пример #17
0
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 ""
Пример #18
0
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/record/%s>%s" % (rn,title,author,CFG_SITE_URL,sysno,note)

    # send the email
    send_email(FROMADDR, SuE, "%s revised" % rn, message, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
Пример #19
0
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 ""
Пример #20
0
def register_emergency(msg, recipients=None):
    """Launch an emergency. This means to send email messages to each
    address in 'recipients'. By default recipients will be obtained via
    get_emergency_recipients() which loads settings from
    CFG_SITE_EMERGENCY_EMAIL_ADDRESSES
    """
    from invenio.mailutils import send_email
    if not recipients:
        recipients = get_emergency_recipients()
    for address_str in recipients:
        send_email(CFG_SITE_SUPPORT_EMAIL, address_str, "Emergency notification", msg)
Пример #21
0
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)
Пример #22
0
def register_emergency(msg, recipients=None):
    """Launch an emergency. This means to send email messages to each
    address in 'recipients'. By default recipients will be obtained via
    get_emergency_recipients() which loads settings from
    CFG_SITE_EMERGENCY_EMAIL_ADDRESSES
    """
    from invenio.mailutils import send_email
    if not recipients:
        recipients = get_emergency_recipients()
    for address_str in recipients:
        send_email(CFG_SITE_SUPPORT_EMAIL, address_str,
                   "Emergency notification", msg)
Пример #23
0
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)
Пример #24
0
def _notify_error_user(email_user,
                       original_filename,
                       recid,
                       submission_title,
                       ln=invenio.config.CFG_SITE_LANG):
    """Sends an error notification to the specified addres 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)
Пример #25
0
def _notify_success_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG):
    """Sends an success notification to the specified addres of the user.
       Is called by process_batch_job() if the processing was successfull.
    @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,
    )
Пример #26
0
def _notify_error_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG):
    """Sends an error notification to the specified addres 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,
    )
Пример #27
0
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')])
Пример #28
0
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_addr = '%s Alert Engine <%s>' % (CFG_SITE_NAME,
                                          CFG_WEBALERT_ALERT_ENGINE_EMAIL)
    to_addr = 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_LOGDIR,
        'contact':
        "Please contact %s quoting the following information:" %
        (CFG_SITE_SUPPORT_EMAIL, )
    }
    from invenio.mailutils import send_email
    send_email(from_addr, to_addr, subject="Error notification", content=body)
Пример #29
0
def send_notification_email(dois, log_dir, count_total, count_new,
                            skip_results):
    """Notify on errors by mail.

    If any issues occured during the DOI update, this function
    notifies the appropriate authorities with details of the error
    Parameters:
     * dois - a dictionary with three categories of problem DOIs
     * log_dir - the directory where the logs are stored

    """
    msg_html = """<p>Message from BibTasklet %s:</p>

<p>Problems have occurred while updating the DOIs of records. In total %d DOIs were
processed, of which %d were processed succesfully.</p>

<p>Further details on these errors can be found in the log files, they should be
available here: '%s/'</p>
""" % (SCRIPT_NAME, count_total, count_new, log_dir)

    categories = [cat for cat in CATEGORIES if not cat[0] in skip_results]

    for cid, title, desc, structure in categories:
        str1, str2, str3 = structure.split(', ')
        if len(dois[cid]) > 0 and not cid in skip_results:
            msg_html += """
<h3>%s</h3>
<p>%s:</p>
<table>
    <tr>
        <td><p><strong>%s</strong></p></td>
        <td><p><strong>%s</strong></p></td>
        <td><p><strong>%s</strong></p></td>
    </tr>
""" % (title, desc, str1, str2, str3)
            for doi, arxiv, data in dois[cid]:
                msg_html += """<tr>
                            <td><p>%s</p></td>
                            <td><p>%s</p></td>
                            <td><p>%s</p></td>
                          </tr>""" % (doi, arxiv, str(data))
            msg_html += "</table>"

    send_email(CFG_SITE_ADMIN_EMAIL,
               CFG_SITE_ADMIN_EMAIL,
               "Issues during ArXiv DOI Update",
               html_content=msg_html)
Пример #30
0
def _notify_success_user(email_user,
                         original_filename,
                         recid,
                         submission_title,
                         ln=invenio.config.CFG_SITE_LANG):
    """Sends an success notification to the specified addres of the user.
       Is called by process_batch_job() if the processing was successfull.
    @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)
Пример #31
0
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 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 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_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 bst_arxiv_harvest_notification(admin_email=CFG_SITE_ADMIN_EMAIL):
    """
    Checks if Arxiv harvesting has ran today and emails the
    admin if it has not. This task should be scheduled to run
    at the end of the day.

    @param admin_email: The person who should be notified
    @type admin_email: string
    """
    # Search string lists all records harvested today from Arxiv
    if not perform_request_search(p="find da today and eprint arxiv"):
        from invenio.mailutils import send_email
        message = """
            The Arxiv harvest does not appear to have ran
            today (No new records have been harvested)."""

        send_email(admin_email, CFG_WEBALERT_ALERT_ENGINE_EMAIL,
            "Notice: Arxiv harvest has not ran today", message)
Пример #36
0
 def test_email_html_image(self):
     """
     Test sending html message with an image.
     """
     from invenio.config import CFG_WEBDIR
     html_images = {
         'img1': os.path.join(CFG_WEBDIR, '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 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
Пример #38
0
def add_FFT(curdir):
	"""
	!!!move_files_to_storage, move files to done have to be deleted from websubmit function!!!
	add FFT tag into record
	if this function is used: the functions stamp_uploaded_files should not be used in the websubmit anymore
	"""
	if not check_field_exists(curdir,"hgf_file"): return None # no file submitted
	fulltext_filename = read_file(curdir,"hgf_file")
	fulltext_path = os.path.join(curdir,"files","hgf_file",fulltext_filename)
	if not os.path.exists(fulltext_path): return None # no file named in hgf_file in files directory. something is wrong..
	if os.path.getsize(fulltext_path) == 0: #check file size
		#send email
		#first get the url record link
		if not check_field_exists(curdir,"SN"): return None # no recid-->something is wrong..
		recid = get_recordid(curdir)
		rec_url = CFG_SITE_URL + "/record/" + recid
		#create email
		email_txt = 'Dear Sir or Madam, \n\nAn empty file has been submitted for the record: %s\n\nProbably it was caused, because the file has been deleted from its directory before final submission into %s !!!\nIt is possible, that the record itself is not available, when this email was sent, but it should be processed within minutes. Once this is finished you may add the fulltext by accessing %s and using "modify record" link \n\n' %(rec_url,CFG_SITE_NAME,rec_url)
		email_subject = 'File submission incomplete!!!'
		#email check
		if check_field_exists(curdir,"SuE"): email_to = read_file(curdir,"SuE") # get email from submitter
		else: email_to = CFG_SITE_ADMIN_EMAIL # in case somehow no email of submitter exists, send email to admin

		send_email(CFG_SITE_ADMIN_EMAIL, email_to, email_subject, email_txt,copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN,header="",html_header="")
		return None #cancel file submission (the submitter has already been informed via email), the original submission will be processed.


	inst_dict_list = read_json(curdir,"hgf_9201_") #read in institutes
	inst_list = []
	restriction = "firerole: allow groups 'STAFF'" # staff is always
	# add the institutes id and append the external auth info as this
	# builds the actual group name we need to allow here.
	for inst in inst_dict_list:	restriction += ",'" + inst["0"] + ' ['+CFG_EXTERNAL_AUTH_DEFAULT+']' + "'"  # TODO: multiple authentifications
	filename = read_file(curdir,"hgf_file")
	file_path = os.path.join(curdir,"files","hgf_file",filename)
	if not check_field_exists(curdir,"rn"): return
	rn = read_file(curdir,"rn")

	#fill subfields for FFT
	fft_dict = {}
	fft_dict["a"] = file_path
	fft_dict["n"] = rn
	fft_dict["r"] = restriction
	write_json(curdir,"hgf_FFT__",fft_dict)
Пример #39
0
def Mail_Submitter(parameters,
                   curdir,
                   subject,
                   text,
                   support_email="",
                   from_address=""):
    """
    This function send an email to the submitter to warn him the
    document he has just submitted has been correctly received.

    Parameters:

      * authorfile: Name of the file containing the authors of the
                    document

      * titleFile: Name of the file containing the title of the
                   document

      * emailFile: Name of the file containing the email of the
                   submitter of the document

      * status: Depending on the value of this parameter, the function
                adds an additional text to the email.  This parameter
                can be one of: ADDED: The file has been integrated in
                the database.  APPROVAL: The file has been sent for
                approval to a referee.  or can stay empty.

      * edsrn: Name of the file containing the reference of the
               document

      * newrnin: Name of the file containing the 2nd reference of the
                 document (if any)
    """
    # The submitters email address is read from the file specified by 'emailFile'
    try:
        fp = open("%s/%s" % (curdir, parameters['emailFile']), "r")
        m_recipient = fp.read().replace("\n", " ")
        fp.close()
    except:
        m_recipient = ""
    # send the mail
    send_email(fromaddr=from_address, toaddr=m_recipient.strip(), subject=subject, \
               content=text, footer=email_footer(support_email=support_email), copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
Пример #40
0
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,
                     )
Пример #41
0
 def test_sending_attachment(self):
     """
     Test sending email with an attachment.
     """
     from invenio.config import CFG_WEBDIR
     attachments = [
         os.path.join(CFG_WEBDIR, '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()
Пример #42
0
 def large_file_notification(sender, deposition=None, deposition_file=None,
                             **kwargs):
     if deposition_file and deposition_file.size > 10485760:
         from invenio.mailutils import send_email
         from invenio.config import CFG_SITE_ADMIN_EMAIL, CFG_SITE_NAME
         from invenio.textutils import nice_size
         from invenio.jinja2utils import render_template_to_string
         current_app.logger.info(deposition_file.__getstate__())
         send_email(
             CFG_SITE_ADMIN_EMAIL,
             CFG_SITE_ADMIN_EMAIL,
             subject="%s: %s file uploaded" % (
                 CFG_SITE_NAME, nice_size(deposition_file.size)
             ),
             content=render_template_to_string(
                 "email_large_file.html",
                 deposition=deposition,
                 deposition_file=deposition_file,
             )
         )
Пример #43
0
    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 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_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
Пример #46
0
def openaire_upload_notification(recid):
    """
    Send a notification to all user collections.
    """
    ctx = {
        'record': get_record(recid),
    }

    ucolls = UserCollection.from_recid(recid, provisional=True)
    for c in ucolls:
        try:
            if c.owner.email:
                ctx.update({
                    'usercollection': c,
                })
                content = render_template_to_string("usercollection_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
Пример #47
0
def send_request_notification_to_all_linkback_moderators(recid, origin_url, linkback_type, ln):
    """
    Send notification emails to all linkback moderators for linkback request
    @param recid
    @param origin_url: URL of the requestor
    @param linkback_type: of CFG_WEBLINKBACK_LIST_TYPE
    """
    content = """There is a new %(linkback_type)s request for %(recordURL)s from %(origin_url)s which you should approve or reject.
              """ % {'linkback_type': linkback_type,
                     'recordURL': generate_redirect_url(recid, ln),
                     'origin_url': origin_url}

    html_content = """There is a new %(linkback_type)s request for %(record)s (<a href="%(recordURL)s">%(recordURL)s</a>) from <a href="%(origin_url)s">%(title)s</a> (<a href="%(origin_url)s">%(origin_url)s</a>) which you should approve or reject.
                   """ % {'linkback_type': linkback_type,
                          'record': format_record(recID=recid, of='hs', ln=ln),
                          'recordURL': generate_redirect_url(recid, ln),
                          'origin_url': origin_url,
                          'title': origin_url}

    for email in acc_get_authorized_emails('moderatelinkbacks', collection = guess_primary_collection_of_a_record(recid)):
        send_email(CFG_SITE_ADMIN_EMAIL, email, 'New ' + linkback_type + ' request', content, html_content)
Пример #48
0
def register_emergency(msg, recipients=None):
    """Launch an emergency. This means to send email messages to each
    address in 'recipients'. By default recipients will be obtained via
    get_emergency_recipients() which loads settings from
    CFG_SITE_EMERGENCY_EMAIL_ADDRESSES
    """
    from invenio.mailutils import send_email
    from socket import gethostname
    if not recipients:
        recipients = get_emergency_recipients()
    recipients = set(recipients)
    recipients.add(CFG_SITE_ADMIN_EMAIL)
    mail_subject = "Emergency notification from " + gethostname() + " at " + CFG_SITE_URL
    sms_subject = "ALERT"
    for address_str in recipients:
        if "sms" in address_str:
            # Probably an SMS, lets reduce things!
            subject = sms_subject
        else:
            subject = mail_subject
        send_email(CFG_SITE_SUPPORT_EMAIL, address_str, subject, msg)
Пример #49
0
def register_emergency(msg, recipients=None):
    """Launch an emergency. This means to send email messages to each
    address in 'recipients'. By default recipients will be obtained via
    get_emergency_recipients() which loads settings from
    CFG_SITE_EMERGENCY_EMAIL_ADDRESSES
    """
    from invenio.mailutils import send_email
    from socket import gethostname
    if not recipients:
        recipients = get_emergency_recipients()
    recipients = set(recipients)
    recipients.add(CFG_SITE_ADMIN_EMAIL)
    mail_subject = "Emergency notification from " + gethostname() + " at " + CFG_SITE_URL
    sms_subject = "ALERT"
    for address_str in recipients:
        if "sms" in address_str:
            # Probably an SMS, lets reduce things!
            subject = sms_subject
        else:
            subject = mail_subject
        send_email(CFG_SITE_SUPPORT_EMAIL, address_str, subject, msg)
Пример #50
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:
            ownerprefs = invenio.webuser.get_user_preferences(owner)
            if ownerprefs.has_key("bibcatalog_username"):
                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
Пример #51
0
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)
Пример #52
0
def Mail_Submitter(parameters, curdir, subject, text, support_email="", from_address=""):
    """
    This function send an email to the submitter to warn him the
    document he has just submitted has been correctly received.

    Parameters:

      * authorfile: Name of the file containing the authors of the
                    document

      * titleFile: Name of the file containing the title of the
                   document

      * emailFile: Name of the file containing the email of the
                   submitter of the document

      * status: Depending on the value of this parameter, the function
                adds an additional text to the email.  This parameter
                can be one of: ADDED: The file has been integrated in
                the database.  APPROVAL: The file has been sent for
                approval to a referee.  or can stay empty.

      * edsrn: Name of the file containing the reference of the
               document

      * newrnin: Name of the file containing the 2nd reference of the
                 document (if any)
    """
    # The submitters email address is read from the file specified by 'emailFile'
    try:
        fp = open("%s/%s" % (curdir,parameters['emailFile']),"r")
        m_recipient = fp.read().replace ("\n"," ")
        fp.close()
    except:
        m_recipient = ""
    # send the mail
    send_email(fromaddr=from_address, toaddr=m_recipient.strip(), subject=subject, \
               content=text, footer=email_footer(support_email=support_email), copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
Пример #53
0
def send_overdue_letter(borrower_id, subject, content):
    """
    Send an overdue letter

    @param borrower_id: identify the borrower. Primary key of crcBORROWER.
    @type borrower_id: int

    @param subject: subject of the overdue letter
    @type subject: string
    """

    to_borrower = db.get_borrower_email(borrower_id)

    send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
               toaddr=to_borrower,
               subject=subject,
               content=content,
               header='',
               footer='',
               attempt_times=1,
               attempt_sleeptime=10
               )
    return 1
Пример #54
0
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_addr = '%s Alert Engine <%s>' % (
        CFG_SITE_NAME, CFG_WEBALERT_ALERT_ENGINE_EMAIL)
    to_addr = 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_LOGDIR,
        'contact': "Please contact %s quoting the following information:" %
            (CFG_SITE_SUPPORT_EMAIL, )}
    from invenio.mailutils import send_email
    send_email(from_addr, to_addr, subject="Error notification", content=body)