<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def check_undelivered(to=None):
 """Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to: Recipient address. If not set Django ADMINS setting is used. :rtype: int """

    failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count()

    if failed_count:
        from sitemessage.shortcuts import schedule_email
        from sitemessage.messages.email import EmailTextMessage

        if to is None:
            admins = settings.ADMINS

            if admins:
                to = list(dict(admins).values())

        if to:
            priority = 999

            register_message_types(EmailTextMessage)

            schedule_email(
                'You have %s undelivered dispatch(es) at %s' % (failed_count, get_site_url()),
                subject='[SITEMESSAGE] Undelivered dispatches',
                to=to, priority=priority)

            send_scheduled_messages(priority=priority)

    return failed_count