def background(self): self.letters = f_read("emails") if config.NAME == "KLBFAX" and self.n == 1 and config.has_gmail_login( ): import gmail details = f_readlines("gmail") g = gmail.login(details[0], details[1]) unread = g.inbox().mail(unread=True) for mail in unread: mail.fetch() lines = "".join(mail.body.split("\r")).split("\n") if lines[ 0] == "EVENT" and "*****@*****.**" in mail.fr: try: with open_local('events', 'a') as f: for line in lines: if line != "EVENT": f.write(line + "\n") mail.read() except: pass elif lines[ 0] == "CARD" and "*****@*****.**" in mail.fr: with open('/home/pi/cards/' + lines[1], "w") as f: f.write("\n".join(lines[2:])) mail.read() elif "POINTS" in lines[0].upper( ) and "*****@*****.**" in mail.fr: from points import add_points length = 1 points_to_give = 0 while length <= len(lines[2]): try: if lines[2][:length] != "-": points_to_give = int(lines[2][:length]) length += 1 except: break add_points(lines[1].split("=")[0], points_to_give) mail.read() else: newletter = "" for line in lines: if line != "": while len(line) > 79: newletter += line[:79] + "\n" line = line[79:] newletter += line + "\n" self.letters = newletter + "\n" + "from " + mail.fr + "\n\n" + self.letters mail.read() self.letters = self.letters.split("\n") if len(self.letters) > 1000: self.letters = self.letters[:1000] with open_local("emails", "w") as f: f.write("\n".join(self.letters)) else: self.letters = self.letters.split("\n")
def parse_gmail(self, username, passwd, ioc_data): try: emailData = defaultdict(set) g = gmail.login(username, passwd) if (g.logged_in): print "sucessful login..." today = datetime.date.today().strftime("%Y-%m-%d") daysBack = datetime.date.today() - datetime.timedelta(days=2) emails = g.inbox().mail(before=datetime.date.today(), after=daysBack, unread=True) for e in range(0, len(emails)): try: emails[e].fetch() content = emails[e].body subject = re.sub('(^\s|re:\s+|\r\n|fwd:\s+)', '', emails[e].subject, flags=re.IGNORECASE) ioc_data[subject]['hashes'] = set() ioc_data[subject]['ip'] = set() ioc_data[subject]['domain'] = set() self.get_hashes(content, ioc_data[subject]['hashes'], self.md5Regex) self.get_ip(content, ioc_data[subject]['ip']) self.get_domain(content, ioc_data[subject]['domain']) self.get_hashes(content, ioc_data[subject]['hashes'], '\\b[a-fA-F0-9]{64}\\b') self.get_hashes(content, ioc_data[subject]['hashes'], '\\b[a-fA-F0-9]{40}\\b') except Exception as ex: continue print "emails found: %s" % len(emails) else: sys.exit() except gmail.exceptions.AuthenticationError: print "auth error" sys.exit()
def check_email_password(self, email_subject): # Check Email and Return Password self.sleeper(480) email = gmail.login(receiver_email, receiver_password) unread = email.inbox().mail(sender=sender_email, prefetch=True, unread=True) password = "" if len(unread) > 0: # while not password: for message in unread: sent_date = str(message.sent_at.date()) current_date = str(date.today()) print(".....................") print(message.sent_at) print(sent_date) print(current_date) print(message.subject) print(self.locate_password(message.body)) print(".....................") if sent_date == current_date: if message.subject == email_subject: print(message.subject) password = self.locate_password(message.body) message.read() else: pass # UNFORTUNATELY SPAM MAIL IS NOT WORKING # if password == "": # password = self.check_spam(email_subject) return password
def loginToGmail(u, p): # Login to your gmail account try: g = gmail.login(u, p) except Exception as e: print '\nSomething messed up\n' return g
def getstat(): now = datetime.datetime.now() sender2 = sys.argv[1] print sys.argv[1] password = "******" getmail = gmail.login("ramramu.jr", password) if (getmail.logged_in): #print "hi" #print datetime.datetime(now.year,now.month,now.day,hourdelta(now.hour,now.minute-43),minutedelta(now.minute-43),now.second) t = getmail.inbox().mail(unread=True, after=datetime.datetime( now.year, now.month, now.day, hourdelta(now.hour, now.minute - 2), minutedelta(now.minute - 2), now.second), sender=sender2) #print len(t) for i in range(len(t)): t[i].read() t[i].fetch() #print t[i].body pattern = re.compile("Enable USB ") if pattern.search(t[i].subject): pat = re.compile("yes") if pat.search(t[i].body): print "yes" return 1 #t[i].delete() else: print "no" return 0
def check_email(): while True: g = gmail.login(GMAIL_USER, GMAIL_PASS) inbox = g.inbox().mail(unread=True, fr=EMAIL_JUSTIN) # justin if inbox: inbox[0].fetch() subject = inbox[0].subject body = inbox[0].body body = body.strip("*") json = {"title": subject, "body": body} db.posts.insert_one(json) inbox[0].read() inbox = g.inbox().mail(unread=True, fr=EMAIL_TIM) # tim if inbox: inbox[0].fetch() subject = inbox[0].subject print subject body = inbox[0].body print body body = body.replace('\r', '<br/>').replace('\n', '<br/>') json = {"title": subject, "body": body} db.posts.insert_one(json) inbox[0].read() g.logout() time.sleep( 600 ) # wait 10 minutes; you dont want all the server resources gone in the next minute
def main(): g = gmail.login(GMAIL_USERNAME, GMAIL_PASSWORD) for mail in g.inbox().mail(unread=True, sender=KUMAR_EMAIL, prefetch=True): if KEYWORDS_REGEX.search(mail.body): # Restore DB and send a reply. mail.add_label('Database fixes') send_reply(mail.subject)
def empaqueta(): global contA global archivo contA=0 username = request.form['email'] password = request.form['pass'] filtro = request.form['filtroH'] print(username) print(password) g = gmail.login(username, password) print g.logged_in if filtro=='1': messages = g.inbox().mail() else: if filtro=='2': messages = g.inbox().mail(read=True) else: messages = g.inbox().mail(unread=True) if not os.path.exists('adjuntos'): os.makedirs('adjuntos') for mensaje in messages: mensaje.fetch() fecha = mensaje.sent_at.strftime("%d %m %Y %H:%M:%S") directory = 'adjuntos/'+mensaje.subject+' '+fecha if mensaje.attachments: if not os.path.exists(directory): os.makedirs(directory) for adjunto in mensaje.attachments: adjunto.save(directory +'/'+adjunto.name) contA = contA +1; archivo = "copia "+datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") zip('adjuntos/',archivo) shutil.rmtree('adjuntos') return render_template('dropbox.html')
def steamGuard(self): # Manual authentication if RBot.emailPassword is None: while True: self.Bot.Log("GuardCode sent to " + RBot.emailAddress) guardCode = raw_input(color.Fore.BLUE + color.Style.BRIGHT + "[" + self.Bot.name + "] " + color.Fore.RESET + color.Style.RESET_ALL + "GuardCode: ") return guardCode else: g = gmail.login(RBot.emailAddress, RBot.emailPassword) # Check for emails until we get Steam Guard code for i in range(0, settings.steam["guard"]["retries"]): mails = g.inbox().mail(sender="*****@*****.**", unread=True) if mails: mail = mails[-1] mail.fetch() guardCode = re.findall(r"log in again: ([A-Z0-9]{5})", mail.body)[0] mail.read() mail.delete() g.logout() return guardCode else: self.log("Don't have any new emails") self.log("Retrying in " + str(settings.steam["guard"]["interval"]) + " seconds") time.sleep(settings.steam["guard"]["interval"]) if i == range(0, settings.steam["guard"]["retries"]): while True: self.log("GuardCode sent to " + self.Bot.email["address"] + ". You'll have to manually enter the code.") guardCode = raw_input(color.Fore.BLUE + color.Style.BRIGHT + "[" + self.Bot.name + "] " + color.Fore.RESET + color.Style.RESET_ALL + "GuardCode: ") return guardCode
def fetch_emails(username, password, label, after): """ Fetch unread emails for today and mark read """ g = gmail.login(username, password) emails = g.mailbox(label).mail(after=after) text = [dict_email(e) for e in emails] g.logout() return text
def __init__(self, login, password): self.g = gmail.login(login, password) self.dbname = login.split('@')[0] + ".json" self.db = readJSON(self.dbname) if self.db is None: self.db = {} self.writeDB()
def main(): g = gmail.login(GMAIL_USER, GMAIL_PASS) engagement_emails = g.inbox().mail(sender='*****@*****.**') if len(engagement_emails) == 0: print "No engagement email" return latest = engagement_emails[-1] latest.fetch() trend = "NOTREND" if "*UPTREND*" in latest.body: trend = "UPTREND" if "*DOWNTREND*" in latest.body: trend = "DOWNTREND" r.set(CACHE_KEY_TREND, trend, CACHE_EXPIRY_TIME) for attachment in latest.attachments: if attachment.name == "engagement.xls": print "Saving {name}".format(name=attachment.name) attachment.save(ENGAGEMENT_FILE_PATH) return print "Could not find engagement.xls attachment"
def check_email(): while True: g = gmail.login(GMAIL_USER, GMAIL_PASS) inbox = g.inbox().mail(unread=True, fr=EMAIL_JUSTIN) # justin if inbox: inbox[0].fetch() subject = inbox[0].subject body = inbox[0].body body = body.strip("*") json = { "title": subject, "body": body } db.posts.insert_one(json) inbox[0].read() inbox = g.inbox().mail(unread=True, fr=EMAIL_TIM) # tim if inbox: inbox[0].fetch() subject = inbox[0].subject print subject body = inbox[0].body print body body = body.replace('\r', '<br/>').replace('\n', '<br/>') json = { "title": subject, "body": body } db.posts.insert_one(json) inbox[0].read() g.logout() time.sleep(600) # wait 10 minutes; you dont want all the server resources gone in the next minute
def login_gmail(self): email = gmail.login(receiver_email, receiver_password) if not email: return 0 else: return 1
def checkGmail(): print("Started checkGmail") while True: print "toDie - " + str(toDie) if toDie: print "BARBERBOT CHECK GMAIL DIEING" os.system("ps -ef | grep barber | grep -v grep | tr -s ' ' | cut -d' ' -f2 | xargs kill -9") try: g = gmail.login(username, password) if not g: pass emails = g.inbox().mail(to="*****@*****.**", unread=True, prefetch=True) except: print "Login failed.." pass #emails = g.inbox().mail(to="*****@*****.**", unread=True, prefetch=True) if len(emails) > 0: for email in emails: sender = " ".join(email.fr.split()[:2]) subject = email.subject email.read() print "Attention! New Member email from %s - %s" % (sender, subject) text2send = "Attention! New Member email from %s - %s" % (sender, subject) conn = httplib.HTTPSConnection(_GROUPME_URL) headers = {"Content-type": "application/x-www-form-urlencoded"} params = urllib.urlencode({'text': text2send, 'bot_id': marcsmen_token}) #params = urllib.urlencode({'text': text2send, 'bot_id': botgroup_token}) conn.request("POST", "/v3/bots/post", params, headers) response = conn.getresponse() print response.status, response.reason, response.getheaders() conn.close() time.sleep(600)
def get(self): g = gmail.login(GMAIL_USERNAME, GMAIL_PASSWORD) mails = g.label("info").mail() res = '' for m in mails[-20:]: m.fetch() feeds = make_feeds(mails[-20:]) self.render('index.html', feeds = feeds)
def check_inbox(user, pwd): g = gmail.login(user, pwd) emails = g.inbox().mail() mails = [] for email in emails: email.fetch() mails.append(email) return mails
def get_messages_from_gmail(): g = gmail.login('username', 'password') g.mailbox('ITP').mail() messages = g.mailbox('ITP').mail(prefetch=True) message_list = list() for message in messages: message_list.append(message.subject + ", " + message.fr + ", " + message.thread_id) return message_list
async def refresh_sessions(self): self.gmail_session.close() self.gmail_session.logout() self.gmail_session = gmail.login() self.one_session.close() self.one_session.logout() self.one_session = one.login()
def initEmail(): logEvent('SYSTEM - Initializing email') f = open('email_creds.txt', 'r') line = f.read() creds = line.split('|') f.close() # g = gmail.login(creds[0], creds[1]) return gmail.login('pifacetest', 'SuperSecure!')
def check_inbox(user, pwd) : g = gmail.login(user, pwd) emails = g.inbox().mail() mails = [] for email in emails : email.fetch() mails.append(email) return mails
def email(): g = gmail.login(EMAIL, PASSWORD) message = g.inbox().mail()[-1] message.fetch() urls = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.body) return urls[0]
def open_connection(verbose=False): # Read the config file config = ConfigParser.ConfigParser() config.read('./.mailsettings') #mysql data mysqldata={} mysqldata['hostname'] = config.get('mysql', 'hostname') mysqldata['username'] = config.get('mysql', 'username') mysqldata['password'] = config.get('mysql', 'password') mysqldata['database'] = config.get('mysql', 'database') mysqldata['port'] = int(config.get('mysql', 'port')) # Login to our account username = config.get('account', 'username') password = config.get('account', 'password') folders = config.get('folders', 'mailbox') fromdate = config.get('folders', 'fromdate') todate = config.get('folders', 'todate') if username is '': logger.error("Enter Username in config") sys.exit(1) if password is '': logger.error("Enter Password in config") sys.exit(1) if folders is '': logger.warn("Set of folders is none. So setting it to Inbox") if fromdate is '': logger.warn("From date is none. So setting fromdate and todate to current date") now = datetime.datetime.now() fromdate = now.strftime("%Y-%m-%d") todate = fromdate #if todate is '': #now = datetime.datetime.now() #todate = now.strftime("%Y-%m-%d") for k, v in mysqldata.iteritems(): if v is None: logger.error("mysqldata Key: " + k + " is None") sys.exit(1) if verbose: logger.info('Logging in as ' + username) connection = gmail.login(username, password) logger.info("Connection: " + str(connection)) logger.info("Folders: " + folders) logger.info("FromDate: " + fromdate) logger.info("ToDate: " + todate) return connection, folders, fromdate, todate, mysqldata
def main(): g = gmail.login(GMAIL_USERNAME, GMAIL_PASSWORD) for mail in g.inbox().mail(unread=True, prefetch=True): match = KEYWORDS_REGEX.search(mail.subject) if match: #print match slack.notify(text="PING_NG") else: slack.notify(text="Tails")
def main(): while True: g1 = gmail.login(""); # User login ("username","password") BBBunread = g.inbox().mail(unread=True, sender=""); # set sender equal to email you want to spam if BBBunread: for unread in BBBunread: sendSpam(); unread.delete(); g1.logout(); time.sleep(5);
def gm_connect(): username = "******" #Send me some emails sure password = "" try: print "Logging into {0}".format(username) gmail_connection = gmail.login(username, password) return gmail_connection except: print "Error", sys.exc_info()[0:5] gmail_connection.logout()
def main(): #TODO: implement oauth authentication for email; was left to password to allow for different accounts between email and Drive. g = gmail.login('<email>', '<password>') emails = g.mailbox('<label name>').mail(unread=True) if emails: logging.info('Number of emails to process: %s' % len(emails)) grabHtml(emails) parseURLs() grabImages() uploadImages() sendBullet() else: logging.info('No emails to process. Exiting.')
def get_mail(user,passwd,list): g = gmail.login(user, passwd) emails=g.inbox().mail(unread=True, to=list) data=[] currentMail=[] for email in emails: email.fetch() email.read() if (email.thread_id==email.message_id and email.subject[:3]!="Re:"): global xy xy=email.sent_at currentMail.insert(0,[email.subject,email.body,email.sent_at]) return currentMail
def get_unseen_emails(username: str, password: str) -> list: """ Login to gmail and get unseen emails :param username: str :param password: str :return: list """ g = gmail.login(username, password) unseen_mails = g.inbox().mail(unread=True) g.logout() return unseen_mails
def process_unread_emails(username, password): print 'Checking unread mail for music URIs' uris = [] g = gmail.login(username, password) emails = g.inbox().mail(unread=True, prefetch=True) for email in emails: uri = parse_supported_uri(email.body) if uri is not None: uris.append(uri) print '\nFrom[%s]\nSent at[%s]\nSubject[%s]\nURI[%s]\n' % ( email.fr, email.sent_at, email.subject, uri) email.read() g.logout() return uris
def get_emails(box, date=datetime.datetime.now()): gmail_conn = gmail.login(TEST_GMAIL_ID, TEST_GMAIL_PWD) emails = gmail_conn.label(box).mail(after=date) results = [] print "num emails:", len(emails) for email in emails: # Call fetch to pull in email attributes email.fetch() results.append(email) gmail_conn.logout() print "Logged in?", gmail_conn.logged_in return results
def download_attachments(username, password, label, extension, save_dir): ''' username: username of the gmail account (make sure you enable login for less secure apps) password: password of the gmail account label: label of the messages with attachments extension: file extension expected (e.g. .json) save_dir: path of directory you want attachments saved in ''' g = gmail.login(username, password) mail = g.mailbox(label).mail() for m in mail: m.fetch() for attach in m.attachments: if os.path.splitext(attach.name)[1] == extension: attach.save(save_dir) print 'saving ' + attach.name + ' from ' + m.fr g.logout()
def clean_gmail(username, password): """ Archive or delete (default archive) old unread messages. """ g = gmail.login(username, password) old_unread_messages = get_old_unread_messages(g) print '%s unread old messages in your inbox!' % len(old_unread_messages) print 'Cleaning in progress!' for message in old_unread_messages: if ARCHIVE: print 'Message %s is being archived!' % message.uid message.archive() else: print 'Message %s is being deleted!' % message.uid message.delete() print 'All cleaning done!'
def parse_gmail(self, username, password): """ This method is used to parse the inbox of a valid Gmail account. The flag used for this method to send to output.py is 1. @author Robb Krasnow @param username The gmail account's username @param password The gmail account's password """ try: if self.dedup: self.dedup_store = set() # Log the user in g = gmail.login(username, password) # When the user is logged in, grab all the email from their inbox # and parse all the messages for IOCs if g.logged_in: print('***** Login Successful. *****\n') self.handler.print_header(username) emails = g.inbox().mail() for email in range(0, len(emails)): try: emails[email].fetch() content = emails[email].body subject = re.sub('(^\s|re:\s+|\r\n|fwd:\s+)', '', emails[email].subject, flags=re.IGNORECASE) self.parse_page(subject, content, 1, 1) except Exception as e: continue self.handler.print_footer(username) print('\n***** %s emails found. *****' % len(emails)) g.logout() print('***** Logout Successful. *****') else: sys.exit() except gmail.exceptions.AuthenticationError: print('Authentication Error') sys.exit()
def parse_gmail(self, username, password): """ This method is used to parse the inbox of a valid Gmail account. The flag used for this method to send to output.py is 1. @author Robb Krasnow @param username The gmail account's username @param password The gmail account's password """ try: if self.dedup: self.dedup_store = set() # Log the user in g = gmail.login(username, password) # When the user is logged in, grab all the email from their inbox # and parse all the messages for IOCs if g.logged_in: print '***** Login Successful. *****\n' self.handler.print_header(username) emails = g.inbox().mail() for email in range(0, len(emails)): try: emails[email].fetch() content = emails[email].body subject = re.sub('(^\s|re:\s+|\r\n|fwd:\s+)', '', emails[email].subject, flags=re.IGNORECASE) self.parse_page(subject, content, 1, 1) except Exception as e: continue self.handler.print_footer(username) print '\n***** %s emails found. *****' % len(emails) g.logout() print '***** Logout Successful. *****' else: sys.exit() except gmail.exceptions.AuthenticationError: print 'Authentication Error' sys.exit()
def get_receipt_emails(query_from, query_to): """ Retrieve emails from gmail """ import gmail g = gmail.login(settings.RECEIPT_INBOX_USERNAME, settings.RECEIPT_INBOX_PASSWORD) # NOTE: the query_from/query_to has been removed. This script will only # try to process emails that are unread and it'll set them to read after # being processed Maybe later on we need to start querying date ranges, # but given the volume of emails this should be a more robust solution. emails = g.inbox().mail(sender=settings.RECEIPT_INBOX_FROM_EMAIL, unread=True) yield emails g.logout()
def check_spam(self, email_subject): # Check Email and Return Password email = gmail.login(receiver_email, receiver_password) unread = email.spam().mail(sender=sender_email, prefetch=True, unread=True) password = "" if len(unread) > 0: for message in unread: date = message.sent_at print("-----------SPAM--------------") print(date.date()) if date.date() == date.today(): if message.subject == email_subject: password = self.locate_password(message.body) return password
def main(): _, user, pw, days = argv g = gmail.login(user, pw) if g.logged_in: print "Logged in to %s." % user junk = find_junk(g, days) html = write_html(junk) filename = "%s--%s.html" % (str(date.today() - timedelta(days=int(days))), str(date.today())) f = open(filename, 'w') f.write(html) f.close() try: filename = 'file://%s/%s' % (os.path.dirname(os.path.realpath(__file__)), filename) webbrowser.open_new_tab(filename) except: print 'Open %s in your web browser.' % filename else: print "Could not log in to %s." % user
def main(args): re_subject = re.compile('CMD_SVVPA[ ]+(?P<cmd>\w+)[ ]*(?P<args>.*)') g = greader.login(os.environ['SMPT_USER'], os.environ['SMPT_PASS']) emails = g.mailbox('CMD_SVVPA').mail(unread=True) uids = [e.uid for e in emails] g.logout() for uid in uids: e = getEmailByUid(uid) e.read() subject = e.subject.replace("\r\n","") print u"[{}] {}: Procesando comando '{}'".format(datetime.datetime.now(), __file__, subject) r = re_subject.search(subject) if r and CMD_SVVPA.has_key(r.group('cmd')): try: print u"[{}] {}: Ejecutando comando '{}'".format(datetime.datetime.now(), __file__, r.group('cmd')) e=getEmailByUid(uid, e) e.add_label(CMD_WORKING) CMD_SVVPA[r.group('cmd')](r.group('args')) print u"[{}] {}: Comando '{}' ejecutado correctamente".format(datetime.datetime.now(), __file__, r.group('cmd')) e=getEmailByUid(uid, e) e.add_label(CMD_OK) e.remove_label(CMD_WORKING) except Exception, ex: print >> sys.stderr, u"[{}] {}: ERROR! Ha ocurrido el error '{}' al procesar el comando '{}'".format(datetime.datetime.now(), __file__, repr(ex), r.group('cmd')) e=getEmailByUid(uid, e) e.add_label(CMD_ERROR) msg_subject = error_general_subject.format(command=r.group('cmd')) msg_html = error_general_html.format(command=r.group('cmd'), error=ex) notificar_email(msg_subject, msg_html) else: print >> sys.stderr, u"[{}] {}: ERROR! La sintaxis del comando '{}' no es correcta.".format(datetime.datetime.now(), __file__,r.group('cmd')) e=getEmailByUid(uid, e) e.add_label(CMD_ERROR) msg_subject = error_sintaxis_subject msg_html = error_sintaxis_html.format(command=r.group('cmd'), correo=os.environ['GMAIL_ACCOUNT_ALIAS']) notificar_email(msg_subject, msg_html)
def gmail_verify(g_sender): # function to get verfiy code # fetch verification code from gmail g_username = gmail_user_openroadintegrated g_password = gmail_password_openroadintegrated g = gmail.login(g_username, g_password) sleep(60) # get mails from goodreads and download the goodreads attachement emails = g.inbox().mail(sender = g_sender) # access the newest email emails[len(emails)-1].fetch() code_string = emails[len(emails)-1].body # access the email information res = re.search('Sailthru verification code: ', code_string).end() output_code = code_string[res:res+6] print(output_code) return output_code
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.SESSION = dict() if os.path.exists('session.json'): with open('session.json', 'r') as fp: d = json.load(fp) self.SESSION['discord'] = d['discord'] else: self.SESSION['discord'] = { "modmail": { "listeners": {} }, "cancelled": { "listeners": {} } } self.gmail_session = gmail.login() self.one_session = one.login() self.GMAIL_DATA = gmail.Data() self.cancelled_sessions_job.start()
def index(): g = gmail.login(receiver_email, receiver_password) if not g: print("Login Failed") else: unread = g.inbox().mail(sender=sender_email, prefetch=True, unread=True) print(len(unread)) for message in unread: if message.subject == "Invitation": print("Message", message.subject) print(locate_password(message.body)) password = locate_password(message.body) # if message.subject == "Re-Invitation": # password = locate_password(message.body) # print("Message", message.subject) # print(locate_password(message.body)) return password return "nani"
ssl._create_default_https_context = ssl._create_unverified_context opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ssl.SSLContext(ssl.PROTOCOL_SSLv23))) urllib2.install_opener(opener) today=str(datetime.datetime.now())[:10] # YYYY MM DD for name of directory year = today[:4] month = today[5:7] day = today[-2:] dirpath = os.path.expanduser('~') + '\Desktop\\result\\' + today # Path of directory ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE flat = "N/A" flon = "N/A" g = Gmail() g = gmail.login('*****@*****.**', 'qaz123ws') print "[*] Authentication complete." emails = g.inbox().mail(sender='*****@*****.**') print "[*] Engaging email parsing." for email in emails: email.read() email.fetch() time = email.sent_at print email.subject print "original time: ",time time = time + datetime.timedelta(hours=9) print "processed time: ",time print "________________\r\n" todayDir() SQLInit()
def check_email(): """Check the mail account and lint new mail.""" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(user, password) g = gmail.login(user, password) # Check for unread messages. unread = g.inbox().mail(unread=True) # Submit a job to lint each email sent to [email protected]. Record the # resulting job_ids somewhere (in Redis, I suppose), keyed by a hash of the # email. for u in unread: u.fetch() signature = u.fr.decode("utf-8") + u.subject.decode("utf-8") + u.body.decode("utf-8") hash = hashlib.sha256(signature.encode("utf-8")).hexdigest() if user_to in u.to or user_to in u.headers.get("Cc", []): job_id = conn.get(hash) if not job_id: # If the email hasn't been sent for processing, send it. r = requests.post(api_url, data={"text": u.body}) conn.set(hash, r.json()["job_id"]) else: # Otherwise, check whether the results are ready, and if so, # reply with them. r = requests.get(api_url, params={"job_id": job_id}) if r.json()["status"] == "success": reply = quoted(u.body) errors = r.json()["data"]["errors"] reply += "\r\n\r\n".join([json.dumps(e) for e in errors]) msg = MIMEMultipart() msg["From"] = "{} <{}>".format(name, user) msg["To"] = u.fr msg["Subject"] = "Re: " + u.subject msg.add_header("In-Reply-To", u.headers["Message-ID"]) msg.add_header("References", u.headers["Message-ID"]) body = reply + "\r\n\r\n--\r\n" + tagline + "\r\n" + url msg.attach(MIMEText(body, "plain")) text = msg.as_string() server.sendmail(user, u.fr, text) # Mark the email as read. u.read() u.archive()
import gmail import requests from datetime import date import json import os.path g = gmail.login(config.gmail.user, config.gmail.password) #only unarchived, unread messages marked as priority up until midnight pacific today = date.today() msgs = g.important().mail(unread=True, label="INBOX", before=today) num_msgs = len(msgs) datfile = '/home/jcarver/code/quantified-self/dat/mail-priority-count/%s' % today.strftime('%Y%m%d') if not os.path.isfile(datfile): with open(datfile, 'w') as f: f.write('%s\n' % num_msgs)
import re import json import re import datetime import logging import smtplib #logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from gensim import corpora, models, similarities user = '******' #CHANGE password = "******" #CHANGE g = gmail.login(user, password) def unix_time(dt): epoch = datetime.datetime.utcfromtimestamp(0) delta = dt - epoch return delta.total_seconds() def get_annoying_emails(): parsed_mail = {} annoying_mails = g.label('annoying').mail() for annoying_mail in annoying_mails: annoying_mail.fetch() #print(annoying_mail.fr)
os.system("sudo apt-get update") print "Repositórios atualizados" os.system("sudo apt-get upgrade -y") print("Pacotes atualizados") os.system("sudo apt-get dist-upgrade -y") print("Distribuição atualizada") # else: # os.system("sudo apt-get update") # print "Os repositórios foram atualizados" # # os.system("sudo apt-get autoremove") # print("Sistema atualizado, e limpo") if comando=="-gmail": g = gmail.login("*****@*****.**", "senha") if g.logged_in: print dir(g) # for email in folder: # print email.id, len(email), email.subject # for msg in email: # print " ", msg.id, msg.number, msg.subject # print msg.source
# Gmail Checker # #-------------------------# # Download gmail library from https://github.com/charlierguo/gmail # use http://www.thegeekstuff.com/2010/08/sms-using-email/ import gmail import getpass import time from email.mime.text import MIMEText from subprocess import Popen, PIPE def sendMail(n): msg = MIMEText("Chk mail.") msg["From"] = "user@domain" msg["To"] = "*****@*****.**" msg["Subject"] = "Unread mail" p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) p.communicate(msg.as_string()) username = "******" password = getpass.getpass("Password: "******"Logged in" prevNum = 0 while 1: numEmails = g.inbox().count(unread=True) if numEmails > prevNum: sendMail(numEmails) prevNum = numEmails time.sleep(5) g.logout()
def _do_login(self): c = self.connection if c is None: c = gmail.login(self.username, self.password) self.connection = c return True
def readMail(): # Read & Parse the mail index = 0 gpsflag = 0 seplat = 0.0 maxlat = 0.0 minlat = 999.999 datalat = [] seplon = 0.0 maxlon = 0.0 minlon = 999.999 datalon = [] gpsdata = "" try: flat = "N/A" flon = "N/A" g = Gmail() g = gmail.login('*****@*****.**', 'qaz123ws') print "[*] Authentication complete." emails = g.inbox().mail(sender='*****@*****.**') print "[*] Engaging email parsing." for email in emails: index = index + 1 email.read() email.fetch() time = email.sent_at print time time = time + datetime.timedelta(hours=9) print time body = email.body print "[*] RAW body : "+body if (len(body) >= 12) and (body.find("http") == -1) : body = b64(email.body) print "[*] Base64 decoded body : "+body surl = re.findall('(https?:\/\/\S+)', str(body)) surl = str(surl)[2:-2] path = (surl.split("/")[-1]) surl = surl.replace(path, '') path = re.sub('[=@#?$}.]', '', path.decode('utf-8')) surl = surl + path if len(str(surl).split("/")[-1]) > 4 and str(surl).find("grep.kr") != -1 : print str(surl.find("grep.kr")) path = (surl.split("/")[-1]) surl = surl.replace(path, '') path = path[:4] surl = surl + path print "[*] grep.kr processed: ", surl if str(surl).decode('utf-8').find(str("\\x")) > -1 : print surl print str(surl).decode('utf-8') surl = re.sub('(\\\\x..)', '', str(surl).decode('utf-8')) print "[*] Junk data removed: ", surl if str(surl).find('\\n') != -1: surl = str(surl)[:-2] print "[*] New line removed: ", surl furl, surl = unshortURL(surl.decode('utf-8')) print "[*] URL Unshortened" print "[*] Shortened URL : "+surl print "[*] Full URL : "+str(urllib.unquote(urllib.unquote(furl)).decode('utf-8').encode('cp949')) filename = furl.split('/')[-1] filepath = (dirpath+"\\"+filename) filepath = urllib2.unquote(urllib.unquote(filepath)).decode('utf-8').encode('cp949') req = urllib2.Request(furl, headers={ 'User-Agent': 'Mozilla/5.0' }) req.add_header('Accept', 'application/json') file = urllib2.urlopen(req) file.close() urllib.urlretrieve(furl, filepath) fMD5 = MD5(filepath) fSHA1 = SHA1(filepath) if filepath.split('.')[-1] == 'jpg' : flat, flon = jpgGPS(filepath) if flat!="N/A" and flon!="N/A" : print "[*] GPS data found, Lat: " + str(flat) +" Lon:"+str(flon) flat = float(flat) flon = float(flon) datalat.append(flat) datalon.append(flon) if(flat > maxlat) : maxlat = flat if(flat < minlat) : minlat = flat if(flon > maxlon) : maxlon = flon if(flon < minlon) : minlon = flon gpsflag=1 furl = urllib.unquote(urllib.unquote(furl)) filename = urllib.unquote(urllib.unquote(filename)) print "[*] Information added to CSV file" addCsv(filepath, str(index), str(time), str(surl), str(furl), str(filename), str(flat), str(flon), str(fMD5), str(fSHA1)) SQLDump(str(time), str(surl), str(furl), str(filename), str(flat), str(flon), str(fMD5), str(fSHA1)) finallat = datalat[:] finallon = datalon[:] except gmail.AuthenticationError: print "Auth fail" print "[*] Mail read complete." if gpsflag == 1: latsum = 0.0 lonsum = 0.0 for i in datalat: latsum = latsum + i latavg = latsum / len(datalat) for i in datalon: lonsum = lonsum + i lonavg = lonsum / len(datalon) if((abs(maxlat-minlat) > 1.5) or abs(maxlon-minlon) > 1.5) and ((abs(latavg-minlat) > 1.5) or (abs(lonavg-minlon) > 1.5)) : datalat.remove(maxlat) datalat.remove(minlat) datalon.remove(maxlon) datalon.remove(minlon) sum = 0.0 latsum = 0.0 lonsum = 0.0 print maxlat, minlat, latavg, datalat, finallat print maxlon, minlon, lonavg, datalon, finallon print lonavg if(abs(latavg-minlat) > 1.5): print "[*] latavg - minlat : ",latavg-minlat finallat.remove(minlat) seplat = minlat elif(abs(maxlat-latavg) > 1.5) : print "[*] maxlat - latavg : ", maxlat-latavg finallat.remove(maxlat) seplat = maxlat if(abs(maxlon-lonavg) > 1.5) : print "[*] maxlon - lonavg : ", maxlon-lonavg finallon.remove(maxlon) seplon = maxlon elif(abs(lonavg-minlon) > 1.5): print "[*] lonavg - minlon : ",lonavg-minlon finallon.remove(minlon) seplon = minlon seperateGPSMAP(filepath, seplat, seplon) print seplat, seplon for i in range(len(finallat)): gpsdata = gpsdata+str(finallat[i])+","+str(finallon[i])+"|" GPSMAP(filepath, gpsdata)
def __init__(): self.account = gmail.login(email_address, email_password)
def main(): # Parse Today's Date print "[!] E-Mail Parser" print "==================================================================================================" now_date = datetime.datetime.now() cov_date = str(now_date)[8:10] cov_date = int(cov_date) print "[+] Today is " + str(cov_date) + " day" print "[+] Prepare to parsing" # Make DB File file_db = open("..\\result.db", "a+") print "[-] Make DB File!" con = sqlite3.connect("..\\result.db") con.text_factory = str cursor = con.cursor() # Create Table cursor.execute( "CREATE TABLE IF NOT EXISTS result(File_Time text, Short_URL text, Long_URL text, File_Name text, GPS_X text, GPS_Y text, MD5 text, SHA1 text)" ) # Create CSV File file_csv = open("result.csv", "w") result = csv.writer(file_csv, lineterminator='\n') print "[-] Make CSV File!" result.writerow(["\xEF\xBB\xBF"]) result.writerow([ "File Number", "Time", "Short URL", "Long URL", "File Name", "GPS (X)", "GPS (Y)", "MD5", "SHA1" ]) # Login Gmail print "[-] Log-on Gmail Account..." g = gmail.login('-', '-') target = '*****@*****.**' # Check Mail in Box emails = g.inbox().mail(on=datetime.date(2016, 7, 29), sender=target) print "[-] Collect Link from Target's E-Mail : " + target file_num = 0 print "==================================================================================================" # Define GPS Info List gps_list = [] for email in emails: # for every email sent in same day email.fetch() txt = email.body file_num += 1 # File Number Count print "[!] Send Time : " + str(email.sent_at) + "\n" dec_txt = txt # Encoding Compare if email.headers.has_key('Content-Transfer-Encoding'): if email.headers['Content-Transfer-Encoding'] == 'base64': dec_txt = base64.b64decode(txt) else: pass # Use Regular Expression reg = '((https?://grep\.kr/[0-9a-zA-Z]{4})|https?://goo\.gl/[0-9a-zA-Z]{6})|(https?://me2\.do/[0-9a-zA-Z]{8})' file_short = re.search(reg, dec_txt).group() # Long URL try: long_url = urllib.urlopen( file_short, context=ssl._create_unverified_context()).geturl() file_long = urllib.unquote(urllib.unquote(long_url)) # If Link is bomb, shutdown program except: print "[!] Warning : Sorry, This Link is Bomb!\n" result.writerow([ file_num, email.sent_at, file_short, None, None, None, None, None, None ]) exit() # Print URL Info print "[+] URL Info" print "[-] Short URL : " + file_short print "[-] Long URL : " + file_long + "\n" # Parse File Name file_name = file_long.split('/')[-1].decode('UTF-8') print "[+] File Name : " + file_name + "\n" try: # Download File from Long URL urllib.urlretrieve(long_url, file_name, context=ssl._create_unverified_context()) except: # HTTP/HTTPS Compare and Add long_url = long_url.replace("http", "https") urllib.urlretrieve(long_url, file_name, context=ssl._create_unverified_context()) d_file = open(file_name, 'rb') # Export GPS Info from Image File tags = exifread.process_file(d_file) # This File included GPS info? if 'GPS GPSLongitude' in tags: # Calculate GPS_Y degx = int(tags['GPS GPSLatitude'].values[0].num) minx = int(tags['GPS GPSLatitude'].values[1].num) secx = float(tags['GPS GPSLatitude'].values[2].num ) / tags['GPS GPSLatitude'].values[2].den # Calculate GPS_X degy = int(tags['GPS GPSLongitude'].values[0].num) miny = int(tags['GPS GPSLongitude'].values[1].num) secy = float(tags['GPS GPSLongitude'].values[2].num ) / tags['GPS GPSLongitude'].values[2].den file_gpsy = (degy + (miny + secy / 60.0) / 60.0) file_gpsx = (degx + (minx + secx / 60.0) / 60.0) # If image file is include Ref Tag if tags['GPS GPSLatitudeRef'].values == "S": file_gpsx = -file_gpsx else: pass # Print EXIP GPS Info print "[+] EXIF GPS Info" print "[-] GPS_X : " + str(file_gpsx) print "[-] GPS_Y : " + str(file_gpsy) + "\n" # Add info to GPS List gps_list.append(str(file_gpsx) + ',' + str(file_gpsy)) else: print "[!] This File is not include GPS info\n" file_gpsx = None file_gpsy = None # File Read file_read = d_file.read() # Calculate File of Hash file_md5 = hashlib.md5(file_read).hexdigest() file_sha1 = hashlib.sha1(file_read).hexdigest() d_file.close() # Print Hash Info print "[+] File Hash Info" print "[-] MD5 : " + file_md5 print "[-] SHA1 : " + file_sha1 + "\n" # Write on CSV File result.writerow([ file_num, email.sent_at, file_short, file_long, file_name.encode('UTF-8'), file_gpsx, file_gpsy, file_md5, file_sha1 ]) print "[!] Success write on CSV file" # Write on DB File cursor.execute("INSERT INTO result VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (email.sent_at, file_short, file_long, file_name, file_gpsx, file_gpsy, file_md5, file_sha1)) print "[!] Success write on DB file" print "==================================================================================================" # Commit and Close DB File con.commit() con.close() # Define Google API Key google_api_key = '&key=AIzaSyAgkE8M1Zj_qAGrIuh62497eRHazjS_jB4' # Define Standard Map Link map_standard = 'https://maps.googleapis.com/maps/api/staticmap?&zoom=2&size=1500x1200&maptype=satellite&markers=' map_path = '&path=' # Export GPS Info from List for gps_xy in gps_list: map_standard = map_standard + gps_xy + '%7C' map_path = map_path + gps_xy + '%7C' # Create Final Map URL real_map_url = map_standard + map_path[0:-3] + google_api_key # Open & Download Map Image File urllib.urlretrieve(real_map_url, "travel_path.jpg", context=ssl._create_unverified_context()) print "\n[!] Success Download Travel Path Photo" print "[+] Make trave_path.jpg" print "\n=================================================================================================="
import gmail import datetime import geeknote g = gmail.login("") todays_mail = g.inbox().mail(after=datetime.date.today(), subject = "evernote") messagecounter = 0 for i in todays_mail: messagecounter = messagecounter + 1 message = str(i.fetch()) f = open("output" + str(messagecounter) + ".txt", "w") f.write(message)
return None def send_message(user, message): print "Sending a message to %s" % (user) from_address = gmail_email to_address = user server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(gmail_username, gmail_password) server.sendmail(from_address, to_address, message) server.quit() if __name__ == '__main__': g = gmail.login(gmail_username, gmail_password) users = get_users(g) for user in users: message = get_mail_message(g, user) print message # check if message is sent today. today_after = date.today() today_before = today_after + timedelta(days=1) result = g.sent_mail().mail(to=parse_email(user), before=today_before, after=today_after, prefetch=True) if not result: send_message(user, message)
import os import sys import gmail import csv import folium # To import functions that i made. sys.path.insert(0, "./mail") import secret_login import parse_mail import pic_process import csv_process try: # login with secret_login. It just store my id & pw. g = gmail.login(secret_login.id, secret_login.pw) if g.logged_in: print('[*] Mail log in success') # Only select unread mail from [email protected] unread = g.inbox().mail(unread=True, sender='*****@*****.**') # This is for mail index. i = 0 # This is for csv index. number = 0 # This is for gps visualization of all received mail. gps_all = folium.Map(location=[22.9602, 119.2102], zoom_start=5) for new in unread: # If not fetch, can not read email new.fetch()
import sys import gmail g = gmail.login(str(sys.argv[1]), str(sys.argv[2])) if len(sys.argv) > 3 and str(sys.argv[3]) == 'spam': emails = g.mailbox("[Gmail]/Spam").mail(prefetch=True) else: emails = g.inbox().mail(prefetch=True) for index, email in enumerate(emails): with open(str(index) + ".txt", "w") as file: file.write(email.body) g.logout()