def __check_imap(self, conn_data):
        """
        Checks IMAP server.
        """
        self.log(1, "Trying to connect to IMAP server...")
        if not "port" in conn_data:
            if conn_data["ssl"]:
                self.log(1, "Port wasn't specified. Will use 993 for SSL.")
                conn_data["port"] = 993
            if conn_data["tls"]:
                self.log(1, "Port wasn't specified. Will use 143 for TLS.")
                conn_data["port"] = 143
            if not conn_data["ssl"] and not conn_data["tls"]:
                self.log(1, "Port wasn't specified. Will use 143 for IMAP.")
                self.log(1, "! WARN: will use insecure connection! ")
                conn_data["port"] = 143

        # IMAP cannot use timeouts, so we set script-wide socket timeout.
        socket.setdefaulttimeout(self.__config["main"]["timeout"])

        try:
            if not conn_data["ssl"]:
                self.log(1, "Using non-SSL handler.")
                s = imaplib.IMAP4(host = conn_data["hostname"], port = conn_data["port"])
            else:
                self.log(1, "Using SSL handler.")
                s = imaplib.IMAP4_SSL(host = conn_data["hostname"], port = conn_data["port"])
        except socket.timeout as e:
            self.log(0, "CRITICAL - Login operation timed out for connection '{0}' (host: {1}, user: {2}, type {3}) was successful".format(self.__config["main"]["connection_to_use"], conn_data["hostname"], conn_data["username"], self.__config["main"]["connection_type"]))

        if conn_data["tls"]:
            self.log(1, "Starting TLS negotiation...")
            s.starttls()

        self.log(1, "Connetion established.")

        try:
            self.log(1, "Logging in...")
            s.login(conn_data["username"], conn_data["password"])
            self.log(1, "Issuing select()...")
            s.select()
        except socket.timeout:
            self.log(0, "CRITICAL - Login operation timed out for connection '{0}' (host: {1}, user: {2}, type {3}) was successful".format(self.__config["main"]["connection_to_use"], conn_data["hostname"], conn_data["username"], self.__config["main"]["connection_type"]))

        self.log(0, "OK - Authentication for connection '{0}' (host: {1}, user: {2}, type {3}) was successful".format(self.__config["main"]["connection_to_use"], conn_data["hostname"], conn_data["username"], self.__config["main"]["connection_type"]))
        s.logout()
Example #2
0
 def login(self):
     server_in = "imap.{}".format(self._setup["server_address"])
     port_in = self._setup["port_in"]
     if port_in == "993":
         self._conn = imaplib.IMAP4_SSL(
             server_in,
             port=port_in,
             keyfile=self._setup.get("keyfile"),
             certfile=self._setup.get("certfile"))
     else:
         if port_in != "143":
             msg = "Port {} is not valid for IMAP protocol. " \
                   "Trying through 143."
             _LOG.warning(msg.format(port_in))
             port_in = "143"
         self._conn = imaplib.IMAP4(server_in, port=port_in)
     self._do_login()
Example #3
0
    def fetchUnreadEmails(self, since=None, markRead=False, limit=None):
        """
        Fetches a list of unread email objects from a user's email inbox.

        Arguments:
        since -- if provided, no emails before this date will be returned
        markRead -- if True, marks all returned emails as read in target inbox

        Returns:
        A list of unread email objects.
        """
        logger = logging.getLogger(__name__)
        profile = config.get()
        conn = imaplib.IMAP4(profile[self.SLUG]["imap_server"],
                             profile[self.SLUG]["imap_port"])
        conn.debug = 0

        msgs = []
        try:
            conn.login(profile[self.SLUG]["address"],
                       profile[self.SLUG]["password"])
            conn.select(readonly=(not markRead))
            (retcode, messages) = conn.search(None, "(UNSEEN)")
        except Exception:
            logger.warning("抱歉,您的邮箱账户验证失败了,请检查下配置")
            return None

        if retcode == "OK" and messages != [b""]:
            numUnread = len(messages[0].split(b" "))
            if limit and numUnread > limit:
                return numUnread

            for num in messages[0].split(b" "):
                # parse email RFC822 format
                ret, data = conn.fetch(num, "(RFC822)")
                if data is None:
                    continue
                msg = email.message_from_string(data[0][1].decode("utf-8"))

                if not since or self.getDate(msg) > since:
                    msgs.append(msg)

        conn.close()
        conn.logout()

        return msgs
Example #4
0
 def receivemessage(self):
     mail = imaplib.IMAP4(self.receive_server, port=993)
     mail.login(self.login, self.password)
     mail.list()
     mail.select("inbox")
     if header:
         criterion = '(HEADER Subject "%s")' % header
     else:
         criterion = 'ALL'
     result, data = mail.uid('search', None, criterion)
     assert data[0], 'There are no letters with current header'
     latest_email_uid = data[0].split()[-1]
     result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
     raw_email = data[0][1]
     email_message = email.message_from_string(raw_email)
     print(email_message)
     mail.logout()
Example #5
0
 def run(self):
     try:
         imaplib.IMAP4(self.mailAddr, self.mailPort)
     except:
         print("[-]错误信息:服务器错误!")
         return 1
     if len(self.userLines) < 1 or len(self.passLines) < 1:
         print("[-]错误信息:字典文件中无内容,请检查!")
         return 1
     for index in range(len(self.userLines)):
         for i in range(len(self.passLines)):
             threadLock.acquire()
             loop.run_until_complete(
                 login(self.mailAddr, self.mailPort, self.userLines[index],
                       self.passLines[i]))
             threadLock.release()
             continue
Example #6
0
 def run(self):
     taskInfo = json.loads(self.message)
     taskId = taskInfo['taskId']
     operation = taskInfo['operation']
     if operation == 'test_account':
         username = taskInfo['username']
         password = taskInfo['password']
         pwd = DESTool.des_descrpt(str(password), str(username[0:8]))
         protocol = taskInfo['protocol']
         server_addr = taskInfo['server']
         port = taskInfo['port']
         useSSL = taskInfo['useSSL']
         if protocol == "imap":
             try:
                 if useSSL == "1":
                     server = imaplib.IMAP4_SSL(str(server_addr), port)
                 else:
                     server = imaplib.IMAP4(str(server_addr), port)
             except Exception, e:
                 result = "server_error"
             else:
                 try:
                     server.login(username, pwd)
                 except:
                     result = "account_error"
                 else:
                     server.logout()
                     result = "connect"
         elif protocol == "pop3":
             try:
                 if useSSL == "1":
                     server = poplib.POP3_SSL(str(server_addr), port)
                 else:
                     server = poplib.POP3(str(server_addr), port)
             except Exception, e:
                 result = "server_error"
             else:
                 try:
                     server.user(username)
                     server.pass_(pwd)
                 except:
                     result = "account_error"
                 else:
                     server.quit()
                     result = "connect"
Example #7
0
def _parse_contact(message):
    """
    Обработка контактов, добавление нового контакта в список авторизованных
    
    :param message: сообщение с контактной информацией
    :return: bool, True - сообщение обработано, False - ошибка обработки
    """
    # Проверяем, чтобы пользователь послал свои контактные данные
    if message.contact.user_id == message.from_user.id:
        host, domain, password = _conn_data()

        if not all([host, domain, password]):
            log.critical('В файле настроек параметры host, domain или password не найдены')
            return

        phone = str(message.contact.phone_number)
        
        # Проверяем существование почтового ящика, должен быть настроен заранее на почтовом сервере
        box = imaplib.IMAP4(host)
        data = box.login('%s@%s' % (phone, domain), password)
        box.logout()
        
        if data[0] == 'OK':
            phones_list = db.get('phones_list', [])

            if phone not in phones_list:
                phones_list.append(phone)
                
                db['phones_list'] = phones_list
            
            if phone not in db:
                db[phone] = message.chat.id
                db[str(message.from_user.id)] = db[phone]
                
                keyboard_hider = types.ReplyKeyboardRemove()
                bot.send_message(message.chat.id, 'Хорошо, я тебя запомнил', reply_markup=keyboard_hider)
            
            else:
                bot.send_message(message.chat.id, 'Виделись уже :)')
        else:
            bot.send_message(message.chat.id, 'Я тебя не узнаю!')
    else:
        bot.send_message(message.chat.id, 'Я сказал свой!')
    
    return True
Example #8
0
def worker(options):

    M = imaplib.IMAP4(host=options['MAIL_HOST'])
    M.login(options['MAIL_ADDRESS'], options['MAIL_PASSWORD'])
    M.select(readonly=True)
    typ, data = M.search(None, 'ALL')

    url_list = []
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
        # print 'Message %s\n%s\n' % (num, data[0][1])
        url = re.findall(
            r"(http://www.spamhaus.org/pbl/removal/verify/[_0-9]+)",
            data[0][1])
        if url:
            url_list.append(url[0])

    M.close()
    M.logout()

    pool = redis.ConnectionPool(host=options['REDIS_DB_HOST'],
                                port=options['REDIS_DB_PORT'],
                                db=options['REDIS_DB_NAME'])
    cli = redis.Redis(connection_pool=pool)

    for url in url_list:
        while True:
            try:
                requests.get(url)
                cli.sadd('email_check', url)
                break
            except requests.exceptions.RequestException as e:
                try:
                    requests.post(
                        'http://%s:%s/report' %
                        (options['WEB_SERVER_IP'], options['PORT']),
                        data={"info": "check email url Error:" + e.message})
                except requests.exceptions.RequestException as e:
                    print "Critical Error"
                    continue

    requests.post('http://%s:%s/report' %
                  (options['WEB_SERVER_IP'], options['PORT']),
                  data={"info": "check email: url... "})
    pool.disconnect()
Example #9
0
def confirm_email(user, proxy):
    counter = 0
    while not counter < 60:
        try:

            mail = imaplib.IMAP4("SERVER")

            mail.login("USER", "PASS")
            mail.select("INBOX")
            mail.list()

            result, data_mail = mail.search(None, '(TO {})'.format(user))

            ids = data_mail[0]
            id_list = ids.split()

            latest_email_id = id_list[-1]

            result, data_mail = mail.fetch(latest_email_id, "RFC822")
            raw_email = data_mail[0][1]
            raw_email = str(raw_email)
            url = raw_email[raw_email.find("Create My Account:") +
                            22:raw_email.find("Create My Account:") + 218]

            if not url.startswith("http"):
                continue
            try:
                requests.post(url, proxies=proxy, timeout=30)
            except Exception as e:
                print(e)
                mail.store(latest_email_id, '+FLAGS', '(\Deleted)')
                mail.expunge()
                mail.logout()
                return

            session_id = url[-19:]

            session_id = session_id.replace("\\", "")
            mail.store(latest_email_id, '+FLAGS', '(\Deleted)')
            mail.expunge()
            mail.logout()
            return session_id
        except Exception:
            counter += 1
            time.sleep(1)
Example #10
0
def getMail(mail_host, account, password, disk_root, port=465, ssl=1):
    my_path = disk_root + ':\\'
    if ssl == 1:
        imap_server = imaplib.IMAP4_SSL(mail_host, port)
    else:
        imap_server = imaplib.IMAP4(mail_host, port)
    imap_server.login(account, password)
    imap_server.select()
    resp, items = imap_server.search(None, "Unseen")
    number = 1
    for i in items[0].split():
        # get information of email
        resp, mail_data = imap_server.fetch(i, "(RFC822)")
        mail_text = mail_data[0][1]
        msg = email.message_from_string(mail_text)
        ls = msg["From"].split(' ')
        str_from = ''
        if (len(ls) == 2):
            from_name = email.Header.decode_header((ls[0]).strip('\"'))
            str_from = 'From : ' + myUnicode(from_name[0][0], from_name[0][1]) + ls[1]
        else:
            str_from = 'From : ' + msg["From"]
        str_date = 'Date : ' + msg["Date"]
        subject = email.Header.decode_header(msg["Subject"])
        sub = myUnicode(subject[0][0], subject[0][1])
        str_sub = 'Subject : ' + sub

        mail_content, suffix = parseEmail(msg, my_path)
        # 命令窗体输出邮件基本信息
        print '\n'
        print 'No : ' + str(number)
        print str_from
        print str_date
        print str_sub
        '''
        print 'Content:'
        print mailContent
        '''
        # 保存邮件正文
        if (suffix != None and suffix != '') and (mail_content != None and mail_content != ''):
            saveFile(str(number) + suffix, mail_content, my_path)
            number = number + 1

    imap_server.close()
    imap_server.logout()
Example #11
0
def fetchUnreadEmails(profile, since=None, markRead=False, limit=None):
    """
        Fetches a list of unread email objects from a user's email inbox.

        Arguments:
        profile -- contains information related to the user (e.g., email
                   address)
        since -- if provided, no emails before this date will be returned
        markRead -- if True, marks all returned emails as read in target inbox

        Returns:
        A list of unread email objects.
    """

    conn = imaplib.IMAP4(profile['email']['imap_server'],
                         profile['email']['imap_port'])
    conn.debug = 0
    conn.login(profile['email']['address'], profile['email']['password'])
    conn.select(readonly=(not markRead))

    msgs = []
    (retcode, messages) = conn.search(None, '(UNSEEN)')

    if retcode == 'OK' and messages != ['']:
        numUnread = len(messages[0].split(' '))
        if limit and numUnread > limit:
            return numUnread

        for num in messages[0].split(' '):
            # parse email RFC822 format
            ret, data = conn.fetch(num, '(RFC822)')
            if data is None:
                continue
            msg = email.message_from_string(data[0][1])

            if not since or getDate(msg) > since:
                msgs.append(msg)

            if isEchoEmail(msg, profile):
                conn.store(num, '+FLAGS', '\Seen')

    conn.close()
    conn.logout()

    return msgs
Example #12
0
 def __init__(self, server, port, recipient, password, use_ssl=True):
     # check for required param
     if not recipient:
         raise ValueError('You must provide a recipient email address')
     self.server = server
     self.port = port
     self.recipient = recipient
     self.password = password
     self.use_ssl = use_ssl
     self.recipient_folder = ''
     # instantiate our IMAP client object
     try:
         if self.use_ssl:
             self.imap = imaplib.IMAP4_SSL(self.server, self.port)
         else:
             self.imap = imaplib.IMAP4(self.server, self.port)
     except OSError as err:
         raise err
Example #13
0
def get_email(imap_url,
              imap_user,
              impa_password,
              mail_folder="INBOX",
              mail_search_str=''):
    mail = imaplib.IMAP4(imap_url)
    mail.login(imap_user, impa_password)
    mail.select(mail_folder)

    typ, msgs = mail.search(None, mail_search_str)
    msgs = msgs[0].split()
    message_list = []
    for emailid in msgs:
        resp, data = mail.fetch(emailid, "(RFC822)")
        email_body = data[0][1]
        m = email.message_from_bytes(email_body)
        message_list.append(m)
    return message_list
Example #14
0
    def __init__(self, **kwargs):
        self.servername = kwargs.get("host")
        self.serverport = kwargs.get("port")
        self.ssl = kwargs.get("ssl")
        self.username = kwargs.get("username")
        self.password = kwargs.get("password")
        self.address = kwargs.get("address")

        logs["imapclient"](repr(self))

        try:
            if self.ssl: self.conn = imaplib.IMAP4_SSL(self.servername)
            else: self.conn = imaplib.IMAP4(self.servername)
        except Exception as exc:
            print(exc)
        finally:
            self.conn.login(self.username, self.password)
            self.imapqueue = queue.Queue()
Example #15
0
 def relogin(self):
     if self.p3:
         self.p3.logout()
         self.p3.close()
         self.p3 = None
     try:
         if self.use_ssl:
             self.p3 = imaplib.IMAP4_SSL(
                 self.host, self.port and self.port
                 or imaplib.IMAP4_SSL_PORT)
         else:
             self.p3 = imaplib.IMAP4(
                 self.host, self.port and self.port or imaplib.IMAP4_PORT)
         #self.p3._debugging =1
         self.p3.login(self.user, self.passwd)
     except Exception, e:
         self.p3 = None
         logger.exception("login failed")
Example #16
0
 def __init__(self, host, port, username, password, remote_folder, ssl,
              exclude):
     if not ssl:
         self.mailbox = imaplib.IMAP4(host, port)
     else:
         self.mailbox = imaplib.IMAP4_SSL(host, port)
     self.mailbox.login(username, password)
     typ, data = self.mailbox.select(remote_folder, readonly=True)
     if typ != 'OK':
         # Handle case where Exchange/Outlook uses '.' path separator when
         # reporting subfolders. Adjust to use '/' on remote.
         adjust_remote_folder = re.sub('\.', '/', remote_folder)
         typ, data = self.mailbox.select(adjust_remote_folder,
                                         readonly=True)
         if typ != 'OK':
             logging.critical(
                 "MailboxClient: Could not select remote folder '%s'" %
                 remote_folder)
Example #17
0
 def get_imap_mail_count(self):
     """Returns the number of unseen mails in this IMAP4 account."""
     # if port is not set
     if self.port is None:
         # use the well known port for imap4
         port = 993
     else:
         port = self.port
     if self.use_ssl:
         imap = imaplib.IMAP4_SSL(self.host, port)
     else:
         imap = imaplib.IMAP4(self.host, port)
     imap.login(self.username, self.password)
     imap.select()
     typ, msgs = imap.search(None, "UNSEEN")
     imap.close()
     imap.logout()
     return len(msgs[0].split())
Example #18
0
 def __init__(self, host, username, pwd, port=993):
     self.host = host
     self.username = username
     self.pwd = pwd
     self.port = port
     self.resList = []
     self.db = pymysql.connect("localhost", "root", "mysql", "emailfetcher")
     self.cursor = self.db.cursor()
     try:
         self.serv = imaplib.IMAP4_SSL(self.host, self.port)
     except:
         self.serv = imaplib.IMAP4(self.host, self.port)
     self.serv.login(self.username, self.pwd)
     self.serv.select()
     self.index = None
     self.uid_pattern = re.compile(r'\d+ \(UID (\d+)\)')
     self.indices = list()
     self.utc = pytz.UTC
def main():
    with imaplib.IMAP4(url_) as M:
        M.noop()
        password = getpass.getpass()
        M.login('dilawars', password)
        M.select()
        #  typ, data = M.search(None, 'ALL')
        typ, data = M.search(None, '(UNSEEN)')
        print('Total new msg: %d' % len(data[0].split()))

        # FETCH?
        #for num in data[0].split():
        #    typ, data = M.fetch(num, '(SUBJECT FROM)')
        #    print('Message %s\n%s\n' % (num, data[0][1]))
        #    typ, data = M.store(num, '-FLAGS', '\\Seen')

        M.close()
        M.logout()
Example #20
0
    def connect_to_imapserver(self):
        """
        Connect to configured IMAP server.
        """
        # Debug Log Message
        logmsg = ("Start connecting to imap server")
        c.log_a_msg(self.queues["logger"], self.name, logmsg, "DEBUG")

        try:
            # connecting to the imap server
            if self.imap_info["security"] == 'ssl':
                server = imaplib.IMAP4_SSL(self.imap_info["server"],
                                           int(self.imap_info["port"]))
            else:
                server = imaplib.IMAP4(self.imap_info["server"],
                                       int(self.imap_info["port"]))

            if self.imap_info["security"] == 'starttls':
                server.starttls()

            server.login(self.imap_info["user"], self.imap_info["passwd"])
        except imaplib.IMAP4.abort:
            logmsg = "Login to server was aborted with security= " + self.imap_info["security"] + \
                     " , port= " + str(self.imap_info["port"])
            c.log_a_msg(self.queues["logger"], self.name, logmsg, "ERROR")
            return 0
        except imaplib.IMAP4.error:
            logmsg = "Got an error when trying to connect to the imap server with" + \
                     " security= " + self.imap_info["security"] + " , port= " + str(self.imap_info["port"])
            c.log_a_msg(self.queues["logger"], self.name, logmsg, "ERROR")
            return 0
        except Exception as e:
            logmsg = str(e)
            c.log_a_msg(self.queues["logger"], self.name, logmsg, "ERROR")
            logmsg = "Got an unknown exception when trying to connect to the imap " + \
                     "server with security= " + self.imap_info["security"] + " , port= " + str(self.imap_info["port"])
            c.log_a_msg(self.queues["logger"], self.name, logmsg, "ERROR")
            return 0

        logmsg = "Successfully logged into imap server with security= " + self.imap_info["security"] + \
                 " , port= " + str(self.imap_info["port"])
        c.log_a_msg(self.queues["logger"], self.name, logmsg, "INFO")

        return server
Example #21
0
def managesieve_test():
    # We don't have a Python sieve client, so we'll
    # just run the IMAP client and see what happens.
    import imaplib

    try:
        M = imaplib.IMAP4(hostname, 4190)
    except ConnectionRefusedError:
        # looks like fail2ban worked
        raise IsBlocked()

    try:
        M.login("fakeuser", "fakepassword")
        raise Exception("authentication didn't fail")
    except imaplib.IMAP4.error:
        # authentication should fail
        pass
    finally:
        M.logout()  # shuts down connection, has nothing to do with login()
Example #22
0
 def connect(self):
     assert (self._imap_hanlde == None)
     if self._imap_hanlde != None:
         return True
     try:
         logging.info("login IMAP server")
         if const.IMAP_SSL:
             self._imap_hanlde = imaplib.IMAP4_SSL(const.IMAP_ADDRESS,
                                                   const.IMAP_PORT)
         else:
             self._imap_hanlde = imaplib.IMAP4(const.IMAP_ADDRESS,
                                               const.IMAP_POR)
         self._imap_hanlde.login(const.IMAP_USER_NAME, const.IMAP_PASSWORD)
         logging.info("login IMAP server success")
         return True
     except Exception as e:
         logging.error(e)
         self.close()
         return False
Example #23
0
def main():
    # Look for the credentials in a well known file in several
    # locations relative to the location of this file.
    #
    # XXX Should make a command line option to set the mail dir
    #     directory we exepct to use.
    #
    username = None
    password = None
    for path in ('test_mode', '../test_mode'):
        creds_file = os.path.join(os.path.dirname(__file__), path,
                                  "test_mode_creds.txt")
        print "Looking for creds file {}".format(creds_file)
        if os.path.exists(creds_file):
            print "Using credentials file {}".format(creds_file)
            username, password = open(creds_file).read().strip().split(':')
            test_mode_dir = os.path.dirname(creds_file)
            break

    if username is None or password is None:
        raise RuntimeError("Unable to find test mode credentials")

    # Look for the address file in the same directory as the creds file
    #
    addr_file = os.path.join(test_mode_dir, 'test_mode_addr.txt')
    addr, port = open(addr_file).read().strip().split(':')
    port = int(port)

    print "Cleaning and setting up test-mode maildir"
    cleanup_test_mode_dir(test_mode_dir)

    imap = imaplib.IMAP4(addr, port)
    imap.login(username, password)

    for mbox_name in ('INBOX', 'Archive', 'Junk'):
        print "Selected '{}'".format(mbox_name)

        imap.select(mbox_name)
        do_baked_appends(test_mode_dir, imap, mbox_name)
        dump_all_messages(imap)

    imap.close()
    imap.logout()
Example #24
0
    def login_imap(cls, config, section, list_mailboxes):
        if config.getboolean(section, MailSpreader.CONFIG_FIELD_USE_SSL):
            imap_server = imaplib.IMAP4_SSL(
                host=config.get(section, MailSpreader.CONFIG_FIELD_HOST),
                port=config.get(section, MailSpreader.CONFIG_FIELD_PORT))
        else:
            imap_server = imaplib.IMAP4(
                host=config.get(section, MailSpreader.CONFIG_FIELD_HOST),
                port=config.get(section, MailSpreader.CONFIG_FIELD_PORT))

        imap_server.login(
            config.get(section, MailSpreader.CONFIG_FIELD_USERNAME),
            config.get(section, MailSpreader.CONFIG_FIELD_PASSWORD))

        if list_mailboxes:
            print('Mailboxes for %(username)s@%(host)s:' % config[section])
            for mailbox in imap_server.list()[1]:
                print(mailbox.decode())
        return imap_server
Example #25
0
    def connect_all(self, hostServer, port_smtp, port_imap):
        try:
            self.connect_smtp = smtplib.SMTP()
            self.connect_smtp.connect(hostServer, port_smtp)
            self.connect_pop3 = poplib.POP3_SSL(hostServer)
        except Exception as error:
            print error

        try:
            self.connect_imap = imaplib.IMAP4_SSL(hostServer, port_imap)
        except Exception as error:
            self.connect_imap = imaplib.IMAP4(hostServer, port_imap)
            print error

        try:
            self.connect_pop3 = poplib.POP3_SSL(hostServer)
        except Exception as error:
            self.connect_pop3 = poplib.POP3(hostServer)
            print error
    def validate(self):
        """Validate email id and check POP3/IMAP and SMTP connections is enabled."""
        if self.email_id:
            validate_email_add(self.email_id, True)

        if frappe.local.flags.in_patch or frappe.local.flags.in_test:
            return

        if not frappe.local.flags.in_install and not frappe.local.flags.in_patch:
            try:
                if self.use_imap:
                    if self.use_ssl:
                        test = imaplib.IMAP4_SSL(self.email_server)
                    else:
                        test = imaplib.IMAP4(self.email_server)

                else:
                    if self.use_ssl:
                        test = poplib.POP3_SSL(self.email_server)
                    else:
                        test = poplib.POP3(self.email_server)

            except Exception:
                frappe.throw("Incoming email account not correct")
                return None
            finally:
                try:
                    if self.use_imap:
                        test.logout()
                    else:
                        test.quit()
                except Exception:
                    pass
            try:
                if self.use_tls and not self.smtp_port:
                    self.port = 587
                sess = smtplib.SMTP((self.smtp_server or "").encode('utf-8'),
                                    cint(self.smtp_port) or None)
                sess.quit()
            except Exception as e:
                frappe.throw("Outgoing email account not correct")
                return None
        return
Example #27
0
def CheckIMAPServer(host, port, recipients, watchfor, sms, timeoutalert):
    """Parses through XML Object of Server and checks server as per type

    Returns nothing."""

    try:
        a = imaplib.IMAP4(host, int(port))
        MakeLog(
            now.strftime("%Y-%m-%d %H:%M") +
            ": Connected successfully to IMAP4 host '" + host + "' on port " +
            port)
    except:
        MakeLog(
            now.strftime("%Y-%m-%d %H:%M") +
            ": ERROR can't connect to IMAP4 host '" + host + "' on port " +
            port + " Error- " + str(sys.exc_info()[0]))
        CreateEmailMessage(
            recipients, "IMAP4 Error: Can't connect to '" + host + "' at " +
            now.strftime("%Y-%m-%d %H:%M"), "IMAP4", sms)
Example #28
0
    def _connect(self, target):
        data = getattr(self, target)
        auth = getattr(self, target + "_auth")

        self.logger.info("Connect to %s (%s)" % (target, data['host']))
        if data['port'] == 993:
            connection = imaplib.IMAP4_SSL(data['host'], data['port'])
        else:
            connection = imaplib.IMAP4(data['host'], data['port'])

        if len(auth) > 0:
            self.logger.info("Authenticate at %s" % target)
            connection.login(*auth)

        setattr(self, '_conn_%s' % target, connection)
        self.logger.info("%s connection established" % target)
        # Detecting delimiter on destination server
        code, mailbox_list = connection.list()
        self.delimiter = mailbox_list[0].split('"')[1]
Example #29
0
    def _listen(self):
        if self.UseDoDEmail:
            ArrivalEmail = "*****@*****.**"
        else:
            ArrivalEmail = "*****@*****.**"
        while self.Alive:
            date = (datetime.datetime.now() -
                    datetime.timedelta(1)).strftime("%d-%b-%Y")
            M = imaplib.IMAP4(self.email_incoming_svr,
                              self.email_incoming_port)
            if self.email_username is not None:
                response, details = M.login(self.email_username,
                                            self.email_userpw)
            M.select('INBOX')
            #Limit our search to Unseen Messages for our IMEI in the Past 24 Hours from Iridium Only
            response, items = M.search(
                None,
                '(UNSEEN SENTSINCE {date} HEADER Subject "SBD Msg From Unit: {IMEI}" FROM "{Email}")'
                .format(date=date, IMEI=self.IMEI, Email=ArrivalEmail))
            for emailid in items[0].split():
                response, data = M.fetch(emailid, '(RFC822)')
                mail = email.message_from_string(data[0][1])

                if not mail.is_multipart():
                    continue
                for part in mail.walk():
                    if part.is_multipart():
                        continue
                    if part.get('Content-Disposition') is None:
                        continue
                    file_nm = part.get_filename()
                    if file_nm is None:
                        continue
                    filename, fileext = os.path.splitext(file_nm)
                    if fileext != '.sbd':
                        continue
                    msg = part.get_payload(decode=True)
                    for line in msg.splitlines(True):
                        self.modem._process_incoming_nmea(line)
                    temp = M.store(emailid, '+FLAGS', '\\Seen')
            M.close()
            M.logout()
            sleep(self.email_check_rate * 60)  # Wait a minute and try again.
Example #30
0
 def is_authenticated(self, user, password):
     host = ""
     if self.configuration.has_option("auth", "imap_host"):
         host = self.configuration.get("auth", "imap_host")
     secure = True
     if self.configuration.has_option("auth", "imap_secure"):
         secure = self.configuration.getboolean("auth", "imap_secure")
     try:
         if ":" in host:
             address, port = host.rsplit(":", maxsplit=1)
         else:
             address, port = host, 143
         address, port = address.strip("[] "), int(port)
     except ValueError as e:
         raise RuntimeError("Failed to parse address %r: %s" %
                            (host, e)) from e
     if sys.version_info < (3, 4) and secure:
         raise RuntimeError("Secure IMAP is not availabe in Python < 3.4")
     try:
         connection = imaplib.IMAP4(host=address, port=port)
         try:
             if sys.version_info < (3, 4):
                 connection.starttls()
             else:
                 connection.starttls(ssl.create_default_context())
         except (imaplib.IMAP4.error, ssl.CertificateError) as e:
             if secure:
                 raise
             self.logger.debug("Failed to establish secure connection: %s",
                               e,
                               exc_info=True)
         try:
             connection.login(user, password)
         except imaplib.IMAP4.error as e:
             self.logger.debug("IMAP authentication failed: %s",
                               e,
                               exc_info=True)
             return False
         connection.logout()
         return True
     except (OSError, imaplib.IMAP4.error) as e:
         raise RuntimeError("Failed to communicate with IMAP server %r: "
                            "%s" % (host, e)) from e