def mail_summary(): #print(parameters.get('Body')) main() ezgmail.init() unreadThreads = ezgmail.unread(maxResults=5) print(unreadThreads) return unreadThreads
def report(): # need to flesh out layout = [ [sg.CalendarButton("from date", key="from")], [sg.CalendarButton("to date", key="to")], [sg.Cancel("Cancel"), sg.Submit("Submit")], ] window = sg.Window("Select Dates", layout, resizable=True) event, values = window.read() from_date = values["from"] to_date = values["to"] window.close() if not (from_date and to_date): sys.exit() else: from_date = values["from"].strftime("%Y-%m-%d") to_date = values["to"].strftime("%Y-%m-%d") results = Shipment.fetch_all_records_in_date(from_date, to_date) ezgmail.init() ezgmail.send("*****@*****.**", "Shipping Unit Program!", str(results[0]))
def init_ezgmail(): print("Initialing email connection...") # Path to the gmail account API JSON file os.chdir(r'C:\YOLOv5\yolov5\Email Automation\Credentials') # Initialize the mail client with JSON credentials ezgmail.init() logging.info("Succesfully initializing email connection.") print("Succesfully initializing email connection.")
def relay_email(wa_client): s3 = boto3.client('s3') ezgmail.init(userId='*****@*****.**') subject, body = wa_client.get_email_body() if subject is not None and body is not None: for email in email_recipients.keys(): print(f'Sending {len(body)} chars to {email}') ezgmail.send(email, subject, MIMEText(body, 'html', 'utf-8')) return True
def send_test_email(): s3 = boto3.client('s3') ezgmail.init(userId='*****@*****.**') print(f'Ezgmail initialized for {ezgmail.EMAIL_ADDRESS}') ezgmail.send( '*****@*****.**', 'Hello from AARC', 'Pop, pop, popsicle, Ice, ice, icecycle, Test, test, testing one two three' ) return True
def send_mail(parameters): main() ezgmail.init() print(parameters) toEmail=parameters['email'] subject=parameters['sub_email'] body=parameters['body_email'] print(toEmail,subject,body,sep=" ") ezgmail.send(toEmail,subject,body)
def __init__(self, sendQueue, recieveQueue, config): ezgmail.init() self.service = 1 self.thread = QtCore.QThread() self.thread.name = "auto_refresh" self.worker = emailThread(self.service, sendQueue, recieveQueue, config) self.worker.moveToThread(self.thread) self.worker.start()
def _sendPlotsByEmail(subReport): fileNames = [] pngFiles = glob.glob('*.png') for prodName in subReport['prodNames']: fileName = prodName.replace(" ", "") + '.png' if (fileName in pngFiles): fileNames.append(fileName) ezgmail.init() ezgmail.send( subReport['email'], 'PriceMonitor Relatorio', 'Olá {}, segue por anexo seu relatório do PriceMonitor.'.format( subReport['username']), fileNames) print("Email enviado!")
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 wiki_file(content): # write content of wikipedia page to a file with open('test_wiki.txt', 'w') as f: for i in content: f.writelines(i) print('\n') # send an email with attached file # initiate ezgmail ezgmail.init() # ask for credentials from user email = input( 'Input the email you will like to have a copy of the document sent to.' ) subject = input('Input a subject line') message = input('Input a message...press enter to continue when done.') text_doc = 'test_wiki.txt' ezgmail.send(email, subject, 'Here is a copy of your wikipedia article!', [text_doc])
def email(): ezgmail.init() DAYS_AHEAD=1 start_date = datetime.now().date() + timedelta(days=DAYS_AHEAD) end_date = (datetime.now().date() + timedelta(days=DAYS_AHEAD)) # downloading the earnings calendar yec = YahooEarningsCalendar() earnings_list = yec.earnings_between(start_date, end_date) print(earnings_list) # saving the data in a pandas DataFrame earnings_df = pd.DataFrame(earnings_list) print(earnings_df["startdatetime"]) earnings_df["startdatetime"]= earnings_df['startdatetime'].astype(str).str[:-14] earnings_df["Link"]="https://finance.yahoo.com/quote/{}".format(earnings_df["ticker"]) for index, x in enumerate(earnings_df["ticker"]): earnings_df["Link"][index]="https://finance.yahoo.com/quote/{}".format(x) print(earnings_df["startdatetime"]) print(earnings_df) earnings_df.to_csv( r"C:\Users\MIKEB\Desktop\Python\Fuhnance\Earnings_For_{}.csv".format(start_date)) e,g,l=generate_dfs(10) msg="Top Gainers Today:\n\n" for index,x in enumerate(g["Symbol"]): try: line=f"{x} | {g['Name'][index]} | {g['% Change'][index]}% | https://finance.yahoo.com/quote/{x}\n\n" msg=msg+line except: pass print(msg) msg=msg+"\n\nTop Losers Today:\n\n" for index,x in enumerate(l["Symbol"]): try: line=f"{x} | {l['Name'][index]} | {l['% Change'][index]}% | https://finance.yahoo.com/quote/{x}\n\n" msg=msg+line except: pass msg=msg+"\n\nEarnings Action Today:\n\n" for index,x in enumerate(e["ticker"]): line=f"{x} | {e['companyshortname'][index]} | {e['startdatetimetype'][index]} | {round(e['% Change'][index],2)}% | https://finance.yahoo.com/quote/{x}\n\n" msg=msg+line print(msg) #for x in ["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"]: for x in ["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"]: ezgmail.send(x,"Gainers, Losers, and Earnings {}".format(start_date),msg,r"C:\Users\MIKEB\Desktop\Python\Fuhnance\Earnings_For_{}.csv".format(start_date))
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 test_init(): # Test the basic set up with token.json and credentials.json: ezgmail.init() # Test with nonexistant token file: #with pytest.raises(ezgmail.EZGmailException): # ezgmail.init(tokenFile='DOES_NOT_EXIST.json', credentialsFile='credentials.json') # Test with nonexistant credential file: if not os.path.exists('token-custom.json'): shutil.copy('token.json', 'token-custom.json') with pytest.raises(ezgmail.EZGmailException): #ezgmail.init(tokenFile='token-custom.json', credentialsFile='DOES_NOT_EXIST.json') ezgmail.init(credentialsFile='DOES_NOT_EXIST.json') # Test that exceptions aren't raised when _raiseException is False: #ezgmail.init(tokenFile='DOES_NOT_EXIST.json', credentialsFile='credentials.json', _raiseException=False) # Test the basic set up with custom names: if not os.path.exists('credentials-custom.json'): shutil.copy('credentials.json', 'credentials-custom.json') ezgmail.init(tokenFile='token-custom.json', credentialsFile='credentials-custom.json') assert ezgmail.EMAIL_ADDRESS == TEST_EMAIL_ADDRESS assert ezgmail.LOGGED_IN == True
def do_authentication_gmail(emailaddress=f"{USERNAME}@{EMAILADDR}"): """ Check authentication for email address Parameters ---------- emailladdress: str, optional Email to check login for. """ if ezgmail.init() == emailaddress: return True else: return False
def initialise_email(): # os.chdir(os.path.normpath(os.getcwd() + os.sep + os.pardir)) ezgmail.init()
import ezgmail from pdf2image import convert_from_path from pdf2image.exceptions import ( PDFInfoNotInstalledError, PDFPageCountError, PDFSyntaxError, ) import random from fpdf import FPDF ezgmail.init() Threads = ezgmail.unread() lookAt = len(Threads) count = 0 leonard_responses = [ "Spent more money again huh :/", "Leonard the bot says meow. You spend too much. Meow.", "MEOW MEOW MEOW MEOW MEOW MEOW MEOW ", "If Leonard could talk he'd say he's disappointed in you >:(", "silence", "money doesn't grow on trees!!", "do you have a job? then why you spend money!!! >:(", ] leonardSays = random.choice(leonard_responses)
def log_into_email(self): os.chdir(self.path) ezgmail.init()
emails = emails.email_list chores = ['dishes', 'walk_dog', 'cleaning', 'laundry'] subject = 'Chore assignment' msgBody = 'Hello,\n\nYou have been assigned the following chore via ChoreAssigner.py:\n' print('\nEmail addresses:') for email in emails: print('- ' + email) print('\nChores:') for chore in chores: print('- ' + chore) print('\nAttempting to log into gmail API...') os.chdir(FILEPATH) try: initialize = ezgmail.init() print('Login successful!') except Exception as e: print('ERROR! Unable to log into gmail API.\nError Message: {}'.format(e)) try: print('\nDelegating tasks...') # print('\n\nemail list TEST') # for email in emails: # print('- ' + email) for email in emails: randomChoice = random.choice(chores) print('Sending email to {} for the following task: {}'.format( email, randomChoice)) ezgmail.send(email, subject, msgBody + randomChoice) chores.remove(randomChoice)
def main(): correct_content = False correct_attachment = False attachment = [] client_list = open("../client_list.csv") dict_reader = csv.DictReader(client_list) os.chdir("../content") while not correct_content: filename = input( "Please select the content file that you wish to send: ") try: fd = open(filename, "r") correct_content = True except: print("file does not exist please try again") correct_content = False os.chdir("../attachments") total_size = 0 while not correct_attachment: usr_input = input( "Please select the attachment files that you wish to send: ") filename = "../attachments/" + usr_input if usr_input == '': correct_attachment = True else: try: print("file selected is", Path(filename).stat()) total_size = total_size + Path(filename).stat().st_size if total_size > 20480000: print("File size exceeds 20mb, please choose another file") correct_attachment = False else: attachment.append(filename) correct_attachment = True except: print( "File does not exist!, please choose another attachment!") choice = input( "Is there another attachment that you want to select?(Y/n): ") if evaluate(choice): correct_attachment = False else: correct_attachment = True os.chdir("../credentials") print("Loading account info please wait.....") try: ezgmail.init() except: print( "Unable to initialize account, please check your credentials.json") exit(-1) print("Account is loaded!") title = input("Please type in the title of email: ") data = fd.read() for row in dict_reader: if not len(attachment): ezgmail.send(row["Email"], title, data) else: ezgmail.send(row["Email"], title, data, attachment) print("Email to", row["ClientName"], "sent!") usr_input = input( "ALl email sent, do you want to send another one?(Y/n): ") if evaluate(usr_input): main() else: print("exiting script now, have a nice day :)") fd.close()
def __init__(self): ezgmail.init()
logger.debug(f'Sleeping for {sleep_secs} seconds') time.sleep(sleep_secs) torrent.stop() if __name__ == '__main__': # noinspection PyBroadException try: check_args = True show = sys.argv[ 1] if check_args else 'sword-art-online-alicization-war-of-underworld' logger.debug(f'Getting new episodes for {show}') elements = get_horrible_sub_elements(show) ezgmail.init(tokenFile=os.environ.get('GMAIL_TOKEN', 'token.json'), credentialsFile=os.environ.get('GMAIL_CREDENTIALS', 'credentials.json')) try: tor_client = trpc.Client( port=os.environ['TRANSMISSION_PORT'], username=os.environ['TRANSMISSION_USERNAME'], password=os.environ['TRANSMISSION_PASSWORD']) except KeyError: logger.exception('Environment variables not set correctly') sys.exit(1) torrent_ids = add_torrents(show, elements, tor_client) logger.debug(f'Torrent ids - {torrent_ids}') wait_for_download(torrent_ids, tor_client) except Exception:
def action(self, spoken_text, arguments_list: list = []): # Set the input queue of the speech object to the arguments list if it # exists. This will ensure that all hear & approve commands in this # feature will get input from the arguments list in order instead of # asking the user for input. Hence, the arguments list provided should # have as many items as there are hear & approve commands in this # feature. if (len(arguments_list) > 0): self.bs.set_input_queue(arguments_list) recipient = self.get_recipient(spoken_text) if not recipient: recipient = self.bs.ask_question( 'Who do you want to send the email to?') if not recipient: return close_names = [] known_contacts = self.get_contact_names() while close_names == []: close_names = difflib.get_close_matches(recipient, known_contacts) if close_names == []: recipient = self.bs.ask_question( """Could not find this contact. Please try again (say 'stop' or 'cancel' to exit.""" ) if not recipient: return try: recipient_email = self.get_email(close_names[0]) except Exception as e: print(e) self.bs.respond( """An error occured. I will stop trying to send an email now.""" ) return # get subject subject = self.bs.ask_question('What is the subject of your email?') if not subject: return # get message message = self.bs.ask_question('What is the message of your email?') if not message: return # show summary email self.bs.respond('Here is a summary of your email:') print(self.summary_email(recipient_email, subject, message)) # edit email if self.bs.approve("Would you like to edit this?"): edited_email = self.term_email_edit( recipient_email, subject, message) edited_email_json = json.loads(edited_email) recipient_email = edited_email_json["recipient_email"] subject = edited_email_json["subject"] message = edited_email_json["message"] self.bs.respond('Here is another summary of your email:') print(self.summary_email(recipient_email, subject, message)) if self.bs.approve("Would you like to send this email?"): # send email ezgmail.init( tokenFile=self.gmail_creds_folder+'token.json', credentialsFile=self.gmail_creds_folder+'credentials.json' ) message += "\n\n Bumblebee (Zintan's ai assistant)" ezgmail.send(recipient_email, subject, message) self.bs.respond('I have sent the email.') else: self.bs.respond('Okay.') return
import ezgmail, os, smtplib gmail_user = * gmail_pass = * to_address = * from_address = * ezgmail.init(tokenFile='/home/admin/Projects/Movie-Recording-Reminder/token.json', credentialsFile='/home/admin/Projects/Movie-Recording-Reminder/credentials.json') try: smtpObj=smtplib.SMTP('smtp.gmail.com',587) smtpObj.ehlo() smtpObj.starttls() except: print('something went wrong') smtpObj.login(gmail_user, gmail_pass)
from syncer import sync tsend = sync(ts.tsend) # zsh = local["zsh"]["-c"] lblProcessed = "Label_7772537585229918833" lblTest = "Label_4305264623189976109" def ecerr(str): print(f"{now} {str}", file=sys.stderr) tokenpath = local.env["HOME"] + "/.gmail.token" credpath = local.env["HOME"] + "/.gmail.credentials.json" import ezgmail as g # @todo1 send notif if this needs auth g.init(tokenFile=tokenpath, credentialsFile=credpath) service = g.SERVICE_GMAIL def printLabels(): results = service.users().labels().list(userId="me").execute() labels = results.get("labels", []) if not labels: print("No labels found.") else: print("Labels:") for label in labels: print(label["name"] + " " + label["id"]) def parseContentTypeHeaderForEncoding(value): """Helper function called by GmailMessage:__init__()."""