def get_redirect_url(self, *args, **kwargs): pk = self.kwargs.get('pk') mail = imaplib.IMAP4_SSL('imap.gmail.com') user = self.request.user compania = Compania.objects.get(pk=pk) print(compania) assert compania.correo_intercambio, "No hay correo" assert compania.pass_correo_intercambio, "No hay password" correo = compania.correo_intercambio.strip() passw = compania.pass_correo_intercambio.strip() print(correo, passw) try: mail.login(correo, passw) except imaplib.IMAP4.error as e: messages.error(self.request, str(e)) return reverse_lazy('intercambios:lista', kwargs={'pk': pk}) mail.list() mail.select("inbox") result, data = mail.search(None, "ALL") id_list = data[0].split() try: last_email = Intercambio.objects.latest('codigo_email') except Intercambio.DoesNotExist: last_email = 0 last_email_code = int(id_list[-1].decode()) if last_email == 0: local_last_email_code = last_email else: local_last_email_code = int(last_email.codigo_email) if last_email_code > local_last_email_code: new_elements = last_email_code - local_last_email_code else: messages.info(self.request, "No posee nuevos correos") return reverse_lazy('intercambios:lista', kwargs={'pk': pk}) if new_elements == 1: latest_emails = [id_list[-1]] else: latest_emails = id_list[-new_elements:] for element in latest_emails: result, email_data = mail.fetch(element, "(RFC822)") raw_email = email_data[0][1] raw_multipart = email.message_from_bytes(raw_email) raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) attachment_count, attachments = self.get_attachment(raw_multipart) remisor_name, remisor_email = self.get_remisor( str( email.header.make_header( email.header.decode_header(email_message['From'])))) Intercambio.objects.create( codigo_email=element.decode(), receptor=compania, remisor=remisor_name, email_remisor=remisor_email, fecha_de_recepcion=self.get_received_time( str( email.header.make_header( email.header.decode_header( email_message['Received'])))), cantidad_dte=attachment_count, titulo=str( email.header.make_header( email.header.decode_header(email_message['Subject']))), contenido=self.get_body(raw_multipart).decode('latin-1')) messages.success(self.request, "Cantidad de correos nuevos: {}".format(new_elements)) return reverse_lazy('intercambios:lista', kwargs={'pk': pk})
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 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 email import getpass import imaplib import os mail = imaplib.IMAP4_SSL('imap.gmail.com',993) user = input("Please enter the gmail usename: ") password = getpass.getpass("Enter the password: "******"INBOX") def loop(): mail.select("INBOX") unread_mails = 0 (retcode,messages) = mail.search(None,'(Unseen)') if retcode == 'OK': for num in messages[0].split(): unread_mails += 1 print(unread_mails) if __name__ == '__main__': try: while True: loop() finally: print("Thanks")
fControl = open(CONTROL_FILE_LOCATION) strSwitch = fControl.read() fControl.close() # log ts = time.time() strTime = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') strLog = strTime + " --> Refreshing emails..." + " \n" #f1 = open(LOG_FILE_LOCATION, "a+") #f1.write(strLog) #f1.close() print(strLog) # open emails M = imaplib.IMAP4_SSL(SMTP_SERVER) M.login(FROM_EMAIL, FROM_PWD) M.select('inbox') typ, data = M.search(None, 'UNSEEN') # loop through UNSEEN emails for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') for response_part in data: if isinstance(response_part, tuple): # search email msg strEmail = response_part[1].decode() strMsg = email.message_from_string(strEmail) print(strMsg['from'])
def connect(self, server, user, password) -> object: m = imaplib.IMAP4_SSL(self.server) m.login(self.user, self.password) m.select() logger.info("Connected to the mail server") return m
def doProbe(args): global verbose, host, port, ssltls, authtype, user, passwd, timeout foundHost = None foundPort = None foundSsl = None foundSrvr = None if len(args) < 2: print >> sys.stderr, "Email address required" print >> sys.stderr, "--help for more info" return 2 emailAddr = args[1] hhost = host user, h, p = parseEmail(emailAddr, user, host, port) if not host: host = h if not port: port = p if not timeout: timeout = 10 socket.setdefaulttimeout(timeout) if hhost: h = hhost pfxs = ('', ) else: h = host pfxs = ('mail.', 'imap.', 'imap4.', '', 'pop.') ss = (True, ) if ssltls else (True, False) print 'Probing %d host/security connections, this can take up to %.0f seconds' \ % (len(pfxs)*len(ss), len(pfxs)*len(ss)*timeout) for pfx in pfxs: for s in ss: testhost = pfx + h p = port if not p: p = 993 if s else 143 if verbose: print 'Trying %s:%d, %sssl ...' % (testhost, p, '' if s else 'no '), sys.stdout.flush() try: if s: srvr = imaplib.IMAP4_SSL(testhost, p) else: srvr = imaplib.IMAP4(testhost, p) except socket.error: if verbose: print 'failed to connect' srvr = None if srvr: if verbose: print 'success' if not foundHost: foundHost = testhost foundPort = p foundSsl = s foundSrvr = srvr if not verbose: break if not foundHost: print 'Unable to find a connection for', emailAddr return 1 print 'Success: host = %s, port = %d, ssl/tls = %s' % (foundHost, foundPort, foundSsl) if verbose: print 'Server capabilities:' for cap in foundSrvr.capabilities: print ' ', cap return 0
def __init__(self, username, password): self.username = username self.password = password self.mail = imaplib.IMAP4_SSL('imap.gmail.com') self.mail.login(self.username, self.password) self.mail.select("inbox")
def client(self): if not hasattr(self, "_client"): self._client = imaplib.IMAP4_SSL("imap.gmail.com") return self._client
def check_source(self, test=False): logger.debug(msg='Starting IMAP email fetch') logger.debug('host: %s', self.host) logger.debug('ssl: %s', self.ssl) if self.ssl: server = imaplib.IMAP4_SSL(host=self.host, port=self.port) else: server = imaplib.IMAP4(host=self.host, port=self.port) server.login(user=self.username, password=self.password) try: server.select(mailbox=self.mailbox) except Exception as exception: raise SourceException( 'Error selecting mailbox: {}; {}'.format( self.mailbox, exception ) ) try: status, data = server.uid( 'SEARCH', None, *self.search_criteria.strip().split() ) except Exception as exception: raise SourceException( 'Error executing search command; {}'.format(exception) ) if data: # data is a space separated sequence of message uids uids = data[0].split() logger.debug('messages count: %s', len(uids)) logger.debug('message uids: %s', uids) for uid in uids: logger.debug('message uid: %s', uid) try: status, data = server.uid('FETCH', uid, '(RFC822)') except Exception as exception: raise SourceException( 'Error fetching message uid: {}; {}'.format( uid, exception ) ) try: EmailBaseModel.process_message( source=self, message_text=data[0][1] ) except Exception as exception: raise SourceException( 'Error processing message uid: {}; {}'.format( uid, exception ) ) if not test: if self.store_commands: for command in self.store_commands.split('\n'): try: args = [uid] args.extend(command.strip().split(' ')) server.uid('STORE', *args) except Exception as exception: raise SourceException( 'Error executing IMAP store command "{}" ' 'on message uid {}; {}'.format( command, uid, exception ) ) if self.mailbox_destination: try: server.uid( 'COPY', uid, self.mailbox_destination ) except Exception as exception: raise SourceException( 'Error copying message uid {} to mailbox {}; ' '{}'.format( uid, self.mailbox_destination, exception ) ) if self.execute_expunge: server.expunge() server.close() server.logout()
import imaplib import email import os import datetime import pandas as pd import sys import requests import time import json from base64 import b64encode import xml.etree.ElementTree as ET import json svdir = os.getcwd() filename = 'None' mail=imaplib.IMAP4_SSL('imap-intern.telekom.de') mail.login("*****@*****.**","Ammukutt!2") mail.select("INBOX") date = date = datetime.datetime.now().strftime("%d-%b-%Y") typ, msgs = mail.search(None, '(SENTON {date} FROM "Padinharepattu, Rajeev" SUBJECT "pcc_excel")'.format(date=date)) count = len(msgs[0].split()) for num in msgs[0].split(): typ, data = mail.fetch(num, '(RFC822)') email_body = data[0][1] email_body = email_body.decode('utf-8') m = email.message_from_string(email_body) if m.get_content_maintype() != 'multipart':
def devour(self): """When it is time, poll and process. Make sure the account has these boxes: INBOX, Trash, Archive """ imap = self.whale.imap smtp = self.whale.smtp # open the IMAP connection and get everything in the INBOX try: M = imaplib.IMAP4_SSL(imap['server'], int(imap['port'])) except RuntimeError: print imap['server'] print traceback.format_exc() sys.stdout.flush() M.login(imap['username'], imap['password']) M.select() typ, raw = M.search(None, 'ALL') msg_nums = raw[0].split() if len(msg_nums) == 0: #print "no new mail" #sys.stdout.flush() return else: i_good = i_bad = 0 # track what we do for the log message for num in msg_nums: # get the From header and compare it to our membership lists From = self.from_addr(M, num).lower() if From not in self.whale.accept_from: # move it to the trash! M.copy(num, 'Trash') M.store(num, 'FLAGS.SILENT', '(\Deleted)') i_bad += 1 else: # get the raw email typ, raw = M.fetch(num, '(RFC822)') raw = raw[0][1] msg = email.message_from_string(raw) # tweak the headers if self.whale.mode == 'discussion': reply_to = imap['username'] else: reply_to = From try: msg.replace_header('Reply-To', reply_to) except KeyError: msg.__setitem__('Reply-To', reply_to) msg.add_header('X-Released-By', 'THE KRAKEN!!!!!!!!1') # and pass it on! server = smtplib.SMTP(smtp['server'], smtp['port']) server.starttls() server.ehlo() server.login(smtp['username'], smtp['password']) server.sendmail(imap['username'], self.whale.send_to, msg.__str__()) server.quit() # and move to archive M.copy(num, 'Archive') M.store(num, 'FLAGS.SILENT', '(\Deleted)') i_good += 1 M.close() M.logout() print 'new mail found: approved %s; rejected %s' % (i_good, i_bad) sys.stdout.flush()
def connect(username, password): #first field is imap server, second - port (993 for gmail SSL IMAP) M = imaplib.IMAP4_SSL("imap.gmail.com", 993) #first field is imap login (gmail uses login with domain and '@' character), second - password M.login(username, password) return M
async def get_emails_imap( self, username, password, imap_server, foldername, amount, unread, fields, include_raw_body, include_attachment_data, ): if type(amount) == str: try: amount = int(amount) except ValueError: return "Amount needs to be a number, not %s" % amount try: email = imaplib.IMAP4_SSL(imap_server) except ConnectionRefusedError as error: try: email = imaplib.IMAP4(imap_server) email.starttls() except socket.gaierror as error: return "Can't connect to IMAP server %s: %s" % (imap_server, error) except socket.gaierror as error: return "Can't connect to IMAP server %s: %s" % (imap_server, error) try: email.login(username, password) except imaplib.IMAP4.error as error: return "Failed to log into %s: %s" % (username, error) email.select(foldername) unread = True if unread.lower().strip() == "true" else False try: # IMAP search queries, e.g. "seen" or "read" # https://www.rebex.net/secure-mail.net/features/imap-search.aspx mode = "(UNSEEN)" if unread else "ALL" thistype, data = email.search(None, mode) except imaplib.IMAP4.error as error: return "Couldn't find folder %s." % (foldername) email_ids = data[0] id_list = email_ids.split() if id_list == None: return "Couldn't retrieve email. Data: %s" % data try: print("LIST: ", len(id_list)) except TypeError: return "Error getting email. Data: %s" % data emails = [] error = None if type(fields) == str: fields = {k.strip(): k.strip() for k in fields.split(",")} else: fields = None include_raw_body = True if include_raw_body.lower().strip( ) == "true" else False include_attachment_data = (True if include_attachment_data.lower().strip() == "true" else False) ep = eml_parser.EmlParser( include_attachment_data=include_attachment_data, include_raw_body=include_raw_body, ) for i in range(len(id_list) - 1, len(id_list) - amount - 1, -1): resp, data = email.fetch(id_list[i], "(RFC822)") if resp != "OK": print("Failed getting %s" % id_list[i]) continue if data == None: continue # Convert email in json try: data = json.loads( json.dumps(ep.decode_email_bytes(data[0][1]), default=default)) except UnicodeDecodeError as err: print("Failed to decode part of email %s" % id_list[i]) error = "Failed to decode email %s" % id_list[i] except IndexError as err: print("Indexerror: %s" % err) error = "Something went wrong while parsing. Check logs." # Pick only selected fields if specified try: data = glom.glom(data, fields) if fields else parsed_eml except glom.core.PathAccessError: print("Required fields are not valid") error = "Required fields are not valid" if error: emails.append({ "id": id_list[i].decode("utf-8"), "error": error }) else: emails.append(data) return json.dumps(emails)
food_list = [line.strip() for line in open(filename)] #list of food items def isFoodAnnouncement(subject, message): if (containsFoodWord(subject) or containsFoodWord(message)) and(floor_pattern.match(subject) or floor_pattern.match(message)): return True else: return False def containsFoodWord(text): for food in food_list: if food in text: return True return False imap_host = 'imap.gmail.com' mail = imaplib.IMAP4_SSL(imap_host, 993) #connect to GMail mail.login(username, password) last_id = 0 # ID of latest checked message. All new messages checked should have an ID > than this value. current_date = '\"' + time.strftime("%d-%b-%Y").lower() + '\"' search_string = '(TO "*****@*****.**" SINCE ' + current_date + ")" # Get ID of most recent message that matches the search string (if it exists) try: print 'Connecting to ' + label_name + '..' mail.select(label_name) result, data = mail.search(None, search_string) uid_list = data[0].split() if uid_list: last_id = max(uid_list) #most recent ID except:
def auth(user, password, imap_url): con = imaplib.IMAP4_SSL(imap_url) con.login(user, password) return con
msg = email.message_from_bytes(data[0][1]) for header in ['From', 'Subject', 'Date']: hdr = email.header.make_header( email.header.decode_header(msg[header])) if header == 'Date': date_tuple = email.utils.parsedate_tz(str(hdr)) if date_tuple: local_date = datetime.datetime.fromtimestamp( email.utils.mktime_tz(date_tuple)) print("{}: {}".format( header, local_date.strftime("%a, %d %b %Y %H:%M:%S"))) else: print('{}: {}'.format(header, hdr)) # with code below you can process text of email # if msg.is_multipart(): # for payload in msg.get_payload(): # if payload.get_content_maintype() == 'text': # print payload.get_payload() # else: # print msg.get_payload() M = imaplib.IMAP4_SSL("mail.teenagemutantninjaturtles.com", 993) M.login("*****@*****.**", "cowabunga") rv, data = M.select("INBOX") if rv == 'OK': process_mailbox(M) M.close() M.logout()
def __init__(self): self.M = imaplib.IMAP4_SSL('imap.gmail.com') self.time_between_checks = 5 self.sleep_adjustment = 0.25
def getcount(usr, pw): with imaplib.IMAP4_SSL('imaphm.qiye.163.com', 993) as M: M.login(usr, pw) res, data = M.select(mailbox='Sent') return int(data[0])
print("The word(s) '" + spokenText + "' have been said") print("Command: ", command, ", Option: ", option) socket.emit('commands', { "spoken": spokenText, "command": command, "option": option }) socket.emit(command, {"spoken": spokenText, "option": option}) if __name__ == '__main__': username = os.getenv("USER") password = os.getenv("PASSWORD") port = os.getenv("PORT") if (username == None or password == None): print( "No username or password found. Please set these environment variables." ) else: # keepAlive.start() try: mail = imaplib.IMAP4_SSL("imap.gmail.com", 993) mail.login(username, password) print("Login Successful.") c = SiriControl(callback, mail) c.start() socket.run(app, debug=False, host="0.0.0.0", port=port) except Exception as e: print(e)
# Maskierte Passwortabfrage import getpass # Wie viele Emails sollen gezeigt werden? LIMIT = 10 # Diese Daten müssen Sie anpassen, z.B. imap.gmail.com, wenn Sie einen # Googlemail Account haben. Port 993 ist meist für gesicherte Verbindungen. HOSTNAME = 'imap.example.com' PORT = 993 user = input('User:'******'Password:'******'ALL') # IDs kommen als String zurück - zerlegen! mail_ids = mails[0].split() # Sortieren und begrenzen mail_ids = list(reversed(mail_ids))[:LIMIT]
def run(self): try: conn = imaplib.IMAP4_SSL(self.server) conn.login(self.username, self.password) except BaseException as e: self.connection_error_signal.emit(str(e))
import imaplib import sys, getpass pw = getpass.getpass('Password:'******'imap.gmail.com') connection_message = server.login(sys.argv[1], pw) print(connection_message) print (server.select("inbox")) #server.select("ALL MAIL") sender ='' #senderEmail you want to delete. result_status, email_ids = server.search(None, '(FROM "%s")' % sender) emails = email_ids[0].split() print ('%d emails found'%len(emails)) for x in emails: server.store(x,'+X-GM-LABELS', '\\Trash') pass print ("Deleted %d messages. Closing connection & logging out."%len(emails)) server.logout()
def main(argv): now = date.today() try: opts, args = getopt.getopt(argv, "a:b:c:") except getopt.GetoptError: print("argument error") sys.exit(2) email_user = raw_input("Gmail username: "******"Gmail password: "******"Active Members") for account in active_member_accounts.find_account( "Full Members").children: member = Member(account) active_members.append(member) for account in active_member_accounts.find_account( "Student Members").children: member = StudentMember(account) active_members.append(member) for member in active_members: if member.effective_balance() < 0: print(member.name(), "has a balance of", member.effective_balance(), " ", member.email()) if member.email() == None: print("ERROR:", member.name(), "does not have an email address on record") else: gmail = imaplib.IMAP4_SSL('imap.gmail.com', port=993) gmail.login(email_user, email_pass) gmail.select('[Gmail]/Drafts') msg = email.message.Message() msg['Subject'] = 'SkullSpace Dues' msg['To'] = member.email() msg['CC'] = '*****@*****.**' msg.set_payload( 'Hello ' + member.name() + ',\n\nAccording to our records, your account balance is currently $' + str(member.effective_balance()) + '. Dues for the month of ' + calendar.month_name[now.month % 12 + 1] + ' were due on ' + calendar.month_name[now.month] + ' 15th. If you believe there is an issue with this record, please let us know.\n\nThank you,\n\n- Your SkullSpace Board of Directors' ) # extra_late_warning = "Note that since you are more than 3 months behind, you are at risk of losing your membership. Please contact us to make arrangements as soon as possible." gmail.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), str(msg))
def read_email_from_gmail(): mail = imaplib.IMAP4_SSL(IMAP_SERVER) mail.login(MY_EMAIL,MY_PWD) mail.select('inbox') type, data = mail.search(None, 'ALL') mail_ids = data[0] id_list = mail_ids.split() first_email_id = int(id_list[0]) latest_email_id = int(id_list[-1]) status, response = mail.search(None, '(UNSEEN)') id_list = response[0].split() for e_id in id_list: e_id = e_id.decode('utf-8') typ, response = mail.fetch(e_id, '(RFC822)') email_message = email.message_from_string(response[0][1]) email_subject = email_message['Subject'] email_date = email_message['Date'] email_from = email.utils.parseaddr(email_message['From']) email_response = str(email_from[1]) print 'From : ' + str(email_from[0]) print 'email : ' + str(email_response) print 'Data: ' + str(email_date) print 'Subject : ' + str(email_subject) + '\n' if email_message.get_content_maintype() != 'multipart': continue for part in email_message.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue data = email_date.replace(' ', '_') data = data.replace (',','') data = data.replace (':','_') data = data.replace ('+','') print 'data: ' + str(data) filename = part.get_filename() stato = '--' stato = ping() rispondi_ricevimento(email_response, filename, stato) filename = data + '_' + part.get_filename() att_path = os.path.join(detach_dir, filename) fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() print 'Salvato : ' + filename + '\n' messaggio = 'Ricevuto: ' + filename for e_id in id_list: mail.store(e_id, '+FLAGS', '\Seen') mail.close() mail.logout()
import imaplib #imports imap package import json mail = imaplib.IMAP4_SSL('imap.gmail.com') #imap url mail.login('', '') #email info
import imaplib, email, getpass from email import policy imap_host = 'imap.mail.yahoo.com' imap_user = '******' imap_pass = '******' # init imap connection mail = imaplib.IMAP4_SSL(imap_host, 993) rc, resp = mail.login(imap_user, imap_pass) # select only unread messages from inbox mail.select('Inbox') status, data = mail.search(None, '(UNSEEN)') # for each e-mail messages, print text content for num in data[0].split(): print(num) # get a single message and parse it by policy.SMTP (RFC compliant) status, data = mail.fetch(num, '(RFC822)') email_msg = data[0][1] email_msg = email.message_from_bytes(email_msg, policy=policy.SMTP) print("\n----- MESSAGE START -----\n") print("From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n" % ( \ str(email_msg['From']), \ str(email_msg['To']), \ str(email_msg['Date']), \ str(email_msg['Subject'] )))
def test_imap(user, auth_string): imap_conn = imaplib.IMAP4_SSL('imap.gmail.com') imap_conn.debug = 4 imap_conn.authenticate('XOAUTH2', lambda x: auth_string) imap_conn.select('INBOX')
import email import imaplib from imap_tools import A, AND, OR, NOT from datetime import date EMAIL = 'EMAIL' PASSWORD = '******' SERVER = 'imap.gmail.com' TIME = date.today() #TIME = '16/09/2019' #D/M/Y # connect to the server and go to its inbox mail = imaplib.IMAP4_SSL(SERVER) mail.login(EMAIL, PASSWORD) # we choose the inbox but you can select others mail.select('inbox') # we'll search using the ALL criteria to retrieve # every message inside the inbox # it will return with its status and a list of ids #status, data = mail.search(None, 'ALL') # we'll search using the FROM criteria to retrieve # every message inside the inbox FROM the desired string # it will return with its status and a list of ids # status, data = mail.search(None, 'FROM Jamie') status, data = mail.search(None, '(SINCE 15-Mar-2000 FROM Jamie)') # the list returned is a list of bytes separated # by white spaces on this format: [b'1 2 3', b'4 5 6'] # so, to separate it first we create an empty list
def fetch_mail(request): fetch_form = FetchMailForm(request.POST) if not fetch_form.is_valid(): return Http404 user = fetch_form.cleaned_data["email"] pwd = fetch_form.cleaned_data["password"] # connecting to the gmail imap server imap = imaplib.IMAP4_SSL("imap.gmail.com") resp, _items = imap.login(user, pwd) if resp != 'OK': return error("Wrong user name or password") #m.select("[Gmail]/INBOX") # here you a can choose a mail box like INBOX instead resp, _items = imap.select('sigma') if resp != 'OK': return error("Cannot locate label 'sigma'") resp, items = imap.search(None, '(SUBJECT "Sigma-Aldrich Order confirmation")') if resp != 'OK': return error("Cannot search for emails for Sigma") items = items[0].split() # getting the mails id pending_list = [] for emailid in items: # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc resp, data = imap.fetch(emailid, "(RFC822)") if data is None or data[0] is None: continue email_body = data[0][1] # getting the mail content mail = email.message_from_string( email_body) # parsing the mail content to get a mail object # Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "[" + mail["From"] + "] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue # finally write the stuff fp = io.BytesIO() fp.write(part.get_payload(decode=True)) fp.seek(0) #apply_lbl_msg = imap.uid('COPY', emailid, 'done') #if apply_lbl_msg[0] == 'OK': # mov, data = imap.uid('STORE', emailid , '+FLAGS', '(\Deleted)') # imap.expunge() try: for primer in pdfMine(fp): entry = Pending(name=primer[0], seq=primer[1]) entry.save() pending_list.append(entry) except PDFSyntaxError: pass fp.close() return render_to_response('upload_success.html', {'primers_list': pending_list})
print('TESTS SUCCEEDED') else: print('SOME TESTS FAILED:') for test in failed_tests: print(test) sys.exit(1) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('username', help='Email address of the user') parser.add_argument('password', help='Password of the user') parser.add_argument('ip_proxy', help='Ip address of the proxy') parser.add_argument('-s', '--ssl', help='Enable SSL/TLS connection', action='store_true') parser.add_argument('-p', '--port', type=int, help='Talk on the given port (Default: 143 or 993 with SSL/TLS enabled)') args = parser.parse_args() try: if args.ssl: if args.port: run_tests(imaplib.IMAP4_SSL(args.ip_proxy, args.port), args.username, args.password) else: run_tests(imaplib.IMAP4_SSL(args.ip_proxy), args.username, args.password) else: if args.port: run_tests(imaplib.IMAP4(args.ip_proxy, args.port), args.username, args.password) else: run_tests(imaplib.IMAP4(args.ip_proxy), args.username, args.password) except ConnectionRefusedError: print('Port blocked')