def _ready_message_with_attachments(self, msg, attachments): """ Converts attachment filepaths to MIME objects and adds them to the msg. Args: msg (MIMEMultipart): The message to add attachments to. attachments (List[str]): A list of attachment file paths. """ for filepath in attachments: content_type, encoding = mimetypes.guess_type(filepath) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) with open(filepath, 'rb') as file: raw_data = file.read() attm = (MIMEText(raw_data.decode("utf-8"), _subtype=sub_type) if main_type == 'text' else MIMEImage(raw_data, _subtype=sub_type) if main_type == 'image' else MIMEAudio(raw_data, _subtype=sub_type) if main_type == 'audio' else None) if not attm: attm = MIMEBase(main_type, sub_type) attm.set_payload(file.read()) filename = os.path.basename(filepath) attm.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attm)
def get_message(arg): if os.path.isfile(arg): with open(arg, 'r') as file: message = file.read() elif os.path.isfile(os.path.dirname(os.path.abspath(__file__)) + "/" + arg): with open(os.path.dirname(os.path.abspath(__file__)) + "/" + arg, 'r') as file: message = file.read() else: message = arg return message
def drive_ignore(unttrack_file, l): cwd = os.getcwd() drive_ignore_path = os.path.join(cwd, '.driveignore') if(len(unttrack_file) != 0): try: file = open(drive_ignore_path, 'r') files = file.readlines() file.close() except: files = [] file = open(drive_ignore_path, 'a+') for f in unttrack_file: f = f + "\n" file_path = os.path.join(cwd, f[:-1]) if os.path.exists(file_path): if not (f in files): file.write(f) else: click.secho(f[:-1] + " doesn't exist in " + cwd, fg="red") file.close() if l: click.secho("listing untracked files....", fg="magenta") utils.save_history([{"-l": ["True"]}, " ", cwd]) if os.path.isfile(drive_ignore_path): file = open(drive_ignore_path, 'r') untracked_files = file.read() click.secho(untracked_files) file.close() else: click.secho(".driveignore file doesn't exist in " + cwd, fg="red") sys.exit(0) else: utils.save_history([{"-l": [None]}, " ", cwd])
def main(): with open('message.html', 'r') as file: template = file.read() data = get_sheets_data(SHEETS) email_sent = [[PURPOSE]] num_sent = 0 for person in data: message_body = template for item in person: search_str = '{{' + item + '}}' message_body = message_body.replace(search_str, str(person[item])) work = send_message( GMAIL, 'me', create_message(SENDER, person['Email'], SUBJECT, message_body)) email_sent.append([str(work)]) num_sent = +1 if num_sent % SLEEP_TIME == 0: time.sleep(BATCH_AMT) last_column = colnum_string(len(data[0]) + 1) range_ = last_column + ':' + last_column body = {'range': range_, 'majorDimension': 'ROWS', 'values': email_sent} #SHEETS.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID) SHEETS.spreadsheets().values().update(spreadsheetId=SHEETS_FILE_ID, range=range_, valueInputOption='RAW', body=body).execute()
def create_message_with_attachment( recipients, subject, message_text, files): # deal with the message body message = MIMEMultipart() message['to'] = ','.join(recipients) message['from'] = '*****@*****.**' message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) # deal with the attachment/files for file in files: filename = file.name content_type = file.content_type encoding = file.charset if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) msg = MIMEBase(main_type, sub_type) msg.set_payload(file.read()) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) b64_bytes = base64.urlsafe_b64encode(message.as_bytes()) b64_string = b64_bytes.decode() service = initialise_gmail() b = BytesIO() b.write(b64_bytes) media_body = googleapiclient.http.MediaIoBaseUpload(b, mimetype='message/rfc822') message =(service.users().messages().insert(userId='me', media_body=media_body).execute()) print( 'Message Id: %s' % message['id']) return message
def schema_checker(google_file): if google_file: fn = ("%s.csv" % os.path.splitext(files[0]["name"].replace(" ", "_"))[0] ) # rename file with underscores print('Exporting "%s" as "%s"... ' % (files[0]["name"], fn), end="") data = DRIVE.files().export(fileId=files[0]["id"], mimeType=DST_MIMETYPE).execute() if data: with open(fn, "wb") as f: f.write(data) print("DONE") # done exporting as csv file with open(fn, 'a') as f: f.write( 'a' ) # Hone conversion cuts off a letter at the end, so append a letter to be delted. Hone = hone.Hone( ) # convert csv file to nested json format, result is a list schema = Hone.get_schema(fn) result = Hone.convert(fn) splitting_dict(result) # since result is a list, iterate validation over each item: number = 0 for data in split_dict_list: number += 1 del data[ 'Timestamp'] # Google Forms automatically creates this column, but we don't want it user_email = data.pop( 'email') # we don't want to store this in the database data['_id'] = uuid.uuid4() sample_information = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) with open("materials.json", "r") as file: loaded_schema = file.read() validation_schema = ast.literal_eval(loaded_schema) try: validate(data, validation_schema) print( 'Sample %s validation complete!' % number ) # prints only if no error occurs during validation step doc_id = coll.insert_one( data ).inserted_id # insert validated schema into MongoDB print('The ID for this document is: ', doc_id) clear_spreadsheet( FILEID ) # spreadsheet is only cleared if doc SUCCESSFULLY uploads to MongoDB send_email(user_email, body_valid, sample_information) except Exception as e: validation_error = 'Error: ' + str(e) send_email(user_email, body_invalid, sample_information, validation_error) else: print("ERROR: could not download file") else: print("ERROR: file not found")
def main(arguments): args, options, parser = get_options(arguments) if options.description_file is not None and os.path.exists( options.description_file): with open(options.description_file, encoding="utf-8") as file: options.description = file.read() try: run_main(parser, options, args) except googleapiclient.errors.HttpError as error: response = bytes.decode(error.content, encoding=lib.get_encoding()).strip() raise RequestError(u"Server response: {0}".format(response))
def getEmailStr(self, person): if self.template: with open(self.template) as file: text = file.read() self.emailStr = text.replace( '{company}', person['Company']).replace( '{recipientFirst}', person["Name"].split(' ')[0]).replace( '{first}', self.info["first"]).replace( '{last}', self.info["last"]).replace( '{recipientLast}', person["Name"].split(' ')[-1]).replace( '{title}', person["Title"]).replace( "{website}", person["Site"]) else: raise ValueError('Couldn\'t find email template')
def download_file_and_send_encoded(service, file_id): try: path_download, _ = downoad_file_and_store(service, file_id) if type(path_download) == str and path_download != "": file = open(path_download, 'rb') file_data = file.read() encoded_data = base64.encodestring(file_data) # decoded_data = base64.decodestring(encoded_data) # file_data2= open(path_upload, 'wb') # file_data2.write(decoded_data) return encoded_data.decode('utf-8') else: return -3 except Exception as e: print(e) return -3
def createMessage(self, subject, body, mime, attach_file): msg = MIMEMultipart() msg["From"] = self.from_addr msg["To"] = self.to_addr msg["Date"] = formatdate() msg["Subject"] = subject body = MIMEText(body) msg.attach(body) #for attach file if mime != None and attach_file != None: attachment = MIMEBase(mime['type'], mime['subtype']) file = open(attach_file['path']) attachment.set_payload(file.read()) file.close() Encoders.encode_base64(attachment) msg.attach(attachment) attachment.add_header("Content-Disposition", "attachment", filename=attach_file['name']) return msg
def schema_checker(google_file): if google_file: fn = ("%s.csv" % os.path.splitext(files[0]["name"].replace(" ", "_"))[0] ) # rename file with underscores print('Exporting "%s" as "%s"... ' % (files[0]["name"], fn), end="") data = DRIVE.files().export(fileId=files[0]["id"], mimeType=DST_MIMETYPE).execute() if data: with open(fn, "wb") as f: f.write(data) print("DONE") # done exporting as csv file Hone = hone.Hone( ) # convert csv file to nested json format, result is a list schema = Hone.get_schema(fn) result = Hone.convert(fn) splitting_dict(result) # since result is a list, iterate validation over each item: number = 0 for data in split_dict_list: number += 1 with open("materials.json", "r") as file: loaded_schema = file.read() validation_schema = ast.literal_eval(loaded_schema) validate(data, validation_schema) print( 'Sample %s validation complete!' % number ) # prints only if no error occurs during validation step doc_id = coll.insert_one( data).inserted_id # insert validated schema into MongoDB print('The ID for this document is: ', doc_id) clear_spreadsheet( FILEID ) # spreadsheet is only cleared if doc SUCCESSFULLY uploads to MongoDB else: print("ERROR: could not download file") else: print("ERROR: file not found")
def loadfileasattach(filenm=None, toadd=None, fradd=None, subj=None): #should return something sendable thru mime if filenm is None: makeattr() filenm = 'test.xls' file = open(filenm, 'rb') ament = mime.multipart.MIMEMultipart() ament['to'] = toadd ament['from'] = fradd ament['subject'] = subj msg = mime.base.MIMEBase('test', 'octet-base') msg.set_payload(file.read()) file.close() # filename = os.path.basename(file) msg.add_header('Content-Disposition', 'attachment', filename=filenm) ament.attach(msg) # ament.attach(msg) return {'raw': base64.urlsafe_b64encode(ament.as_bytes()).decode()}
def main(arguments): """Upload videos to Youtube.""" usage = """Usage: %prog [OPTIONS] VIDEO [VIDEO2 ...] Upload videos to Youtube.""" parser = optparse.OptionParser(usage) # Video metadata parser.add_option('-t', '--title', dest='title', type="string", help='Video title') parser.add_option('-c', '--category', dest='category', type="string", help='Name of video category') parser.add_option('-d', '--description', dest='description', type="string", help='Video description') parser.add_option('', '--description-file', dest='description_file', type="string", help='Video description file', default=None) parser.add_option('', '--tags', dest='tags', type="string", help='Video tags (separated by commas: "tag1, tag2,...")') parser.add_option('', '--privacy', dest='privacy', metavar="STRING", default="public", help='Privacy status (public | unlisted | private)') parser.add_option('', '--publish-at', dest='publish_at', metavar="datetime", default=None, help='Publish date (ISO 8601): YYYY-MM-DDThh:mm:ss.sZ') parser.add_option('', '--license', dest='license', metavar="string", choices=('youtube', 'creativeCommon'), default='youtube', help='License for the video, either "youtube" (the default) or "creativeCommon"') parser.add_option('', '--location', dest='location', type="string", default=None, metavar="latitude=VAL,longitude=VAL[,altitude=VAL]", help='Video location"') parser.add_option('', '--recording-date', dest='recording_date', metavar="datetime", default=None, help="Recording date (ISO 8601): YYYY-MM-DDThh:mm:ss.sZ") parser.add_option('', '--default-language', dest='default_language', type="string", default=None, metavar="string", help="Default language (ISO 639-1: en | fr | de | ...)") parser.add_option('', '--default-audio-language', dest='default_audio_language', type="string", default=None, metavar="string", help="Default audio language (ISO 639-1: en | fr | de | ...)") parser.add_option('', '--thumbnail', dest='thumb', type="string", metavar="FILE", help='Image file to use as video thumbnail (JPEG or PNG)') parser.add_option('', '--playlist', dest='playlist', type="string", help='Playlist title (if it does not exist, it will be created)') parser.add_option('', '--title-template', dest='title_template', type="string", default="{title} [{n}/{total}]", metavar="string", help='Template for multiple videos (default: {title} [{n}/{total}])') parser.add_option('', '--embeddable', dest='embeddable', default=True, help='Video is embeddable') # Authentication parser.add_option('', '--client-secrets', dest='client_secrets', type="string", help='Client secrets JSON file') parser.add_option('', '--credentials-file', dest='credentials_file', type="string", help='Credentials JSON file') parser.add_option('', '--auth-browser', dest='auth_browser', action='store_true', help='Open a GUI browser to authenticate if required') # Additional options parser.add_option('', '--chunksize', dest='chunksize', type="int", default=1024 * 1024 * 8, help='Update file chunksize') parser.add_option('', '--open-link', dest='open_link', action='store_true', help='Opens a url in a web browser to display the uploaded video') options, args = parser.parse_args(arguments) if options.description_file is not None and os.path.exists(options.description_file): with open(options.description_file, encoding="utf-8") as file: options.description = file.read() try: run_main(parser, options, args) except googleapiclient.errors.HttpError as error: response = bytes.decode(error.content, encoding=lib.get_encoding()).strip() raise RequestError(u"Server response: {0}".format(response))
def getMessageHTML(): file = open("templates/test_email.html", "r") messageHTML = file.read() file.close() return messageHTML
import discord, asyncio, time from discord.ext import commands # Setup the Sheets API SCOPES = 'https://www.googleapis.com/auth/spreadsheets' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) print('Connected to Google Sheets') # Get sheet ID file = open('SHID.txt', 'r') SH_ID = file.read() print('Opened SH_ID') command_prefix = '!' bot = commands.Bot(command_prefix) @bot.command() async def addTime(ctx, a: str): date = ctx.message.created_at date = str(date.month) + '/' + str(date.day) + '/' + str(date.year) await ctx.send(ctx.message.created_at) result = service.spreadsheets().values().get(spreadsheetId=SH_ID, range='A2').execute() values = result.get('values', [])
quote_file = "quotes.txt" f = open(quote_file, 'r', encoding='cp1252') txt = f.read() lines = txt.split('\n.\n') quote = random.choice(lines) print(quote) #writing to txt output = open("output.txt", "a") output.writelines(list) time.sleep(30) output.close() # writing to img (news) file = open('output.txt', mode='r') message = file.read() time.sleep(10) color = 'rgb(255, 255, 255)' # black color draw.text((x, y), message, fill=color, font=font) file = open('output.txt', mode='r') message = file.read() time.sleep(10) # Quote font1 = ImageFont.truetype('arial.ttf', size=35) draw.text((50, 500), quote, fill=color, font=font1) # save the edited image image.save('wallpaper.png') # wallpaper ctypes.windll.user32.SystemParametersInfoW( 20, 0, "D:\Python\Wallpaper_Engine\Windows\wallpaper.png", 0)
file = open("last_message.txt", "w") file.write(content_subject) file.close() if __name__ == '__main__': list_messages = ListMessagesWithLabels(service, 'me', 'Label_26') id_last_message = list_messages[0]['id'] current_message = GetMessage(service, 'me', id_last_message) # help python can read special string encode utf8 japanese letter reload(sys) sys.setdefaultencoding('utf-8') current_subject = str(current_message['payload']['headers'][38]['value']) # write the first subject message to compare with after check # file = open("last_message.txt", "w") # file.write(current_subject) file = open("last_message.txt", "r") before_subject = file.read() # # print "The lasest subject %s" % before_subject file.close() if os.stat("last_message.txt").st_size == 0: print "Please give subject to last_message.txt file" else: if current_subject == before_subject: print "We don't have new message" else: print "WARING...WE HAVE NEW MESSAGE IN RKT PROJECT" update_subject_content(current_subject) # https://developers.google.com/gmail/api/v1/reference/users/messages
imapconn.select(ALL_MAIL) # read/write! current = 0 # Recursively find all messages from specified folder. for root, dirs, filenames in os.walk(options.eml_folder): for filename in filenames: if fnmatch.fnmatch(filename, '*.eml'): restart_line() current += 1 sys.stdout.write("Importing EML message #%s at location '%s'." % (current, os.path.join(root, filename))) sys.stdout.flush() try: with open(os.path.join(root, filename), 'rb') as file: full_message = file.read() file.seek(0) message = email.message_from_file(file) except IOError: print 'Error: Error opening file.' continue except email.errors.MessageError: print 'Error: Problem parsing the message in the file.' continue try: # Use the original send date. message_datestring = message['Date'] except: print "Error: Couldn't find date in message." continue