def respose(choice): if choice == '1': print("enter recipient:- ") recipient = input() subject = input("Enter subject:-") text = input("Enter your message(should be 1 liner):- ") #for i in range(0,len(recipients)): # recipient=str(recipients[i]) ezgmail.send(recipient, subject, text) if choice == '2': unread = ezgmail.unread() #get subject and date results = ezgmail.summary(unread) #print the email print(str(unread[0].messages[0])) if choice == '3': #searching gSearch = input("what you want to search:-") search_result = ezgmail.search(gSearch) print(len(search_result)) results = ezgmail.summary(search_result) if choice == '4': #downloadinng gSearch = input("what you want to search:-") attacmentName = input("name of the attachment:-") download = ezgmail.search(gSearch) download[0].messages[0].downloadAttachment(attacmentName) if choice == '5': exit()
def check_for_job_notification( jobid, labelname='Telescope Notifications/20A-346 Cedar Jobs', markasread=True): if not do_authentication_gmail(): raise ValueError("Cannot login with ezgmail. Check credentials.") notification_emails = ezgmail.search(f"label:{labelname}") # Loop through and see if we find that job ID: for email in notification_emails: # Emails can have multiple messages (replies/grouped emails) for message in email.messages: if str(jobid) not in message.subject: continue # Grab completion, run time for job. jobinfo = message.subject.split(",") status = jobinfo[2].replace(' ', '') runtime = jobinfo[1].split(" ")[-1] if markasread: message.markAsRead() return status, runtime return None
def get_mails(self): from .models import Letter, Attachment try: with open('mail_app/mail_data.json', 'rb') as data_file: downloaded_summary = pickle.load(data_file) mail_data_exists = True except FileNotFoundError: downloaded_summary = None mail_data_exists = False self.latest_letters = ezgmail.search('in=inbox') for letter in self.latest_letters: letter = letter.messages[0] if ezgmail.summary(letter, printInfo=False ) == downloaded_summary and mail_data_exists: break else: aware_datetime = make_aware(letter.timestamp) letter_obj = Letter(mailer=letter.sender, topic=letter.subject, text=letter.body, date_time=aware_datetime) letter_obj.save() for file in letter.attachments: letter.downloadAttachment( file, downloadFolder='media/mail_attachments/') attachment = Attachment() attachment.file.name = 'media/mail_attachments/' + file attachment.letter = letter_obj attachment.save() with open('mail_app/mail_data.json', 'wb') as data_file: latest_letter_summary = ezgmail.summary(self.latest_letters[0], printInfo=False) pickle.dump(latest_letter_summary, data_file)
def getpaypal(): threads = ezgmail.search('subject:canceled automatic payments to you') i = 0 while i < len(threads): n = 0 messages = threads[i].messages while n < len(messages): # Get the data of the email source = 'PayPal' sender = [threads[i].messages[n].sender] timestamp = [str(threads[i].messages[n].timestamp)] # Find relevant data from the body of the email if re.search(r'Customer name:</th><td width="60%">.*</td></tr></table><table cellpadding="5" ' r'cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; ' r'font-weight:normal; border-bottom:0px;" width="40%">Customer email:', threads[i].messages[ n].body) is None: customer_name = re.compile(r'Customer name: .*\s').search(threads[i].messages[n].body).group().strip()[15:] customer_email = re.compile(r'Customer email: .*\s').search(threads[i].messages[n].body).group().strip()[ 16:] profile_id = re.compile(r'Profile ID: .*\s').search(threads[i].messages[n].body).group().strip()[12:] profile_status = re.compile(r'Profile status: .*\s').search(threads[i].messages[n].body).group().strip()[ 16:] amount_paid_each_time = re.compile(r'Amount paid each time: .*\s').search( threads[i].messages[n].body).group().strip()[23:-3] billing_cycle = re.compile(r'Billing cycle: .*\s').search(threads[i].messages[n].body).group().strip()[15:] last_payment_date = re.compile(r'Last payment date: .*\s').search( threads[i].messages[n].body).group().strip()[ 19:] last_payment_amount = re.compile(r'Last payment amount: .*\s').search( threads[i].messages[n].body).group().strip()[21:-3] else: customer_name = re.compile(r'Customer name:</th><td width="60%">.*</td></tr></table><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Customer email:').search(threads[i].messages[n].body).group().strip()[35:-192] customer_email = re.compile(r'Customer email:</th><td width="60%">.*</td></tr></table><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Profile ID:').search(threads[i].messages[n].body).group().strip()[36:-188] profile_id = re.compile(r'Profile ID:</th><td width="60%">.*</td></tr></table><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Profile status:').search(threads[i].messages[n].body).group().strip()[32:-192] profile_status = re.compile(r'Profile status:</th><td width="60%">.*</td></tr></table></td></tr></table><table cellpadding="0" cellspacing="0" style="font:1em Calibri, Trebuchet, Arial, sans serif, sans-serif; border:1px solid #eee;margin-top:10px;border-right:0;margin-bottom:10px;" width="100%"><tr><td><span style="display:inline;"><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Amount paid each time:').search(threads[i].messages[n].body).group().strip()[36:-450] amount_paid_each_time = re.compile(r'Amount paid each time:</th><td width="60%">.*HUF</td></tr></table></span><span style="display:inline;"><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Billing cycle:').search( threads[i].messages[n].body).group().strip()[43:-234] billing_cycle = re.compile(r'Billing cycle:</th><td width="60%">.*</td></tr></table></span><span style="display:inline;"><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Last payment date').search(threads[i].messages[n].body).group().strip()[35:-233] last_payment_date = re.compile(r'Last payment date:</th><td width="60%">.*</td></tr></table></span><span style="display:inline;"><table cellpadding="5" cellspacing="0" width="100%"><tr><th style="background-color:#eee; text-align:left; font-weight:normal; border-bottom:0px;" width="40%">Last payment amount:').search(threads[i].messages[n].body).group().strip()[ 39:-236] last_payment_amount = re.compile(r'Last payment amount:</th><td width="60%">.*HUF</td></tr></table></span></td></tr></table><br/><!-- EmailClosingSalutation').search( threads[i].messages[n].body).group().strip()[41:-79] # Compile all relevant data to a list of lists msg.append( [source] + sender + timestamp + [customer_name] + [customer_email] + [profile_id] + [profile_status] + [amount_paid_each_time] + [billing_cycle] + [last_payment_date] + [last_payment_amount]) n += 1 i += 1
def test_basic(): assert ezgmail.EMAIL_ADDRESS == TEST_EMAIL_ADDRESS attachmentFilename = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'attachment.txt') # This test doesn't check the results, it just makes sure these functions don't raise any exceptions: ezgmail.send(TEST_EMAIL_ADDRESS, TEST_SUBJECT, 'This is the body of the email.', [attachmentFilename]) unreadThreads = ezgmail.unread() unreadThreads[ 0] # NOTE: Make sure the test email account always has at least one unread message. ezgmail.summary(unreadThreads, printInfo=False) recentThreads = ezgmail.recent() msg = recentThreads[0].messages[0] msg.sender msg.recipient msg.subject msg.body msg.timestamp ezgmail.search('mancala')
def check_for_archive_notification( ebid, labelname='Telescope Notifications/20A-346 Archive Notifications', project_id=PROJECTID, timewindow=2 * 24 * 3600, verbose=True, markasread=True, **kwargs): """ Given en execution block ID, search for a notification that the archive has sent an email for the staged data. Return the whole MS name and lustre path on AOC. Parameters ---------- timewindow: float or int, optional Time window to consider notification within. Default is 48 hr. """ if not do_authentication_gmail(**kwargs): raise ValueError("Cannot login with ezgmail. Check credentials.") notification_emails = ezgmail.search(f"label:{labelname}") # Loop through and see if we find that EBID: for email in notification_emails: # Emails can have multiple messages (replies/grouped emails) for message in email.messages: if str(ebid) not in message.originalBody: continue if (datetime.now() - message.timestamp).total_seconds() > timewindow: if verbose: log.info( f"Found notification older than {timewindow / 3600.} hr. Skipping." ) continue # Grab and return the full MS name from the archive email: path_to_data, ms_name = extract_path_and_name( message.originalBody, project_id) if markasread: message.markAsRead() return path_to_data, ms_name return None
def read_mail(): """ Fetches your medium digest and emails you with tracking links removed. """ resultThreads = ezgmail.search('from:[email protected]', maxResults=25) text = resultThreads[0].messages[0].originalBody text = re.sub( r'(https://medium\.com/@[a-zA-z0-9]+/.*?)\?.*?§ionName=.*?\)', r'\1)', text, ) ezgmail.send(ezgmail.EMAIL_ADDRESS, 'Your Medium Digest Tracking Free', text)
def run(): max_emails = 100 ezgmail.init() print(ezgmail.EMAIL_ADDRESS) print("Searching for ig statement attachments in 2020, unread ") email_threads = ezgmail.search( "2020 from:'*****@*****.**' label:unread has:attachment", maxResults=max_emails) # threads = ezgmail.search("2011 from:'*****@*****.**' has:attachment", maxResults=MAX_RESULTS) print(email_threads) print(len(email_threads)) print("iterating through all the threads") count = 1 for thread in email_threads: print("email thread", count, ":", thread) file = thread.messages for item in file: file = item.attachments # attachment_name = pprint.pprint(file) print("printing how the attachment reads", file) filename = file[0] item.downloadAttachment(filename, config.SETTINGS['local_tmp'], duplicateIndex=0) # MOVE ITEM INTO statements_folder move() count += 1 # move files to google drive: # we use dropbox as it works better in ubuntu! base_dir = config.SETTINGS['statements_path'] move(movdir=config.SETTINGS['local_statements'], basedir=base_dir) ezgmail.markAsRead(email_threads) # Classify the files in dropbox and move them across ocr_classification() # move into folders mov_into_monthly(config.SETTINGS['statements_path'])
def test_readEmail(): # There should be an email with subject "DO NOT DELETE" used for the purposes of testing. gmailThreads = ezgmail.search('"DO NOT DELETE"') assert len(gmailThreads) > 0 gmailMsg = None for gmailThread in gmailThreads: if gmailThread.messages[ 0].sender == 'Al Sweigart <*****@*****.**>': gmailMsg = gmailThread.messages[0] break assert gmailMsg is not None, 'The "DO NOT DELETE" test message must have been deleted.' # Check this email: assert gmailMsg.sender == DO_NOT_DELETE_SENDER assert gmailMsg.subject == 'DO NOT DELETE' #breakpoint() assert gmailMsg.body == 'This is the body.\r\n' assert gmailMsg.recipient == TEST_EMAIL_ADDRESS # TODO: The following timestamp is in the central timezone. assert gmailMsg.timestamp == datetime.datetime(2019, 6, 23, 21, 32, 41) assert 'attachment.txt' in gmailMsg.attachments assert 'attachment.jpg' in gmailMsg.attachments # Delete any existing attachment downloads from previous unit test runs: if os.path.exists('attachment.txt'): os.unlink('attachment.txt') if os.path.exists('attachment.jpg'): os.unlink('attachment.jpg') # Download attachments: gmailMsg.downloadAttachment('attachment.txt') assert os.path.exists('attachment.txt') assert os.path.getsize('attachment.txt') == 53 os.unlink('attachment.txt') gmailMsg.downloadAttachment('attachment.jpg') assert os.path.exists('attachment.jpg') assert os.path.getsize('attachment.jpg') == 56009 os.unlink('attachment.jpg') gmailMsg.downloadAllAttachments() assert os.path.exists('attachment.txt') assert os.path.getsize('attachment.txt') == 53 os.unlink('attachment.txt') assert os.path.exists('attachment.jpg') assert os.path.getsize('attachment.jpg') == 56009 os.unlink('attachment.jpg')
def attachment_downloads( year, tag="from:'*****@*****.**' label:unread has:attachment"): """ downloads our gmail attachments into a local directory :return: """ max_emails = 100 ezgmail.init() print(ezgmail.EMAIL_ADDRESS) print("Searching for ig statement attachments in", str(year), "unread") search_term = str(year) + " " + tag email_threads = ezgmail.search(search_term, maxResults=max_emails) # threads = ezgmail.search("2011 from:'*****@*****.**' has:attachment", maxResults=MAX_RESULTS) print(email_threads) print(len(email_threads)) print("iterating through all the threads") count = 1 for thread in email_threads: print("email thread", count, ":", thread) file = thread.messages for item in file: file = item.attachments # attachment_name = pprint.pprint(file) print("printing how the attachment reads", file) filename = file[0] item.downloadAttachment(filename, config.SETTINGS['local_tmp'], duplicateIndex=0) # MOVE ITEM INTO statements_folder move() count += 1 ezgmail.markAsRead(email_threads)
def getadjuk(): threads = ezgmail.search('subject:Rendszeres adományozás visszavonva (adjukössze.hu)') i = 0 while i < len(threads): messages = threads[i].messages n = 0 while n < len(messages): # Get the data of the email source = 'AdjukÖssze' sender = [threads[i].messages[n].sender] timestamp = [str(threads[i].messages[n].timestamp)] # Find relevant data from the body of the email customer_name = re.compile(r'támogatód (\(.*?\))').search(threads[i].messages[n].body).group().strip()[11:-1] customer_email = None profile_id = None profile_status = 'Canceled' amount_paid_each_time = re.compile(r'összeget \W.*\W').search( threads[i].messages[n].body).group().strip()[10:-5] billing_cycle = None last_payment_date = None last_payment_amount = None # Compile all relevant data to a list of lists msg.append( [source] + sender + timestamp + [customer_name] + [customer_email] + [profile_id] + [profile_status] + [amount_paid_each_time] + [billing_cycle] + [last_payment_date] + [last_payment_amount]) n += 1 i += 1
#Search import ezgmail resultThreads = ezgmail.search('RoboCop') len(resultThreads) ezgmail.summary(resultThreads) #Download import ezgmail threads = ezgmail.search('vacation photos') threads[0].messages[0].attachments threads[0].messages[0].downloadAttachment('tulips.jpg') threads[0].messages[0].downloadAllAttachments(downloadFolder='vacation2019')
r = frompart(part) if r: return r elif "body" in messageObj["payload"].keys(): r = frompart(messageObj["payload"]) return r def labelprocessed(msg): # msg.addLabel(lblTest) msg.addLabel(lblProcessed) ## Generic email to kidnle # - https://www.ben-evans.com/newsletter # - [email protected] text2kindle = g.search( f"after:{cutoff_date} AND (((from:[email protected]) OR (from:ben-evans.com)) AND NOT label:auto/processed)", maxResults=100) for t in reversed(text2kindle): for m in t.messages: print(f"Processing '{m.subject}' ...") labelprocessed(m) zp("t2e {m.subject} =(ec {m.originalBody})") ## ## substack = g.search( f"after:{cutoff_date} AND ((from:substack.com) AND NOT label:auto/processed)", maxResults=100) for t in reversed(substack):
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 13 17:52:32 2020 @author: tylerkim """ import ezgmail, os # prints list of unread emails unreadThreads = ezgmail.unread() # List of GmailThread objects. ezgmail.summary(unreadThreads) len(unreadThreads) # number of unread emails # Will probably use this more often recentThreads = ezgmail.recent(maxResults=100) len(recentThreads) for i in range(len(unreadThreads)): print('SUB: ' + unreadThreads[0].messages[0].subject) print('BODY: ' + unreadThreads[0].messages[0].body) firstEmail = ezgmail.search('subject:FIRST EMAIL')
# 읽지 않은 메일 확인하기 unread_threads = ezgmail.unread() # GmailThread 객체 리스트 반환 ezgmail.summary(unread_threads) # 메일 속성 접근하기 print(f"안 읽은 메일 갯수: {len(unread_threads)}") unread = unread_threads[0] print(f"GmailThread 문자열 값: {unread}") print(f"안 읽은 첫 번째 메일의 메시지 갯수: {len(unread.messages)}") print(f" 메시지 주제문: {unread.messages[0].subject}") print(f" 메시지 본문: {unread.messages[0].body}") print(f" 메시지 시간: {unread.messages[0].timestamp}") print(f" 메시지 보낸이: {unread.messages[0].sender}") print(f" 메시지 받는이: {unread.messages[0].recipient}") # 최근 받은 메일 확인 (기본 25) recent_threads = ezgmail.recent(maxResults=100) print(f"최근 받은 메일 갯수: {len(recent_threads)}") # 검색 기능 활용하기 result_threads = ezgmail.search("has:attachment") print(f"첨부 파일이 있는 메일:") ezgmail.summary(result_threads) # 첨부 파일 다운로드 thread = result_threads[0] print(f"첨부 파일: {thread.messages[0].attachments}") thread.messages[0].downloadAttachment("attachment.txt") # 첨부파일 하나 다운로드 thread.messages[0].downloadAllAttachments( downloadFolder="attach") # 첨부파일 모두 다운로드
import ezgmail resultThreads = ezgmail.search('RoboCop') print(len(resultThreads)) print(ezgmail.summary(resultThreads))
import ezgmail threads = ezgmail.search('pictures') print(threads[0].messages[0].attachments) print(threads[0].messages[0].downloadAttachment('tulips.jpg')) threads[0].messages[0].downloadAllAttachments(downloadFolder='vacation2019')
def _search_emails(self, subject): search_query = self.INBOX_SEARCH + subject res_threat = ezgmail.search(search_query) # print(ezgmail.summary(res_threat, printInfo=False)) return res_threat
#create repository if not os.path.isdir(main_repo): os.makedirs(main_repo) os.chdir(main_repo) if not os.path.isdir(main_repo + "/" + today): os.makedirs(main_repo + "/" + today) #navigate to emails #addres: [email protected] #password: dickbutt2 os.chdir(project_location) ezgmail.init() print('Access Granted, reading emails:', '\r\n', '\r\n') #parse emails/download attachments threads = ezgmail.search('heyyy') #print(threads[0]) ezgmail.summary(threads) print(threads[0].messages[0].attachments) threads[0].messages[0].downloadAllAttachments(downloadFolder=main_repo + '/' + today) #['tulips.jpg', 'canal.jpg', 'bicycles.jpg'] #threads[0].messages[0].downloadAttachment('tulips.jpg') #threads[0].messages[0].downloadAllAttachments(downloadFolder='vacation2019')
resulthreads[i].messages[j].downloadAllAttachments( ) # downloads attachment(s) for individual messages else: # downloads attachment(s) for single message resulthreads[i].messages[0].downloadAllAttachments() print("Download compelete. Please check your root directory.") except: raise Exception("Error occured while downloading attachment(s).") if __name__ == '__main__': query = input("Enter search query: ") # appending to make sure the result threads always has an attachment newquery = query + " + has:attachment" # search functions accepts all the operators described at https://support.google.com/mail/answer/7190?hl=en resulthreads = ezgmail.search(newquery) if len(resulthreads) == 0: # Executed if results don't have attachment print("Result has no attachments:") else: print("Result(s) with attachments:") for threads in resulthreads: # prints the subject line of email thread in results print(f"Email Subject: {threads.messages[0].subject}") try: ask = input( "Do you want to download attachment(s) in result(s) (Yes/No)? " ) # Allows user to decide whether they want to download attachment(s) or not if ask == "Yes": # calls the function that downloads attachment(s)
logging.basicConfig( filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' ) ezgmail.init() # This is where the program resides program = 'C:\\Program Files\\qBittorrent\\qbittorrent.exe' # This searches your email account for unread emails that have a particular # code, in this case YHAFMARQS47620 (I do not actually use this code anywhere # so I wouldn't try anything immoral! :P) # This is so that we know the emails have the intent of setting up a download resultThreads = ezgmail.search( 'YHAFMARQS47620 AND from:[email protected] AND label:UNREAD' ) # Get the current date now = str(datetime.datetime.now()) # I fancied logging the amount of threads returned logging.debug('Search results retrieved at ' + now + '. Returned ' + str(len(resultThreads)) + ' results.') # Loop through list of threads obtained for i in range(0, len(resultThreads)): # Get the body of a message and split it in a list based on carriage returns emailstring = str(resultThreads[i].messages[0].body) logging.debug('Body of email returned: ' + emailstring)
def mailFinder(self): mail = ezgmail.search( self.subjectLine ) # Collects emails that have a certain subject line return mail
for j in range(len(resulthreads[i].messages)): resulthreads[i].messages[j].downloadAllAttachments( ) # downloads attachment(s) for individual messages else: resulthreads[i].messages[0].downloadAllAttachments( ) # downloads attachment(s) for single message print("Download compelete. Please check your root directory.") except: raise Exception("Error occured while downloading attachment(s).") if __name__ == '__main__': query = input("Enter search query: ") newquery = query + " + has:attachment" # appending to make sure the result threads always has an attachment resulthreads = ezgmail.search( newquery ) # search functions accepts all the operators described at https://support.google.com/mail/answer/7190?hl=en if len(resulthreads) == 0: print("Result has no attachments:" ) # Executed if results don't have attachment else: print("Result(s) with attachments:") for threads in resulthreads: print(f"Email Subject: {threads.messages[0].subject}" ) # prints the subject line of email thread in results try: ask = input( "Do you want to download attachment(s) in result(s) (Yes/No)? " ) # Allows user to decide whether they want to download attachment(s) or not if ask == "Yes":