'Returns logged in POP3/IMAP connection object.'

def get_incoming_server(self, in_receive=False, email_sync_rule=u'UNSEEN'):

    if (frappe.cache().get_value(u'workers:no-internet') == True):
        return None
    args = frappe._dict({u'email_account': self.name, u'host': self.email_server, u'use_ssl': self.use_ssl, u'username': (getattr(self, u'login_id', None) or self.email_id), u'use_imap': self.use_imap, u'email_sync_rule': email_sync_rule, u'uid_validity': self.uidvalidity, u'initial_sync_count': (self.initial_sync_count or 100)})
    if self.password:
        args.password = self.get_password()
    if (not args.get(u'host')):
        frappe.throw(_(u'{0}    is    required').format(u'Email    Server'))
    email_server = EmailServer(frappe._dict(args))
    try:
        email_server.connect()
    except (error_proto, imaplib.IMAP4.error) as e:
        message = e.message.lower().replace(u'    ', u'')
        if (in_receive and any(map((lambda t: (t in message)), [u'authenticationfail', u'loginviayourwebbrowser', u'loginfailed', u'err[auth]', u'errtemporaryerror']))):
            self.handle_incoming_connect_error(description=_(u'Authentication    failed    while    receiving    emails    from    Email    Account    {0}.    Message    from    server:    {1}'.format(self.name, e.message)))
            return None
        else:
            frappe.throw(e.message)
    except socket.error:
        if in_receive:
            description = (frappe.message_log.pop() if frappe.message_log else u'Socket    Error')
            if test_internet():
                self.db_set(u'no_failed', (self.no_failed + 1))
                if (self.no_failed > 2):
                    self.handle_incoming_connect_error(description=description)
            else:
                frappe.cache().set_value(u'workers:no-internet', True)
            return None
        else:
            raise
    if (not in_receive):
        if self.use_imap:
            email_server.imap.logout()
    self.set_failed_attempts_count(0)
    return email_server
