Пример #1
0
def send_loan_mail(trigger, loan, message_ctx={}, **kwargs):
    """Send loan email message asynchronously and log the result in Celery.

    :param trigger: Loan action trigger.
    :param loan: Updated loan.
    :param message_ctx: any other parameter to be passed as ctx in the msg.
    """
    patron = Patron.get_patron(loan["patron_pid"])
    document = Document.get_record_by_pid(loan["document_pid"])
    factory = loan_message_factory()
    msg = factory(
        trigger,
        message_ctx=dict(
            loan=loan,
            document=dict(title=document["title"]),
            patron=patron,
            **message_ctx,
        ),
        recipients=get_recipients([patron.email]),
        **kwargs,
    )
    current_app.logger.debug("Attempting to send email '{}' to {}...".format(
        msg.subject, ", ".join(msg.recipients)))
    data = msg.__dict__
    send_email.apply_async(
        (data, ),
        link=log_successful_mail.s(data),
        link_error=log_error_mail.s(),
    )
Пример #2
0
def send_ils_mail(factory, prev_loan, loan, trigger, **kwargs):
    """Send loan email message asynchronously and log the result in Celery.

    :param factory: Callable message factory to create Message object.
    :param prev_loan: Previous loan.
    :param loan: Updated loan.
    :param trigger: Loan action trigger.
    """
    msg = factory(prev_loan, loan, trigger, **kwargs)
    current_app.logger.debug("Attempting to send email '{}' to {}...".format(
        msg.subject, ", ".join(msg.recipients)))
    data = msg.__dict__
    send_email.apply_async((data, ), link=log_successful_mail.s(data))
Пример #3
0
def send_ils_email(message, name="ils_mail"):
    """Send an email async with Invenio-Mail and log success / errors.

    :param name: The name used in the log message.
    """
    full_data = message.__dict__
    dump = message.dump()
    log_msg = dict(name=name,
                   action="before_send",
                   message_id=dump["id"],
                   data=dump)
    celery_logger.debug(json.dumps(log_msg, sort_keys=True))
    send_email.apply_async((full_data, ),
                           link=log_successful_mail.s(dump),
                           link_error=log_error_mail.s(data=dump))
Пример #4
0
 def send_mail_to_patron(data):
     """Send the notification by email to the patron."""
     patron = data['loan']['patron']
     library = Location.get_record_by_pid(
         data['loan']['pickup_location_pid']).get_library()
     # get the recipient email from loan.patron.patron.email
     recipients = [patron.get('email')]
     # additional recipient
     add_recipient = patron['patron'].get('additional_communication_email')
     if add_recipient:
         recipents.push(add_recipient)
     # delay
     delay_availability = 0
     # get notification settings for notification type
     notification_type = data['notification_type']
     for setting in library['notification_settings']:
         if setting['type'] == 'availability':
             delay_availability = setting['delay']
     msg = Dispatcher._create_email(data, patron, library, recipients)
     task_send_email.apply_async((msg.__dict__, ),
                                 countdown=delay_availability)
Пример #5
0
def send_ils_email(message, is_manually_triggered=False, name="ils_mail"):
    """Send an email async with Invenio-Mail and log success / errors.

    :param message: BlockTemplatedMessage mail message.
    :param name: The name used in the log message.
    """
    message.recipients = get_recipients(message.recipients)

    full_data = message.__dict__
    dump = message.dump()
    log_msg = dict(
        name=name, action="before_send", message_id=dump["id"], data=dump
    )
    celery_logger.info(json.dumps(log_msg, sort_keys=True))

    dump["is_manually_triggered"] = is_manually_triggered

    send_email.apply_async(
        (full_data,),
        link=log_successful_mail.s(dump),
        link_error=log_error_mail.s(data=dump),
    )
Пример #6
0
    def send_notification_by_email(notifications):
        """Send the notification by email to the patron.

        :param notifications: the notification set to perform.
        :return True if email is send, False if errors are found.
        """
        notifications = notifications or []
        if not notifications:
            return True

        notification = notifications[0]
        reply_to = notification.get_recipients(RecipientType.REPLY_TO)
        recipients = notification.get_recipients(RecipientType.TO)

        error_reasons = []
        if not recipients:
            error_reasons.append('Missing notification recipients')
        if not reply_to:
            error_reasons.append('Missing reply_to email')
        if error_reasons:
            current_app.logger.warning(
                f'Notification#{notification.pid} is lost :: '
                f'({")(".join(error_reasons)})')
            return False

        # build the context for this notification set
        notif_class = notification.__class__
        context = notif_class.get_notification_context(notifications)

        msg = Dispatcher._create_email(
            recipients=recipients,
            reply_to=reply_to,
            ctx_data=context,
            template=notification.get_template_path())
        delay = context.get('delay', 0)
        task_send_email.apply_async((msg.__dict__, ), countdown=delay)
        return True
Пример #7
0
    def send_mail_for_printing(notifications=None):
        """Send a set of notification by mail.

         A this time, we doesn't have any way to send a notification using
         classic mail (postal) process. The solution is to send an email
         to the library address. The library will print this email and send it
         to the correct recipient.

         TODO : Implement a way to send notifications to a async PDF’s
                generator process working with CUPS (using RabbitMQ queue)

        :param notifications: the notification set to perform.
        :return True if email is send, False if errors are found.
        """
        notifications = notifications or []
        if not notifications:
            return True

        notification = notifications[0]
        # 1. Find the library were to send the message.
        #   - for AVAILABILITY, we need to use the pickup library
        #   - for BOOKING and TRANSIT, we need to use the transaction library
        #   - for other notifications, we need to use library
        library = notification.library
        if notification.type in [
                NotificationType.BOOKING, NotificationType.TRANSIT_NOTICE
        ]:
            library = notification.transaction_library
        elif notification.type == NotificationType.AVAILABILITY:
            library = notification.pickup_library
        recipient = library.get_email(notification.type)

        # 2. For a REQUEST notification we mainly need to use the email define
        #    on the location. If the location email isn't defined, then use the
        #    library email by default.
        if notification.type == NotificationType.REQUEST:
            recipient = notification.location.get('notification_email',
                                                  recipient)

        error_reasons = []
        reply_to = notification.library.get('email')
        if not recipient:
            error_reasons.append('Missing notification email')
        if not reply_to:
            error_reasons.append('Missing notification reply_to email')
        if error_reasons:
            current_app.logger.warning(
                f'Notification#{notification.pid} for printing is lost :: '
                f'({")(".join(error_reasons)})')
            return False

        # 2. Build the context to render the template
        notif_class = notification.__class__
        context = notif_class.get_notification_context(notifications)
        # 3. Force patron communication channel to 'mail'
        #    In some cases we force the notification to be send by mail despite
        #    the patron asked to received them by email (cipo reminders
        #    notifications with a communication channel to 'mail' value).
        #    Ensure than the ``include_patron_address`` are set to True.
        context['include_patron_address'] = True

        # 3. Send the message
        msg = Dispatcher._create_email(
            recipients=[recipient],
            reply_to=[reply_to],
            ctx_data=context,
            template=notification.get_template_path())
        task_send_email.apply_async((msg.__dict__, ))
        return True