def mail_log(): '''发送系统报告邮件''' message, has_warn = core.gen_sys_info() if has_warn: subject = f'{date2str(now())}【{host_name}】系统报告【警告】' else: subject = f'{date2str(now())}【{host_name}】系统报告' core.send_email(subject, message) print(f'[{time2str(now())}]发送系统报告')
def run(self): """ 主程序入口 :return: """ try: # 登陆 self.login() # 获取人名 while True: self.get_name_to_search() except Exception as e: C.send_email("normal_account_company spider ERROR", e, log)
def action(payload: ActionRequest): """Dummy Endpoint for demonstration purposes.""" sdk = get_sdk_for_schedule(payload.scheduled_plan.scheduled_plan_id) plan = sdk.scheduled_plan(payload.scheduled_plan.scheduled_plan_id) look = sdk.look(plan.look_id) image = sdk.run_look(plan.look_id, 'png') description = look.description image_file = get_temp_file_name(slug, '.'.join(['look', str(look.id), 'png'])) with open(image_file, 'wb') as file: file.write(image) document = Document() document.add_heading('Exported Look', 0) p = document.add_paragraph(description) document.add_picture(image_file, width=Inches(4.50)) file_name = get_output_file_name(slug, '.'.join(['look', str(look.id), 'docx']), timestamp=True) document.save(file_name) response = send_email(to_emails=payload.form_params['email_address'], subject=payload.form_params['email_subject'], body=payload.form_params['email_body'], file_name=file_name, file_type='docx') return {'response': 'response'}
def mail_backup(path: str): file_list = core.sort_file_list(path) file_info, group_list = core.group_file_by_size( file_list, 50331648, 1048576 ) j = len(group_list) # 发送附件清单 message = core.gen_file_info(file_info) subject = f'{date2str(now())}【{host_name}】附件清单【共{j}包】' core.send_email(subject, message) print(f'[{time2str(now())}]发送附件清单') # 发送每个附件包 for i, group in enumerate(group_list, 1): subject = f'{date2str(now())}【{host_name}】附件包【第{i}/{j}包】' message = core.gen_pack_info(group) file_pack = core.pack_file(file_info, group) core.send_email(subject, message, file_pack) print(f'[{time2str(now())}]发送附件包【{i}/{j}】')
def tz_on_mail(keyword=None): if not keyword: keyword = input('Enter key phrase: ') links = google_scraper(keyword) texts = dict() for link in links: texts[link] = get_text(link) top3 = list(texts.values())[:3] keywords_main = texts_analyzer(texts.values()) keywords_secondary = texts_analyzer(top3) keywords_secondary.difference_update(keywords_main) task_text = COPYWRITER_TASK.format( keywords_main='\n'.join(keywords_main), keywords_secondary='\n'.join(keywords_secondary), title=keyword.upper()) send_email(task_text, "*****@*****.**")
def action(payload: ActionRequest): """Endpoint for the Tabbed Spreadsheet action: converts the zipped csv file of data into a multi-tabbed Excel spreadsheet.""" attachment_binary = payload.attachment.data.encode('utf-8') attachment_binary = base64.decodestring(attachment_binary) attachment_file = get_temp_file_name(slug, 'csv_files.zip') with open(attachment_file, 'wb') as file: file.write(attachment_binary) csv_files = [] temp_dir = get_temp_dir('tabbed_spreadsheet') with ZipFile(attachment_file, 'r') as zip_file: # Extract all the contents of zip file in different directory zip_file.extractall(temp_dir) csv_files = zip_file.namelist() workbook = openpyxl.Workbook() for csv_file_name in csv_files: worksheet = workbook.create_sheet() with open(os.path.join(temp_dir, csv_file_name)) as file: reader = csv.reader(file) for row in reader: worksheet.append(row) if payload.form_params['file_name']: file_name = get_output_file_name(slug, payload.form_params['file_name'], timestamp=True) else: file_name = get_output_file_name(slug, 'tabbed_spreadsheet.xlsx', timestamp=True) workbook.save(file_name) response = send_email(to_emails=payload.form_params['email_address'], subject=payload.form_params['email_subject'], body=payload.form_params['email_body'], file_name=file_name, file_type='xlsx') return {'response': 'response'}
def action(payload: ActionRequest): """Endpoint for the Compile Report Pack action.""" sdk = get_sdk_for_schedule(payload.scheduled_plan.scheduled_plan_id) data = json.loads(payload.attachment.data) board_id = data[0]['board_id'] report_pack = sdk.homepage(board_id) report_structure = [] for id in report_pack.section_order[1:]: for section in report_pack.homepage_sections: if section.id == str(id): report_section = { 'title': section.title, 'cover': '', 'pages': [] } page_sizes = [] for match in re.findall(r'\[(.*?)\]', section.title): param, value = match.split(':') if param == 'cover': report_section['cover'] = value if param == 'size': page_sizes = value.split(',') logger.info(f'Processing section: {report_section}') logger.info(f'Page sizes config: {page_sizes}') page_num = 0 filters = [] for item_id in section.item_order: for item in section.homepage_items: if item.id == str(item_id): file_log.debug(f'items loop, filters: {pformat(filters)}') if item.look_id: filters = get_filters(sdk, item.look_id) file_log.debug(pformat(filters)) if item.dashboard_id: page = { 'title': item.title, 'dashboard_id': item.dashboard_id, 'size': '', 'orientation': '', 'filters': filters } if page_sizes: page['size'] = page_sizes[min(page_num, len(page_sizes)-1)] page['orientation'] = 'landscape' report_section['pages'].append(page) page_num += 1 filters = [] report_structure.append(report_section) file_log.debug('Report Structure:') file_log.debug(pformat(report_structure)) pdfs_to_merge = [] for section in report_structure: if section['cover']: cover_page = get_input_file_name(slug, section['cover']) pdfs_to_merge.append((cover_page, 'A4')) for page in section['pages']: if 'size' in page.keys(): if page['size']: page_size = page['size'] else: page_size = DEFAULT_PDF_PAGE_SIZE if 'orientation' in page.keys(): if page['orientation'] == 'landscape': page_is_landscape = True elif page['orientation'] == 'portrait': page_is_landscape = False else: page_is_landscape = DEFAULT_PDF_IS_LANDSCAPE if page['filters']: page_dashboard_id = str(page['dashboard_id']) dashboard_filters = sdk.dashboard(page_dashboard_id).dashboard_filters filter_map = {} for filter_ in dashboard_filters: filter_map[filter_.dimension] = filter_.name for idx, filter_set in enumerate(page['filters']): file_log.debug(f'idx filter_set {idx} {filter_set}') filters = [] for dimension, value in filter_set.items(): try: filters.append((filter_map[dimension], value)) except KeyError: file_log.debug(f'Ignoring filter value for {dimension} as not present in dashboard filter settings') file_name = get_temp_file_name(slug, page['title'].replace(' ', '_')) + f'_{idx}.pdf' file_log.debug(f'Downloading: {file_name} Size: {page_size} Is Landscape: {page_is_landscape}') rendered = download_dashboard(sdk, page['dashboard_id'], file_name, page_size, page_is_landscape, filters) if rendered: pdfs_to_merge.append((file_name, page_size)) else: file_name = get_temp_file_name(slug, page['title'].replace(' ', '_')) + '.pdf' file_log.debug(f'Downloading: {file_name} Size: {page_size} Is Landscape: {page_is_landscape}') download_dashboard(sdk, page['dashboard_id'], file_name, page_size, page_is_landscape) pdfs_to_merge.append((file_name, page_size)) report_pack_file = get_output_file_name(slug, cast(str, report_pack.title)) + '.pdf' if DOWNLOAD_DASHBOARDS: merge_pdfs(pdfs_to_merge, report_pack_file) if SEND_EMAIL: response = send_email( to_emails= payload.form_params['email_address'], subject= payload.form_params['email_subject'], body= payload.form_params['email_body'], file_name= report_pack_file, file_type= 'pdf' ) clear_temp_dir(slug) return {'response': 'response'}
def main(DEBUG=False): core.load_bills() core.check_due_dates() core.all_bills_to_json() core.send_email(DEBUG=DEBUG)
def send(self, subject='', message='', files=None): recipients = u', '.join(self.recipients) reply_to = u', '.join(self.reply_to) files = files or {} # get smtp addressing information from settings smtp_host = self.smtp_settings.get('hostname', u'localhost') mail_from = self.email_settings['addressbook'].get( 'from', u'*****@*****.**') # log smtp settings smtp_settings_log = deepcopy(self.smtp_settings) if 'password' in smtp_settings_log: del smtp_settings_log['password'] log.info( u'Sending email to "{recipients}". smtp settings: {smtp_settings}'. format(recipients=recipients, smtp_settings=smtp_settings_log)) # build subject event_date = time.strftime('%Y-%m-%d') event_time = time.strftime('%H:%M:%S') subject_real = u'' if 'subject_prefix' in self.email_settings['content']: prefix = self.email_settings['content'].get('subject_prefix') if not prefix.endswith(' '): prefix += ' ' subject_real += prefix #subject_real += u'{subject} on {event_date} at {event_time}'.format(**locals()) subject_real += u'{}'.format(subject) filenames = u'\n'.join([u'- ' + entry for entry in files.keys()]) body_template = textwrap.dedent(self.email_settings['content'].get( 'body', '')).strip() if 'signature' in self.email_settings['content']: body_template += u'\n\n--\n' + textwrap.dedent( self.email_settings['content']['signature']).strip() body_template = body_template.replace('\\n', '\r') tplvars = deepcopy(locals()) del tplvars['self'] body = jinja2.Template(body_template).render(**tplvars).strip() # debugging #print body #print('from:', mail_from) #print('recipients:', self.recipients) try: message = build_email(recipients, subject=subject_real, body_text=body, mail_from=mail_from, reply_to=reply_to, attachments=files) # TODO: catch exceptions when sending emails, e.g.:: # # smtplib.SMTPServerDisconnected: Connection unexpectedly closed # send_email(recipients, message, smtp_settings=self.smtp_settings, mail_from=mail_from) log.info( u'Email to recipients "{recipients}" sent successfully'.format( recipients=recipients)) except Exception as ex: # TODO: catch traceback when running in commandline mode log.error(u'Error sending email: {failure}'.format(failure=ex)) raise