def __enter__(self): self.conn = poplib.POP3_SSL(Config.MAIL_HOST) self.conn.user(Config.MAIL_USER) self.conn.pass_(Config.MAIL_PASSWD) self.mail_num = self.conn.stat()[0] return self
#-*- encoding: gb2312 -*- import os, sys, string import poplib # pop3服务器地址 host = "pop-mail.outlook.com" # 用名 username = "******" # 密码 password = "******" # 创建一个pop3对象,这个时候实际上已经连接上服务器了#hotmail使用SSL加密,端口995 pp = poplib.POP3_SSL(host) # 设置调试模式,可以看到与服务器的交互信息 # pp.set_debuglevel(1) # 向服务器发送用户名 pp.user(username) # 向服务器发送密码 pp.pass_(password) # 获取服务器上信件信息,返回是一个列表,第一项是一共有多上封邮件,第二项是共有多少字节 ret = pp.stat() print('Messages: %s. Size: %s' % ret) # 需要取出所有信件的头部,信件id是从1开始的。 for i in range(1, ret[0]+1): # 取出信件头部。注意:top指定的行数是以信件头为基数的,也就是说当取0行, # 其实是返回头部信息,取1行其实是返回头部信息之外再多1行。 mlist = pp.top(i, 0) print mlist[1]
import poplib from email.parser import Parser from email.header import decode_header from email.utils import parseaddr # 输入邮件地址, 口令和POP3服务器地址: email = input('Email:') password = input('Password:'******'pop3 server:') # 连接到POP3服务器: server = poplib.POP3_SSL(pop3_server) # 可以打开或关闭调试信息: server.set_debuglevel(1) # 可选:打印POP3服务器的欢迎文字: print(server.getwelcome().decode('utf-8')) # 身份认证: server.user(email) server.pass_(password) # stat()返回邮件数量和占用空间: print('Messages: %s. Size: %s' % server.stat()) # list()返回所有邮件的编号: resp, mails, octets = server.list() # 可以查看返回的列表 print(mails) # 获取最新一封邮件, 注意索引号从1开始: index = len(mails) resp, lines, octets = server.retr(index)
def connect(self): globs.log.write(1, 'EmailServer.Connect({})'.format(self.dump())) globs.log.write( 3, 'server={} keepalive={}'.format(self.server, self.keepalive)) # See if a server connection is already established # This is the most common case, so check this first if self.server != None: if self.keepalive is False: # Do we care about keepalives? return None globs.log.write(3, 'Cheeking server connection') if self.protocol == 'imap': try: status = self.server.noop()[0] except: status = 'NO' if status != 'OK': globs.log.write( 1, 'Server {} timed out. Reconnecting.'.format( self.address)) self.server = None self.connect() elif self.protocol == 'pop3': try: status = self.server.noop() except: status = '+NO' if status != '+OK': globs.log.write( 1, 'Server {} timed out. Reconnecting.'.format( self.address)) self.server = None self.connect() elif self.protocol == 'smtp': try: status = self.server.noop()[0] except: # smtplib.SMTPServerDisconnected status = -1 if status != 250: # Disconnected. Need to reconnect to server globs.log.write( 1, 'Server {} timed out. Reconnecting.'.format( self.address)) self.server = None self.connect() else: # Need to establish server connection if self.protocol == 'imap': globs.log.write(1, 'Initial connect using IMAP') try: if self.encryption is not None: self.server = imaplib.IMAP4_SSL( self.address, self.port) else: self.server = imaplib.IMAP4(self.address, self.port) retVal, data = self.server.login(self.accountname, self.passwd) globs.log.write( 3, 'IMAP Logged in. retVal={} data={}'.format( retVal, data)) retVal, data = self.server.select(self.folder) globs.log.write( 3, 'IMAP Setting folder. retVal={} data={}'.format( retVal, data)) return retVal except imaplib.IMAP4.error: return None except imaplib.socket.gaierror: return None elif self.protocol == 'pop3': globs.log.write(1, 'Initial connect using POP3') try: if self.encryption is not None: self.server = poplib.POP3_SSL(self.address, self.port) else: self.server = poplib.POP3(self.address, self.port) retVal = self.server.user(self.accountname) globs.log.write(3, 'Logged in. retVal={}'.format(retVal)) retVal = self.server.pass_(self.passwd) globs.log.write( 3, 'Entered password. retVal={}'.format(retVal)) return retVal.decode() except Exception: return None elif self.protocol == 'smtp': globs.log.write(1, 'Initial connect using SMTP') try: self.server = smtplib.SMTP('{}:{}'.format( self.address, self.port)) if self.encryption is not None: # Do we need to use SSL/TLS? self.server.starttls() retVal, retMsg = self.server.login(self.accountname, self.passwd) globs.log.write( 3, 'Logged in. retVal={} retMsg={}'.format( retVal, retMsg)) return retMsg.decode() except (smtplib.SMTPAuthenticationError, smtplib.SMTPConnectError, smtplib.SMTPSenderRefused): return None else: # Bad protocol specification globs.log.err( 'Invalid protocol specification: {}. Aborting program.'. format(self.protocol)) globs.closeEverythingAndExit(1) return None return None
def process_queue(q, logger): logger.info("***** %s: Begin processing mail for django-helpdesk" % ctime()) if q.socks_proxy_type and q.socks_proxy_host and q.socks_proxy_port: try: import socks except ImportError: no_socks_msg = "Queue has been configured with proxy settings, " \ "but no socks library was installed. Try to " \ "install PySocks via PyPI." logger.error(no_socks_msg) raise ImportError(no_socks_msg) proxy_type = { 'socks4': socks.SOCKS4, 'socks5': socks.SOCKS5, }.get(q.socks_proxy_type) socks.set_default_proxy(proxy_type=proxy_type, addr=q.socks_proxy_host, port=q.socks_proxy_port) socket.socket = socks.socksocket elif six.PY2: socket.socket = socket._socketobject email_box_type = settings.QUEUE_EMAIL_BOX_TYPE or q.email_box_type if email_box_type == 'pop3': if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL: if not q.email_box_port: q.email_box_port = 995 server = poplib.POP3_SSL( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) else: if not q.email_box_port: q.email_box_port = 110 server = poplib.POP3( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) logger.info("Attempting POP3 server login") server.getwelcome() server.user(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER) server.pass_(q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD) messagesInfo = server.list()[1] logger.info("Received %d messages from POP3 server" % len(messagesInfo)) for msg in messagesInfo: msgNum = msg.split(" ")[0] logger.info("Processing message %s" % msgNum) full_message = "\n".join(server.retr(msgNum)[1]) ticket = ticket_from_message(message=full_message, queue=q, logger=logger) if ticket: server.dele(msgNum) logger.info( "Successfully processed message %s, deleted from POP3 server" % msgNum) else: logger.warn( "Message %s was not successfully processed, and will be left on POP3 server" % msgNum) server.quit() elif email_box_type == 'imap': if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL: if not q.email_box_port: q.email_box_port = 993 server = imaplib.IMAP4_SSL( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) else: if not q.email_box_port: q.email_box_port = 143 server = imaplib.IMAP4( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) logger.info("Attempting IMAP server login") server.login(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER, q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD) server.select(q.email_box_imap_folder) status, data = server.search(None, 'NOT', 'DELETED') if data: msgnums = data[0].split() logger.info("Received %d messages from IMAP server" % len(msgnums)) for num in msgnums: logger.info("Processing message %s" % num) status, data = server.fetch(num, '(RFC822)') ticket = ticket_from_message(message=encoding.smart_text( data[0][1], errors='replace'), queue=q, logger=logger) if ticket: server.store(num, '+FLAGS', '\\Deleted') logger.info( "Successfully processed message %s, deleted from IMAP server" % num) else: logger.warn( "Message %s was not successfully processed, and will be left on IMAP server" % num) server.expunge() server.close() server.logout() elif email_box_type == 'local': mail_dir = q.email_box_local_dir or '/var/lib/mail/helpdesk/' mail = [ join(mail_dir, f) for f in listdir(mail_dir) if isfile(join(mail_dir, f)) ] logger.info("Found %d messages in local mailbox directory" % len(mail)) logger.info("Found %d messages in local mailbox directory" % len(mail)) for i, m in enumerate(mail, 1): logger.info("Processing message %d" % i) with open(m, 'r') as f: ticket = ticket_from_message(message=f.read(), queue=q, logger=logger) if ticket: logger.info( "Successfully processed message %d, ticket/comment created." % i) try: unlink(m) # delete message file if ticket was successful except: logger.error("Unable to delete message %d." % i) else: logger.info("Successfully deleted message %d." % i) else: logger.warn( "Message %d was not successfully processed, and will be left in local directory" % i)
import poplib, mimetypes, time, datetime, os, re from email import parser from confVariables import * if (int(global_email_uses_SSL)): pop_conn = poplib.POP3_SSL(global_email_Server_Name) else: pop_conn = poplib.POP3(global_email_Server_Name) pop_conn.user(global_email_Main_User_Name) pop_conn.pass_(global_email_Mail_User_Password) #Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] #Comment this part to keep emails. If you want to delete #emails off of the server, then uncomment this for i in range(1, len(pop_conn.list()[1]) + 1): pop_conn.dele(i) # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print "email found\n" now = datetime.datetime.now() timestamp = now.strftime("%Y%j%H%M%S%f") tempString = ('email/' + timestamp + '/') os.makedirs(tempString) filename1 = 'info.info'
#!/usr/bin/python3 import poplib, getpass, sys, mailconfig mailserver = mailconfig.popservername mailuser = mailconfig.popusername mailpasswd = open(mailconfig.poppasswdfile).readlines()[0] print('Connecting...') server = poplib.POP3_SSL(mailserver) server.user(mailuser) server.pass_(mailpasswd) try: print(server.getwelcome()) # msgCount = len(server.list())[1] msgCount, msgBytes = server.stat() print('There are', msgCount, 'mail messages in', msgBytes, 'bytes') print(server.list()) print('-' * 80) input('[press Enter key]') for i in range(msgCount): hdr, message, octets = server.retr(i + 1) # octets = bytes for line in message: print(line.decode()) print('-' * 80) if i < msgCount - 1: input('[press Enter key]') finally: server.quit() print('Bye.')
""" A Pop-3 Mail Filter Python comes with a library called poplib for downloading email messages. Write a script that downloads email messages from a server and attempts to classify them. What are the different properties of an email message and how might you build a feature extraction function to take advantage of these? """ import poplib from email import parser import re pop = poplib.POP3_SSL('pop.gmail.com') pop.user('*****@*****.**') pop.pass_('passwordwithheld") messages = [pop.retr(i) for i in range(1, len(pop.list()[1]) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] pop_conn.quit() def get_words(doc): splitter = re.compile("\\W*") words = [s.lower() for s in splitter.split(doc) if len(s) > 2 and len(s) < 20] return dict([(w, 1) for w in words])
def process_queue(q, quiet=False): if not quiet: print "Processing: %s" % q if q.socks_proxy_type and q.socks_proxy_host and q.socks_proxy_port: try: import socks except ImportError: raise ImportError( "Queue has been configured with proxy settings, but no socks library was installed. Try to install PySocks via pypi." ) proxy_type = { 'socks4': socks.SOCKS4, 'socks5': socks.SOCKS5, }.get(q.socks_proxy_type) socks.set_default_proxy(proxy_type=proxy_type, addr=q.socks_proxy_host, port=q.socks_proxy_port) socket.socket = socks.socksocket else: socket.socket = socket._socketobject email_box_type = settings.QUEUE_EMAIL_BOX_TYPE if settings.QUEUE_EMAIL_BOX_TYPE else q.email_box_type if email_box_type == 'pop3': if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL: if not q.email_box_port: q.email_box_port = 995 server = poplib.POP3_SSL( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) else: if not q.email_box_port: q.email_box_port = 110 server = poplib.POP3( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) server.getwelcome() server.user(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER) server.pass_(q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD) messagesInfo = server.list()[1] for msg in messagesInfo: msgNum = msg.split(" ")[0] msgSize = msg.split(" ")[1] full_message = "\n".join(server.retr(msgNum)[1]) ticket = ticket_from_message(message=full_message, queue=q, quiet=quiet) if ticket: server.dele(msgNum) server.quit() elif email_box_type == 'imap': if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL: if not q.email_box_port: q.email_box_port = 993 server = imaplib.IMAP4_SSL( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) else: if not q.email_box_port: q.email_box_port = 143 server = imaplib.IMAP4( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) server.login(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER, q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD) server.select(q.email_box_imap_folder) status, data = server.search(None, 'NOT', 'DELETED') if data: msgnums = data[0].split() for num in msgnums: status, data = server.fetch(num, '(RFC822)') ticket = ticket_from_message(message=data[0][1], queue=q, quiet=quiet) if ticket: server.store(num, '+FLAGS', '\\Deleted') server.expunge() server.close() server.logout()
import poplib serv = poplib.POP3_SSL('tamdil.iitg.ernet.in', '995') # replace tamdil with your IITG Webmail server serv.user('username') serv.pass_('password')
def recibir_facturas(self, cr, uid, ids, context=None): revisados = self.pool.get("messages_server") facturas = self.pool.get("account.invoice") lineas = self.pool.get("account.invoice.line") partners = self.pool.get("res.partner") rechazo_obj = self.pool.get("ae.rechazadas") for ir in self.browse(cr, uid, ids, context): #conectando if ir.i_layer is True: m = poplib.POP3_SSL(ir.i_server, ir.i_port) else: m = poplib.POP3(ir.i_server, ir.i_port) m.user(ir.i_user) m.pass_(ir.i_pass) #leyendo los mails mensajes = len(m.list()[1]) for i in range(mensajes): response, headerLines, bytes = m.retr(i + 1) mensaje = '\n'.join(headerLines) p = Parser() email = p.parsestr(mensaje) if email.is_multipart(): part_count = 0 for part in email.get_payload(): part_count = part_count + 1 tipo = part.get_content_type() if tipo == "application/xml" or tipo == "text/xml": try: fp = open('fact_process.xml', 'wb') fp.write(part.get_payload(decode=True)) fp.close() doc = minidom.parse('fact_process.xml') except: rechazo_obj.create(cr, uid, { 'name': "XML No Válido", 'descripcion': email }) continue tagFolio = "tfd:TimbreFiscalDigital" foli = "" try: folio = 0 folio = doc.getElementsByTagName(tagFolio)[0] foli = folio.getAttribute('UUID') print(("Folio de la factura" + str(foli))) except: rechazo_obj.create(cr, uid, { 'name': "UUID No Encontado", 'descripcion': doc }) print("Rompiendo el cicle X") continue #print(lFolio) try: tagEmpresa = 'cfdi:Receptor' empresa = doc.getElementsByTagName(tagEmpresa)[0] nempresa = empresa.getAttribute('rfc') print(("Nombre empresa " + nempresa)) u_obj = self.pool.get("res.users") print("Aqui 1") con = False print("Aqui 2") print(("User id " + str(uid))) print("Aqui 3") for cp in u_obj.browse(cr, uid, [uid]): print("Aqui 4") print(("Probando " + nempresa + "VS" + cp.company_id.rfc)) print((str(nempresa != cp.company_id.rfc))) print("Aqui 4") if nempresa != cp.company_id.rfc: print("Broken") rechazo_obj.create(cr, uid, { 'name': "Empresas no coinciden", 'descripcion': nempresa + " VS " + cp.company_id.name }) con = True if con: print("Rompido") continue except: print("Aqui se rompio") rechazo_obj.create(cr, uid, { 'name': "Empresa no coincide", 'descripcion': email }) continue #revisar que no existe ya el registro print("Aqui 5") idm = revisados.search(cr, uid, [('name', '=', foli), ('cancelada', '=', False)]) print("Aqui 6") ids_e = len(revisados.browse(cr, uid, idm, context)) print(ids_e) print("Aqui 7") if ids_e == 0: print("Creando Factura") #leyendo la fecha tagComprobante = 'cfdi:Comprobante' fe = doc.getElementsByTagName(tagComprobante)[0] fecha = fe.getAttribute('fecha') print(('Fecha: ' + fecha[0:10])) iva = 0.0 riva = 0.0 risr = 0.0 try: print("Buscando Impuestos") ti = 'cfdi:Traslado' liva = doc.getElementsByTagName(ti)[0] print("Existe el IVA 0") siva = str(liva.getAttribute('importe')) print(("Valor del IVA" + siva)) print((type(siva))) print((float(siva))) print("X") iva = float(siva) print(("EL IVA ES POR " + str(iva))) print("Mensaje x") ti2 = 'cfdi:Retencion' elemento = doc.getElementsByTagName(ti2)[0] print(("Que raro" + str(elemento))) for lret in doc.getElementsByTagName(ti2): print("Retención encontrada") impuesto = lret.getAttribute('impuesto') print(("Es XX " + impuesto)) if impuesto == "IVA": print("Es IVA") riva = float(lret.getAttribute( 'importe')) print(("Retencion " + str(riva))) print("No Es IVA") if impuesto == "ISR": print("Es ISR") risr = float(lret.getAttribute( 'importe')) print(("Retencion " + str(risr))) print("Sali del ciclo") except: print("Impuesto no encontrado") #leyendo el RFC de quien emite la factura print("Continuando") tagEmisor = 'cfdi:Emisor' emisor = doc.getElementsByTagName(tagEmisor)[0] rfc = emisor.getAttribute('rfc') print(("Proveedr: " + rfc)) #buscando al cliente por rfc id_proveedor = 0 print("Aqui 8") par = partners.search(cr, uid, [('vat', '=', rfc)]) print("Aqui 9") iP = len(partners.browse(cr, uid, par, context)) print("Aqui 10") if iP == 0: print("Aqui 11") rfc = "MX" + rfc print("Aqui 12") par = partners.search(cr, uid, [('vat', '=', rfc)]) print("Aqui 13") iP = len(partners.browse(cr, uid, par, context)) if iP == 0: mensaje = 'No existe el proveedor con RFC' print(('Error de Proveedor' + mensaje + ': ' + rfc)) rechazo_obj.create(cr, uid, { 'name': emisor, 'rfc': rfc, 'descripcion': "RFC No Encontrado" }) continue for i in partners.browse(cr, uid, par, context): id_proveedor = i.id #creando la factura id_fact = facturas.create(cr, uid, { 'partner_id': id_proveedor, 'date_invoice': fecha[0:10], 'account_id': 209, 'journal_id': 2, 'type': 'in_invoice', 'reference_type': 'none', 'currency_id': 34, 'iva': iva, 'retiva': riva, 'retisr': risr, }, context) #leyendo los conceptos de compra #print("Productos") tagConcepto = 'cfdi:Concepto' prods = doc.getElementsByTagName(tagConcepto) for prod in prods: cantidad = prod.getAttribute('cantidad') desc = prod.getAttribute('descripcion') precio = prod.getAttribute('valorUnitario') #print("") #print(" Cant.: " + cantidad) #print(" Desc.: " + desc.encode("latin1")) #print(" Precio: " + precio) #creando las lineas de la factura lineas.create(cr, uid, { 'invoice_id': id_fact, 'name': desc, 'quantity': cantidad, 'price_unit': precio, 'account_id': 28131, }, context) #Colocando los impuestos for fa in facturas.browse(cr, uid, [id_fact]): total = fa.amount_total + iva - riva - risr facturas.write(cr, uid, [fa.id], {'total': total}) #creando el registro de guardado revisados.create(cr, uid, { 'name': foli, 'from': email["From"], 'to': email["To"], 'fact': id_fact, 'fecha': fecha[0:10], 'proveedor': id_proveedor, }, context) return True
def eliminar_movimientos(self, cr, uid, ids, context=None): revisados = self.pool.get("messages_server") facturas = self.pool.get("account.invoice") rechazo_obj = self.pool.get("ae.rechazadas") move_obj = self.pool.get("account.move") for ir in self.browse(cr, uid, ids, context): #conectando if ir.i_layer is True: m = poplib.POP3_SSL(ir.i_server, ir.i_port) else: m = poplib.POP3(ir.i_server, ir.i_port) m.user(ir.i_user) m.pass_(ir.i_pass) #leyendo los mails mensajes = len(m.list()[1]) for i in range(mensajes): response, headerLines, bytes = m.retr(i + 1) mensaje = '\n'.join(headerLines) p = Parser() email = p.parsestr(mensaje) if email.is_multipart(): part_count = 0 for part in email.get_payload(): part_count = part_count + 1 tipo = part.get_content_type() if tipo == "application/xml" or tipo == "text/xml": try: fp = open('fact_process.xml', 'wb') fp.write(part.get_payload(decode=True)) fp.close() doc = minidom.parse('fact_process.xml') except: rechazo_obj.create(cr, uid, { 'name': "XML No Válido", 'descripcion': email }) continue tagFolio = "tfd:TimbreFiscalDigital" foli = "" try: folio = 0 folio = doc.getElementsByTagName(tagFolio)[0] foli = folio.getAttribute('UUID') print(("Folio de la factura" + str(foli))) except: rechazo_obj.create(cr, uid, { 'name': "UUID No Encontado", 'descripcion': doc }) print("Rompiendo el cicle X") continue #print(lFolio) #print("Eiminando" + str(foli)) for ms in revisados.browse(cr, uid, revisados.search(cr, uid, [('name', '=', foli)])): if(ms.fact and ms.fact.move_id): try: move_obj.write(cr, uid, [ms.fact.move_id.id], {'state': 'draft'}) move_obj.unlink(cr, uid, [ms.fact.move_id.id]) except: print("Movimiento no eliminado") try: facturas.unlink(cr, uid, [ms.fact.id]) except: print("Factura no eliminada") try: revisados.unlink(cr, uid, [ms.id]) except: print(("No se elimino " + str(foli))) return True
def sendMail(mail, filename=None): """ Send an e-mail to a real SMTP server, depending on the sender's configuration. First, the configuration is checked, then (if necessary), a POP-before-SMTP authentication is performed before actually sending the mail. """ import poplib, smtplib global popchecktime, mailaccounts, waitafterpop, debuglevel # find mail configuration for the sender's mail account account = getMailAccount(mail.frm) if account == None: mlog.logerr('No account data found for ' + mail.frm + ' (' + filename + ')') return False # First do POP-Before-SMTP, if necessary if account.rPBS and (popchecktime + account.rpopcheckdelay) < time.time(): try: mlog.log("Performing Pop-before-SMTP") M = poplib.POP3_SSL(account.rpophost, account.rpopport) M.user(account.rpopuser) M.pass_(account.rpoppass) M.quit() popchecktime = time.time() time.sleep(waitafterpop) except: mlog.logerr('POP-before-SMTP caught exception: ' + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])) return False # Send mail try: mlog.log("Sending mail from: " + mail.frm + " to: " + ",".join(mail.to)) mlog.logdebug("Port: " + str(account.rsmtpport)) smtpFunc = smtplib.SMTP if account.rsmtpsecurity == 'ssl': smtpFunc = smtplib.SMTP_SSL mlog.log("Using SSL") if account.localhostname != None: server = smtpFunc(account.rsmtphost, account.rsmtpport, account.localhostname) else: server = smtpFunc(account.rsmtphost, account.rsmtpport) server.set_debuglevel(debuglevel) server.ehlo() if account.rsmtpsecurity == 'tls': mlog.log("Using TLS") server.starttls() server.ehlo() if account.rsmtpuser != None: try: server.login(account.rsmtpuser, account.rsmtppass) except smtplib.SMTPAuthenticationError: # There is a problem with the python smtplib: the login() method doesn't try # the other authentication methods, even when the server tell to do so. # So we have to try it for ourselves. # For now, only the PLAIN authentication method is tried. (code, resp) = server.docmd( "AUTH", "PLAIN " + encode_plain(account.rsmtpuser, account.rsmtppass)) mlog.log("authentication. Code = " + str(code) + ", response = " + resp) if code == 535: mlog.logerr('Authentication error') server.sendmail(mail.frm, mail.to, mail.msg) server.quit() except: # TODO: check Greylist errror mlog.logerr('SMTP caught exception: ' + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])) return False return True
# We will check later if the mail is coming from a specific address # So that only one e-mail address can shutdown your computer # And you will decide that e-mail address #------------------------------------- #check the mail is came from the correct address # for example; # assume you enter '*****@*****.**' to from_addr # we will check it later if the mail is coming from '*****@*****.**' from_addr = input("From address: ") while True: #connect gmail pop_conn = poplib.POP3_SSL('pop.gmail.com') #make sure we are connected to POP, get POP-WELCOME message print("\n" + str(pop_conn.getwelcome())[6:50]) pop_conn.user('*****@*****.**') #e-mail address pop_conn.pass_('my_mail_password') #password #check how many mails we have mail_info = pop_conn.stat() print("Number of new emails: %s (%s bytes)" % mail_info) nmails = mail_info[0] #search for SUBJECT-FROM-DATE elements in the mails
def process_queue(q, logger): logger.info("***** %s: Begin processing mail for django-helpdesk" % ctime()) if q.socks_proxy_type and q.socks_proxy_host and q.socks_proxy_port: try: import socks except ImportError: no_socks_msg = "Queue has been configured with proxy settings, " \ "but no socks library was installed. Try to " \ "install PySocks via PyPI." logger.error(no_socks_msg) raise ImportError(no_socks_msg) proxy_type = { 'socks4': socks.SOCKS4, 'socks5': socks.SOCKS5, }.get(q.socks_proxy_type) socks.set_default_proxy(proxy_type=proxy_type, addr=q.socks_proxy_host, port=q.socks_proxy_port) socket.socket = socks.socksocket elif six.PY2: socket.socket = socket._socketobject email_box_type = settings.QUEUE_EMAIL_BOX_TYPE or q.email_box_type if email_box_type == 'pop3': if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL: if not q.email_box_port: q.email_box_port = 995 server = poplib.POP3_SSL( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) else: if not q.email_box_port: q.email_box_port = 110 server = poplib.POP3( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) logger.info("Attempting POP3 server login") server.getwelcome() server.user(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER) server.pass_(q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD) messagesInfo = server.list()[1] logger.info("Received %d messages from POP3 server" % len(messagesInfo)) for msgRaw in messagesInfo: if six.PY3 and type(msgRaw) is bytes: # in py3, msgRaw may be a bytes object, decode to str try: msg = msgRaw.decode("utf-8") except UnicodeError: # if couldn't decode easily, just leave it raw msg = msgRaw else: # already a str msg = msgRaw msgNum = msg.split(" ")[0] logger.info("Processing message %s" % msgNum) if six.PY2: full_message = encoding.force_text("\n".join( server.retr(msgNum)[1]), errors='replace') else: popmsg = [] for line in server.retr(msgNum)[1]: popmsg.append(line.encode()) full_message = encoding.force_text(b"\n".join(popmsg), errors='replace') ticket = ticket_from_message(message=full_message, queue=q, logger=logger) if ticket: server.dele(msgNum) logger.info( "Successfully processed message %s, deleted from POP3 server" % msgNum) else: logger.warn( "Message %s was not successfully processed, and will be left on POP3 server" % msgNum) server.quit() elif email_box_type == 'imap': if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL: if not q.email_box_port: q.email_box_port = 993 server = imaplib.IMAP4_SSL( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) else: if not q.email_box_port: q.email_box_port = 143 server = imaplib.IMAP4( q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST, int(q.email_box_port)) logger.info("Attempting IMAP server login") try: server.login(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER, q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD) server.select(q.email_box_imap_folder) except imaplib.IMAP.abort: logger.error( "IMAP login failed. Check that the server is accessible and that the username and password are correct." ) server.logout() sys.exit() except ssl.SSLError: logger.error( "IMAP login failed due to SSL error. This is often due to a timeout. Please check your connection and try again." ) server.logout() sys.exit() try: status, data = server.search(None, 'NOT', 'DELETED') except imaplib.IMAP4.error: logger.error( "IMAP retrieve failed. Is the folder '%s' spelled correctly, and does it exist on the server?" % q.email_box_imap_folder) if data: msgnums = data[0].split() logger.info("Received %d messages from IMAP server" % len(msgnums)) for num in msgnums: logger.info("Processing message %s" % num) status, data = server.fetch(num, '(RFC822)') full_message = encoding.force_text(data[0][1], errors='replace') ticket = ticket_from_message(message=full_message, queue=q, logger=logger) if ticket: server.store(num, '+FLAGS', '\\Deleted') logger.info( "Successfully processed message %s, deleted from IMAP server" % num) else: logger.warn( "Message %s was not successfully processed, and will be left on IMAP server" % num) server.expunge() server.close() server.logout() elif email_box_type == 'local': mail_dir = q.email_box_local_dir or '/var/lib/mail/helpdesk/' mail = [ join(mail_dir, f) for f in listdir(mail_dir) if isfile(join(mail_dir, f)) ] logger.info("Found %d messages in local mailbox directory" % len(mail)) logger.info("Found %d messages in local mailbox directory" % len(mail)) for i, m in enumerate(mail, 1): logger.info("Processing message %d" % i) with open(m, 'r') as f: full_message = encoding.force_text(f.read(), errors='replace') ticket = ticket_from_message(message=full_message, queue=q, logger=logger) if ticket: logger.info( "Successfully processed message %d, ticket/comment created." % i) try: unlink(m) # delete message file if ticket was successful except OSError: logger.error("Unable to delete message %d." % i) else: logger.info("Successfully deleted message %d." % i) else: logger.warn( "Message %d was not successfully processed, and will be left in local directory" % i)
#end if # def utf8_to_mbs(s): return s.decode("utf-8").encode(__g_codeset) # def mbs_to_utf8(s): return s.decode(__g_codeset).encode("utf-8") # host = 'pop-mail.outlook.com' username = '******' password = '******' print('begin pop') pop_conn = poplib.POP3_SSL(host) pop_conn.user(username) pop_conn.pass_(password) print('end pop') pop_conn.set_debuglevel(1) #Get messages from server: # 获得邮件 num = len(pop_conn.list()[1]) #邮件总数 if num < 5: #当总邮件数目小于5的时候读取所有邮件 num2 = 0 else: num2 = num-5 for i in range(num,num2,-1): messages = pop_conn.retr(i) #messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
success = [] try: users = open(sys.argv[1], "r").readlines() except(IOError): print "[-] Error: Check your userlist path\n" sys.exit(1) try: words = open(sys.argv[2], "r").readlines() except(IOError): print "[-] Error: Check your wordlist path\n" sys.exit(1) try: pop = poplib.POP3_SSL(server,995) welcome = pop.getwelcome() print welcome pop.quit() except (poplib.error_proto): welcome = "No Response" pass def mailbruteforce(listuser,listpwd): if len(listuser) < 1 or len(listpwd) < 1 : print "An error occurred: No user or pass list" return 1 for user in listuser: for value in listpwd : user = user.replace("\n","") value = value.replace("\n","")
def setUp(self): self.server = DummyPOP3Server((HOST, 0)) self.server.handler = DummyPOP3_SSLHandler self.server.start() self.client = poplib.POP3_SSL(self.server.host, self.server.port)
# Then it will have to do if nothing better comes along this_ticket['Description'] = part.get_payload() # Hope that there was some valid part of that message. command_line = [] for k in this_ticket.keys(): command_line.append("--" + k + "=" + this_ticket[k]) t = smcli.typical_create_program(smcli.SERVICE_DESK, command_line, 'create') if close_immediately: smcli.typical_update_program(smcli.SERVICE_DESK, ["--call-id", t], 'close') if protocol[:3] == 'POP': if protocol[-1] == 'S' or protocol[-3:] == "SSL": if port is None: M = poplib.POP3_SSL(server) else: M = poplib.POP3_SSL(server, port) else: if port is None: M = poplib.POP3(server) else: M = poplib.POP3(server, port) M.user(username) M.pass_(password) M.list() (numMsgs, totalSize) = M.stat() for i in range(1, numMsgs + 1): (header, msglines, octets) = M.retr(i) msg = email.message_from_string(string.join(msglines, "\n")) message_to_ticket(msg) # Finish this bit elif protocol[:4] == "IMAP": if protocol[-1] == "S" or protocol[-3:] == "SSL":