def _parse_mailboxes(self, mailboxes): for mailbox, config in mailboxes.items(): server = config.get('server', 'localhost') port = config.get('port', 143) user = config.get('username', None) password = config.get('password', None) folder = config.get('mailbox', 'INBOX') ssl = config.get('ssl', False) download_attachments = config.get('download_attachments', DEFAULT_DOWNLOAD_ATTACHMENTS) if not user or not password: self._logger.debug("""[IMAPSensor]: Missing username/password for {0}""".format(mailbox)) continue if not server: self._logger.debug("""[IMAPSensor]: Missing server for {0}""".format(mailbox)) continue try: connection = easyimap.connect(server, user, password, folder, ssl=ssl, port=port) except Exception as e: message = 'Failed to connect to mailbox "%s": %s' % (mailbox, str(e)) raise Exception(message) item = { 'connection': connection, 'download_attachments': download_attachments } self._mailboxes[mailbox] = item
def check_for_email(): global imap, config try: new_mail = imap.unseen() if new_mail: for email in new_mail: if 'package to pick up' in email.title: print(email) # send a post to the web server requests.post(config.pnb_url + '/email', json={ 'title': email.title, 'body': email.body }) else: print('no new emails') except IMAP4.abort: # socket error, close & reopen socket traceback.print_exc() imap.quit() imap = easyimap.connect(config.host, config.user, config.password) except: traceback.print_exc()
def getmailfunc(): h = html2text.HTML2Text() h.ignore_links = True login = '******' print("login assigned") password = '******' print("password assigned") imapper = easyimap.connect('imap.gmail.com', login, password) print("imap connect successful") for mail_id in imapper.listids(limit=1): print("inside for loop") mail = imapper.mail(mail_id) print(mail.body) incasehtml = h.handle(mail.body) print("HTML cleaned: " + incasehtml) if mail.attachments == []: attachments = "No attachments." else: attachments = mail.attachments response = (incasehtml + "\n FROM: " + mail.from_addr + " ATTATCHMENTS: " + str(attachments) + " DATE: " + str(mail.date)) newresponse = { 'mailmessage': incasehtml, 'mailsender': mail.from_addr, 'mailsubject': mail.title } python2json = json.dumps(newresponse) return python2json break return python2json
def result(): if request.method == 'POST': userText1 = request.form['email'] userText2 = request.form['password'] imapper = easyimap.connect('imap.gmail.com', userText1, userText2) spam = 0 ham = 0 spam_list = [] ham_list = [] for mail_id in imapper.listids(limit=50): mail = imapper.mail(mail_id) message_text = mail.body result_type = spam_filter(message_text) print(result_type) if result_type == "spam": spam = spam + 1 spam_list.append(mail.from_addr) else: ham = ham + 1 ham_list.append(mail.from_addr) result = [spam, ham] return render_template('result.html', result=result, ham_list=ham_list, spam_list=spam_list)
def get_email_from_gmail(idhere): host = "imap.gmail.com" user = "******" password = "******" mailbox = "INBOX" imapper = easyimap.connect(host, user, password, mailbox) mails = imapper.listup(limit=50) p = re.compile('\d+') emails = [] for item in mails: found = p.search(item.to) if found: idofemail = found.group() # print("ID of Email: ") # print(idofemail) # print("ID: ") # print(idhere) if idofemail == str(idhere): #print("In emails with ID: " + idofemail + " and master id : " + str(idhere)) emails.append("<h6>From : " + item.from_addr + "</h6><h7>" + "To : " + item.to + "</h7><br><p>" + item.body + "</p>") endstr = "" for temp in emails: endstr = endstr + "<br>" + "<div class=message>" + temp + "</div>" + "<br>" return endstr
def read_mail(img): c = 0 p, q = app(img) imapper = easyimap.connect('imap.gmail.com', '*****@*****.**', 'bmexggxmcjvlwanz') while (c == 0): for mail_id in imapper.listids(limit=1): mail = imapper.mail(mail_id) if (mail.title == "Re: Someone's at the door"): if mail.body[0:5] == p: ser.write(b'open') print('Please Enter...') time.sleep(10) c = 1 return 2 elif mail.body[0:3] == q: print("no") ser.write(b'close') time.sleep(15) c = 1 return 2 else: pass
def GetEmails(): imapper = easyimap.connect('imap.gmail.com', username, password) email_list = [] for mail_id in imapper.listids(limit=10): mail = imapper.mail(mail_id) type_, folder = FilterSubject(mail.title) email = {} email['subject'] = mail.title email['type'] = type_ email['folder'] = folder email['body'] = mail.body if 'http' in email['body']: url_1 = email['body'].split('http')[1] url_2 = url_1.replace('\r', '$') url = 'http' + url_2.split('$')[0] email['url'] = url email['url'] = str(url.strip('\r\n')) else: email['url'] = '' email['date'] = mail.date email['from'] = mail.return_path.replace('<', '').replace('>', '') email_list.append(email) print(mail.from_addr) # print(' ', mail.to) # print(' ', mail.cc) print(' Datetime: ', email['date']) print(' Subject: ', mail.title) # print(' Body: ', mail.body) print(' Extracted Url: ', email['url']) # print(' ', mail.attachments) return email_list
def __enter__(self): self._connection = easyimap.connect(host=self._account.imap_host, port=self._account.imap_port, user=self._account.address, password=self._account.password, ssl=self._account.imap_ssl) return self
def save_attached_files_from_email(host, user, password, path_to_save_files): imapper = easyimap.connect(host, user, password) last_received_email = imapper.listup()[0] for attachment in last_received_email.attachments: with open(path_to_save_files + attachment[0], 'bw+') as f: f.write(attachment[1])
def check_mail(bot_login, bot_password, sender_login): try: imapper = easyimap.connect('imap.gmail.com', bot_login, bot_password) except: pass for mail_id in imapper.listids(limit=100): mail = imapper.mail(mail_id) if sender_login in mail.from_addr: yield mail.body
def test_send_email(self, email='*****@*****.**', password='******'): imapper = easyimap.connect('imap.gmail.com', email, password) senders = [] titles = [] for mail_id in imapper.listids(limit = 20): mail = imapper.mail(mail_id) senders.append(mail.from_addr) titles.append(mail.title) imapper.quit() self.assertTrue('*****@*****.**' in senders and 'Your fortune cookie today' in titles)
def recieve(serveruser, serverpass, function): server = easyimap.connect('imap.gmail.com'.serveruser, serverpass) i = 0 update = [] command = [] for each in server.listids(limit=10): mail = server.mail(each) update.append[mail.body] command.append[mail.title] return command, update
def create_lots_and_mails(login, password): imapper = easyimap.connect('imap.komus.ru', login, password) today = datetime.datetime.today() for mail_id in imapper.listids(limit=50): mail = imapper.mail(mail_id) if "Зарегистрирован" in mail.title and f"{today:%d}.{today:%m}" in mail.title: num_lot = re.findall(r'N[0-9]{6}', mail.title) num_lot = num_lot[0].replace("N", "") if num_lot not in list_lots: list_lots.append(num_lot) letters[mail.title] = mail.body
def login_find_single_mail(recv_email, recv_passwd , from_who_email , subject_txt): imap_ssl_host = get_imap_name(recv_email) toReturn = None imapper = easyimap.connect(imap_ssl_host, recv_email, recv_passwd) for mail in imapper.unseen(limit=constants.LIMIT_UNREADMAIL): # mail = imapper.mail(mail_id) if mail.title == subject_txt and mail.from_addr == from_who_email: toReturn = mail.body break; return toReturn
def test_send_email(): login = '******' password = '******' imapper = easyimap.connect('imap.gmail.com', login, password) for mail_id in imapper.listids(limit=20): mail = imapper.mail(mail_id) if '*****@*****.**' in mail.from_addr and 'Your fortune cookie today' in mail.title: return True else: return False
def _parse_mailboxes(self, mailboxes): for mailbox, config in mailboxes.items(): server = config.get('server', 'localhost') port = config.get('port', 143) user = config.get('username', None) password = config.get('password', None) folder = config.get('mailbox', 'INBOX') ssl = config.get('ssl', False) download_attachments = config.get('download_attachments', DEFAULT_DOWNLOAD_ATTACHMENTS) poll = config.get('poll', True) if not poll: continue if not user or not password: self._logger.debug("""[IMAPSensor]: Missing username/password for {0}""".format(mailbox)) continue if not server: self._logger.debug("""[IMAPSensor]: Missing server for {0}""".format(mailbox)) continue try: connection = easyimap.connect(server, user, password, folder, ssl=ssl, port=port) except Exception as e: message = 'Failed to connect to mailbox "%s": %s' % (mailbox, str(e)) raise Exception(message) item = { 'connection': connection, 'download_attachments': download_attachments, 'mailbox_metadata': { 'server': server, 'port': port, 'user': user, 'folder': folder, 'ssl': ssl } } self._mailboxes[mailbox] = item
def login_recv_all_mail(recv_email, recv_passwd, from_who_email , subject_txt): imap_ssl_host = get_imap_name(recv_email) g_emails_list = [] g_email_ids = [] imapper = easyimap.connect(imap_ssl_host, recv_email, recv_passwd) for mail in imapper.unseen(limit=constants.LIMIT_UNREADMAIL): #mail = imapper.mail(mail_id) if mail.title == subject_txt: g_email_ids.append(mail.from_addr) g_emails_list.append(mail.body) return g_emails_list , g_email_ids
def main1(): imapper = easyimap.connect(host=imap_host, user=imap_user, password=imap_pass, ssl=True, port=imap_port) for mail_id in imapper.listids(limit=50): mail = imapper.mail(mail_id) print(mail.uid) print(mail.from_addr) print(mail.to) print(mail.cc) print(mail.title) print(mail.body) print(mail.attachments)
def tweety_mail(): imapper = easyimap.connect(host, user, password, mailbox) unseen = imapper.unseen() if unseen is not None: for newmail in unseen: try: basecode = newmail.title.split(' ')[0] tr_subject = newmail.title.split(' ')[1] except: basecode = 'undefined' tr_subject = 'undefined' send_mail(recipients=newmail.from_addr, title=newmail.title, body=tweety_new(find_user_by_mail(newmail.from_addr), basecode, tr_subject)) imapper.quit()
def check_email_for_new_logins(first_name, last_name): """ Checks the email and scrapes for logins and passwords from the claremont Card Office. Returns: The access key recieved for the user of the given name. """ possible_emails = {} fname = first_name.lower() lname = last_name.lower() # Loop through unread emails imapper = easyimap.connect(el.HOST, el.USER, el.PASSWORD, read_only=True) for mail in imapper.unseen()[::-1]: # Scrape the email only if it is from the Claremont card office if (verify_card_office_email(mail)): fn, ln = scrape_email_for_name(mail.body) # check if the last name is correct and put the first name in the # dictionary if (ln == lname): possible_emails[fn] = mail.uid # Find the correct email corr_email = 0 if (len(possible_emails) == 0): # No emails picked up return None elif (fname in possible_emails): # Only one possibility corr_email = possible_emails[fname] else: # Case where the student's first name is not the same that is # listed on claremont card website bmatch = get_best_match(fname, possible_emails.keys()) if (bmatch == ''): return None corr_email = possible_emails[bmatch] # Go back in an mark the email as read while grabbing the correct info # Using witchcraft to change imapper's read_only status imapper._read_only = False imapper.change_mailbox('INBOX') access_key = scrape_email_for_access_key(imapper.mail( str(corr_email)).body) imapper.quit() return access_key
def get_mail(self): print("Downloading mail...") try: imapper = easyimap.connect('imap.gmail.com', self.login, self.password) self.mail = [] for mail_id in imapper.listids(limit=100): self.mail.append(imapper.mail(mail_id)) return self.mail except Exception as e: logf = open("error.log", "w") logf.write(f'{datetime.now():%Y-%m-%d %H:%M:%S%z}') logf.write("Failed to check mail: {0}\n".format(str(e))) logf.close() print(e) finally: return self.mail
def odbierzMail(): ileMaili = input("Podaj ilość maili jaką " "chcesz przeczytać: ") skrzynka = "inbox" imapper = easyimap.connect(serwer, login, haslo, skrzynka, ssl=False, port=143) for mail_id in imapper.listids(limit=int(ileMaili)): mail = imapper.mail(mail_id) print("----------\nWiadomośc email:\n----------") print("Od: " + mail.from_addr) print("Do: " + mail.to) print("Temat: " + mail.title) print("Treść:\n" + mail.body) imapper.quit()
def _parse_accounts(self, accounts): for config in accounts: self._logger.debug('[IMAPSensor]: entering accounts') mailbox = config.get('name', 'Mukesh123') server = config.get('server', 'imap.gmail.com') port = config.get('port', 993) user = config.get('username', '*****@*****.**') password = config.get('password', 'nihilent@123') folder = config.get('folder', 'INBOX') ssl = config.get('secure', True) if not user or not password: self._logger.debug("""[IMAPSensor]: Missing username/password for {0}""".format(mailbox)) continue if not server: self._logger.debug("""[IMAPSensor]: Missing server for {0}""".format(mailbox)) continue try: connection = easyimap.connect(server, user, password, folder, ssl=ssl, port=port) except Exception as e: message = 'Failed to connect to mailbox "%s": %s' % (mailbox, str(e)) raise Exception(message) item = { 'connection': connection, 'mailbox_metadata': { 'server': server, 'port': port, 'user': user, 'folder': folder, 'ssl': ssl } } self._logger.debug('[IMAPSensor]: entering connecting') self._accounts[mailbox] = item
def cmd__open(self, host, username): """ Open an IMAP mailbox. Usage: open <host> <username> Examples: open imap.example.org john.doe open gmail john.dough """ if '.' not in host: host = f'imap.{host}.com' password = self.ask(f'Password for {username}', hidden=True) self.client = easyimap.connect(host, username, password) self.info('Client connected') self.username = username self.enqueue(self.reload)
def handle(self, *args, **options): imaps = settings.IMAPS for imap in imaps: imapper = easyimap.connect(imap['host'], imap['user'], imap['pass'], imap['mailbox']) self.success('Loggueado como {}'.format(imap['user'])) if options['include_seen']: # read every email not present in the db imap_ids = {int(i) for i in imapper.listids()} known_ids = set(Email.objects.values_list('uid', flat=True)) unknown_ids = imap_ids - known_ids mails = (imapper.mail(str(i)) for i in unknown_ids) else: mails = imapper.unseen() # self.success('Se encontraron {} emails'.format(len(list(mails)))) for mail in mails: self.success('Email {}'.format(mail)) attachments = mail.attachments if not attachments: self.success(' ... sin adjuntos') continue email = Email.from_mail_object(mail) self.log(email) for attachment in attachments: # self.success(' -- attachment {}'.format(attachment[0])) if options['only_images'] and not attachment[2].startswith( 'image'): self.warning( f'Ignoring {attachment[0]} ({attachment[2]})') continue instance = Attachment(email=email, mimetype=attachment[2]) try: content = ContentFile(attachment[1]) instance.foto.save(attachment[0], content, save=False) instance.save() self.success(' -- saved {}'.format(instance)) self.log(instance) except IntegrityError: self.warning(f'{attachment[0]} ya está en el sistema')
def _parse_accounts(self, accounts): for config in accounts: mailbox = config.get('name', None) server = config.get('server', 'localhost') port = config.get('port', 143) user = config.get('username', None) password = config.get('password', None) folder = config.get('folder', 'INBOX') ssl = config.get('secure', False) if not user or not password: self._logger.debug("""[IMAPSensor]: Missing username/password for {0}""".format(mailbox)) continue if not server: self._logger.debug("""[IMAPSensor]: Missing server for {0}""".format(mailbox)) continue try: connection = easyimap.connect(server, user, password, folder, ssl=ssl, port=port) except Exception as e: message = 'Failed to connect to mailbox "%s": %s' % (mailbox, str(e)) raise Exception(message) item = { 'connection': connection, 'mailbox_metadata': { 'server': server, 'port': port, 'user': user, 'folder': folder, 'ssl': ssl } } self._accounts[mailbox] = item
def check_email_for_new_logins(): """ Checks the email and scrapes for logins and passwords from the claremont Card Office. Returns: a list tuple pairs in the format: (login, password). """ logins = [] # Loop through unread emails imapper = easyimap.connect(el.HOST, el.USER, el.PASSWORD) for mail in imapper.unseen(): # Scrape the email only if it is from the Claremont card office if (verify_card_office_email(mail)): login, password = scrape_email(mail.body) logins.append((login, password)) imapper.quit() return logins
def monitor_email() -> None: imapper = easyimap.connect(Config.get_imapserver(), Config.get_mailaccount(), Config.get_password()) f = open("messages.json") processed_massages = json.loads(f.read()) f.close() while True: print("Searching for command ... ") for mail_id in imapper.listids(limit=100): mail = imapper.mail(mail_id) body = html2text.html2text(mail.body) if str( mail_id ) not in processed_massages: #re.findall("^IMPORTANT COMMAND", body) \ and subject = mail.title citation = u"> From: " + mail.from_addr + '\n' citation += u"> Date: " + mail.date + '\n' citation += u"> Body: " + html2text.html2text(mail.body) # TODO: process the body and subject through RASA and then send mail reply. # Work on the seperate module for making the web hook call message = API.post_request( message=html2text.html2text(mail.body)) # TODO: Improved on the send mail response EmailBot.send_mail([str(mail.from_addr)], subject, message) print(citation) processed_massages[str(mail_id)] = { 'subject': subject, 'message': message, 'ts': int(time.time()) } f = open("messages.json", "w") f.write(json.dumps(processed_massages)) f.close() print(str(mail_id) + " processed!") time.sleep(Config.get_refresh())
def delivery_confirm(sent_uid, host, username, password, mailbox, report): imapper = easyimap.connect(host, username, password, mailbox) email_quantity = 10 emails_from_your_mailbox = imapper.listids(limit=email_quantity) imapper.quit() imap = imaplib.IMAP4_SSL(host) imap.login(username, password) imap.select(mailbox) uid = 'NO' file = 'NO' for item in emails_from_your_mailbox: status, data = imap.fetch(item, '(RFC822)') msg = email.message_from_bytes(data[0][1], _class=email.message.EmailMessage) if msg['Subject'] == '***Automatically generated by ASMail***': payload = msg.get_payload()[0] recieved_uid = payload.get_payload() for part in msg.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue fileName = part.get_filename() sent_filename = Path(sys.argv[1]).name if sent_uid == recieved_uid: uid = 'YES' if sent_filename == fileName: file = 'YES' if report == True: ctypes.windll.user32.MessageBoxW( 0, 'UID status: ' + uid + '\nFilename status: ' + file, 'Delivery report', 0) print('UID status: ' + uid + '\nFilename status: ' + file) imap.logout()
def getmailfunc(): h = html2text.HTML2Text() h.ignore_links = True login = '******' print("login assigned") password = '******' print("password assigned") imapper = easyimap.connect('imap.gmail.com', login, password) print("imap connect successful") for mail_id in imapper.listids(limit=1): print("inside for loop") mail = imapper.mail(mail_id) print(mail.body) incasehtml = h.handle(mail.body) print("HTML cleaned: " + incasehtml) response = (incasehtml + "<b> ---> FROM: </b>" + mail.from_addr + "<b> ---> content type: </b>" + str(mail.content_type) + "<b> ---> attachments: </b>" + str(mail.attachments) + "<b> ---> date: </b>" + str(mail.date) + "<b> ---> mime version: </b>" + str(mail.mime_version) + "<b> ---> mail sender: </b>" + str(mail.sender)) return response break return response
def main(): module = AnsibleModule( argument_spec=dict(server=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), mailbox=dict(requied=False, default='INBOX'), ssl=dict(required=False, type=bool, default=True), port=dict(required=False, type=int, default=993))) server = module.params['server'] user = module.params['username'] password = module.params['password'] mailbox = module.params['mailbox'] ssl = module.params['ssl'] port = module.params['port'] imapper = None try: imapper = easyimap.connect(server, user, password, mailbox, ssl=ssl, port=port) mails = imapper.unseen(1) if mails: [mail] = mails result = { 'subject': mail.title, 'body': mail.body, 'from': mail.from_addr, 'to': mail.to, 'date': mail.date, 'reply_to': mail.reply_to } module.exit_json(changed=True, mail=result) else: module.exit_json(changed=False) except Exception as e: module.fail_json(msg="imap failed: {0}".format(e)) finally: if imapper: imapper.quit()
def result(): if request.method == 'POST': userText1 = request.form['email'] userText2 = request.form['password'] imapper = easyimap.connect('imap.gmail.com', userText1, userText2) spam = 0 ham = 0 spam_list=[] ham_list=[] for mail_id in imapper.listids(limit=50): mail = imapper.mail(mail_id) message_text = mail.body result_type=spam_filter(message_text) print(result_type) if result_type == "spam": spam=spam+1 spam_list.append(mail.from_addr) else: ham=ham+1 ham_list.append(mail.from_addr) result = [spam,ham] return render_template('result.html',result=result,ham_list=ham_list,spam_list=spam_list)
import easyimap import getpass # Working demo of getting email with python. # Tested on imac with python2. # With Python3, I could not get it to find the modula easyimap # even though I pip3 installed it with pip3.5, pip3.7 # and tried a bunch of other stuff. login = '******' password = getpass.getpass("enter password for user {} : ".format(login)) imapper = easyimap.connect('imap-mail.outlook.com', login, password) def save_kifu_mail_to_file(kifu_mail): game_name = '_'.join(mail.title.split()[2:]) if game_name == '': game_name = 'fallback_name' print("WE HAVE A GAME!") print(game_name) print(mail.body) for mail_id in imapper.listids(limit=10): mail = imapper.mail(mail_id) print(mail.from_addr) print(mail.title) # The intention is to have this on a raspberry pi to # get the kifu in recent emails and save them to files automatically if mail.title.startswith('GoQuest Kifu'):
couch = server[config.get('couch', 'db')] except ResourceNotFound: couch = server.create(config.get('couch', 'db')) # IMAP setup host = config.get('imap', 'host') user = config.get('imap', 'user') try: password = config.get('imap', 'password') except ConfigParser.NoOptionError: password = getpass.getpass("Password for %s on %s: " % (user, host)) mailbox = config.get('imap', 'mailbox') if __name__ == '__main__': print 'Connecting...' imapper = easyimap.connect(host, user, password, mailbox, read_only=True, ssl=True, port=993) print 'Connected. Couple more questions...' amount = int(raw_input('How many mail items would you like to archive? ')) should_skip = raw_input('Skip mail already archived (y/n)? ') if should_skip.lower() in ["y", "yes", "yea", "si", "go", "aye", "sure"]: should_skip = True else: should_skip = False # Loop through the messages and add them to CouchDB ids = imapper.listids(amount) for id in ids: msg = imapper.mail(id, include_raw=True) unique_id = truly_unique_id(msg) try: current_doc = couch[unique_id] if should_skip:
def read_logic(): try: if (no_entry.get() == ""): msgb = messagebox.showinfo("Reading Mail Dialoge", "please Enter a valid number") else: n = int(no_entry.get()) i = 1 except Exception as f: msgb = messagebox.showinfo("Reading Mail Dialoge", "please Enter a valid number") try: imapper = easyimap.connect('imap.gmail.com', username, password) for mail_id in imapper.listids(n): mail = imapper.mail(mail_id) #print(mail.from_addr) #print(mail.title) #print(mail.body) if (mail.attachments): a = 'Some Attachments' else: a = '' messagebox.showinfo( "Mail " + str(i), "Mail From: " + mail.from_addr + "\nTitle: " + mail.title + "\nBody: " + mail.body + "\n" + a) i = int(i) i += 1 except Exception as e: print(e) imapper.quit()