def _send_email(self, to, subject, text_body, html_body=None, sender=None, attachments_info=[]): if sender is None: sender = current_app.config['MAIL_DEFAULT_SENDER'] decoded_attachments = [] for a in attachments_info: try: content = base64.b64decode(a['file']) decoded_attachments.append( Attachment(a['file_name'], a['content_type'], data=content)) except Exception as e: logger.error( 'Error attaching {} file to mail. Receipient(s): {}. Error: {}' .format(a['file_desc'], to, e)) msg = SuperdeskMessage(subject=subject, sender=sender, recipients=to, attachments=decoded_attachments) msg.body = text_body msg.html = html_body app = current_app._get_current_object() with app.mail.connect() as connection: if connection: return connection.send(msg) return app.mail.send(msg)
def send_result(result_data, content_type, recipients, tool_name): """ Sends the result via email to the user who requested it. :param result_data: generated data in a serialized form. :param content_type: MIME type of the attachment. :param recipients: recipients who will receive the email. :param tool_name: name of the tool, which will be used in the subject of the email. """ timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') filename = 'scoap3_export_%s_%s.csv' % (tool_name, timestamp) # compress data if needed compress = current_app.config.get('TOOL_COMPRESS_ATTACHMENT', False) if compress: compressed_buffer = StringIO() gzip_file = GzipFile(fileobj=compressed_buffer, mode="wt") gzip_file.write(result_data) gzip_file.close() result_data = compressed_buffer.getvalue() content_type = 'application/gzip' filename += '.gz' attachment = Attachment(filename=filename, content_type=content_type, data=result_data) msg = TemplatedMessage( template_html='scoap3_tools/email/result.html', subject='SCOAP3 - Export %s result' % tool_name, sender=current_app.config.get('MAIL_DEFAULT_SENDER'), recipients=recipients, attachments=[attachment], ) current_app.extensions['mail'].send(msg)
def generate_report(siteid, startday, endday): '''Create and send report for given site during the specified periodic_task ''' site = Wifisite.query.filter_by(id=siteid).first() start_date = startday.format('DD-MM-YYYY') end_date = endday.format('DD-MM-YYYY') current_app.logger.debug( 'Going to process report for :%s from :%s to :%s' % (site.name, start_date, end_date)) #get all entries within given period entries = Guest.query.filter( and_(Guest.siteid == siteid, Guest.demo == 0, Guest.created_at >= startday, Guest.created_at <= endday)).all() csvList = '\n'.join(','.join(row.to_row()) for row in entries) filename = "Report_%s_to_%s.csv" % (start_date, end_date) attachment = Attachment(filename=filename, content_type='txt/plain', data=csvList) msg = Message(_("Wifi usage report for the period :%s to :%s" % (start_date, end_date)), recipients=[site.client.email, site.reports_list], attachments=[attachment]) msg.body = _("Dear %s,\n\n"\ "\tPlease find the wifi usage report for the period of starting from:%s to %s \n"\ "\nRegards\n"\ "Admin"%(site.name,start_date,end_date)) mail.send(msg)
def alert(id): advice = Advice.objects.get_or_404(id=id) form = AlertAnonForm() if form.validate_on_submit(): csvfile = StringIO.StringIO() writer = csv.writer(csvfile) writer.writerow(csv.ANON_HEADER) writer.writerow(csv.to_anon_row(advice)) attachment = Attachment( 'cada-fix-{0}.csv'.format(advice.id), 'text/csv', csvfile.getvalue() ) mail.send_message("Défaut d'anonymisation sur l'avis CADA {0}".format(advice.id), recipients=[current_app.config['ANON_ALERT_MAIL']], html=render_template('anon_alert_mail.html', advice=advice, details=form.details.data), attachments=[attachment] ) flash( "<strong>Merci pour votre contribution!</strong> Nous avons bien pris en compte votre signalement.", 'success' ) return redirect(url_for('site.display', id=advice.id)) else: abort(400)
def send_result_to_mail(recipients, file_name, file_content): """ Creates message object and gives task to CELERY worker to send this message :param recipients: list of email addresses :param file_name: name of file to send :param file_content: bytes of file :return: None """ message = Message( subject="Your file has been processed!", sender=("CStats", APP.config['MAIL_DEFAULT_SENDER']), recipients=recipients, date=DateTimeManager.get_current_time_stamp(), body="Congratulations, your file has been processed successfully." "Please download it from attached files or from your profile on the site.\n\n" "Thank you for using our service", attachments=[ Attachment( filename=file_name, content_type= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data=file_content) ]) user_id = int(session.get('user_id', 0)) if user_id: send.apply_async([message], serializer='pickle', link=notify_user.s("Result has been sent", user_id)) else: send.apply_async([message], serializer='pickle')
def send_pii_export(self): json_str = self.export_user_pii_json() attachment = Attachment(filename="user_export.json", content_type="application/json", data=json_str) mailer = NotificationMailer(self._requesting_user.email, "appname User Data Export", "Your requested export is attached below", attachments=[attachment]) mailer.send()
def attachments(): # atts_list = ['green.jpg', 'blue.jpg', 'black.jpg', 'yellow.jpg'] a1 = app.open_resource('.\\images\\black.jpg') a2 = app.open_resource('.\\images\\blue.jpg') a3 = app.open_resource('.\\images\\green.jpg') att1 = Attachment(filename='black.jpg', content_type='image/jpg', data=a1.read(), disposition=None, headers=None) att2 = Attachment(filename='blue.jpg', content_type='image/jpg', data=a2.read(), disposition=None, headers=None) att3 = Attachment(filename='green.jpg', content_type='image/jpg', data=a3.read(), disposition=None, headers=None) msg = Message( subject='Snakes\'s attachments', recipients=['*****@*****.**'], # body = 'Kindly find attched the requested files.\nRegards\nChris', html= '<h1>..nice snakes!\' images</h1><hr><p>This is a test email, if evreything is ok, you should find attach multiple snake images.</p>', # sender = ',' cc=['*****@*****.**'], # bcc = [], attachments=[att1, att2, att3], # reply_to=[], # date='', # charset='', # extra_headers={'',''}, # mail_options=[], # rcpt_options=[] ) mail.send(msg) return '<p>email on the way!</p>'
def send_all_reports(report_type=None, year=None, month=None): """Query elasticsearch for each type of stats report.""" # By default get the current month and year now = datetime.now() month = month or now.month year = year or now.year tsv_files = [] all_results = { 'file_download': QueryFileReportsHelper.get( year=year, month=month, event='file_download'), 'file_preview': QueryFileReportsHelper.get( year=year, month=month, event='file_preview'), 'index_access': QueryRecordViewPerIndexReportHelper.get( year=year, month=month), 'detail_view': QueryRecordViewReportHelper.get( year=year, month=month), 'file_using_per_user': QueryFileReportsHelper.get( year=year, month=month, event='file_using_per_user'), 'top_page_access': QueryCommonReportsHelper.get( year=year, month=month, event='top_page_access'), 'search_count': QuerySearchReportHelper.get( year=year, month=month), 'user_roles': get_user_report_data(), 'site_access': QueryCommonReportsHelper.get( year=year, month=month, event='site_access') } with current_app.app_context(): # Allow for this to be used to get specific emails as well reports = {} if report_type is not None and report_type in all_results: reports[report_type] = all_results[report_type] else: reports = all_results zip_date = str(year) + '-' + str(month).zfill(2) zip_name = 'logReport_' + zip_date + '.zip' zip_stream = package_reports(reports, year, month) recepients = StatisticsEmail.get_all_emails() attachments = [Attachment(zip_name, 'application/x-zip-compressed', zip_stream.getvalue())] html_body = render_template( current_app.config['WEKO_ADMIN_REPORT_EMAIL_TEMPLATE'], report_date=zip_date, attached_file=zip_name) subject = zip_date + _(' Log report.') try: send_mail(subject, recepients, html=html_body, attachments=attachments) current_app.logger.info('[{0}] [{1}] '.format(0, 'Sent email')) except Exception as e: current_app.logger.info('[{0}] [{1}] '.format(1, 'Could not send'))
def make_attachment(filename, content_type, data, disposition=None, headers=None): """ Provide a function which can make attachments, insulating the caller from the flask-mail underlying implementation. :param filename: :param content_type: :param data: :param disposition: :param headers: :return: """ return Attachment(filename, content_type, data, disposition, headers)
def pg_backup(): """Backup pg database""" now = datetime.now().strftime('%Y%m%d_%H%M') filename = 'db_lovecalendar_{}.sql.gz'.format(now) pg_dump = subprocess.Popen(('pg_dump', 'lovecalendar'), stdout=subprocess.PIPE) output = subprocess.check_output('gzip', stdin=pg_dump.stdout) pg_dump.wait() with app.app_context(): send_mail('lovecalendar数据库备份', [app.config['ADMIN_MAIL']], None, [ Attachment(filename=filename, content_type='application/gzip', data=output) ])
def _send_user_email(user_id, text_message, html_message, data): """ Send a notification to the user email :param user_id: :param text_message: :param html_message: :return: """ user = superdesk.get_resource_service('users').find_one(req=None, _id=user_id) if not user: return # Check if the user has email notifications enabled preferences = superdesk.get_resource_service( 'preferences').get_user_preference(user.get('_id')) email_notification = preferences.get( 'email:notification', {}) if isinstance(preferences, dict) else {} if not email_notification.get('enabled', False): return user_email = user.get('email') if not user_email: return admins = app.config['ADMINS'] # Determine if there are any files attached to the event and send them as attachments attachments = [] if data.get('event') and data.get('event', {}).get('files'): for file_id in data.get('event', {}).get('files'): event_file = superdesk.get_resource_service( 'events_files').find_one(req=None, _id=file_id) media = app.media.get(event_file['media'], resource='events_files') fp = media.read() attachments.append( Attachment(filename=media.name, content_type=media.content_type, data=fp)) send_email(subject='Superdesk assignment', sender=admins[0], recipients=[user_email], text_body=text_message, html_body=html_message, attachments=attachments)
def long_task_test(self, user, recipient_emails, search_term, search_location): task_id = int(self.request.id.__str__()) # add search to search history print(f"long_task_test task user: {user}") search_history = models.SearchHistory(timestamp=datetime.now(), term=search_term, location=search_location, user_id=user) db.session.add(search_history) db.session.commit() # TODO: Update current/total with page of search results self.update_state(state='PROGRESS', meta={'current': 0, 'total': 1}) run_scrape(search_term=search_term, search_location=search_location, task_id=task_id) self.update_state(state='PROGRESS', meta={'current': 1, 'total': 1}) results = get_results(task_id) attachments = [] if results: attachment_filename = "YP_" + search_term + "_" + search_location + ".csv" content_type = 'text/csv' attachments.append( Attachment(filename=attachment_filename, content_type=content_type, data=results.read())) body = f"Attached are your scraped results for the term '{search_term}' for the location '{search_location}'." else: body = f"No results found for the term '{search_term}' for the location '{search_location}'." msgd = { "recipients": recipient_emails, "subject": "Yellow Pages Scrape Results", "body": body, "attachments": attachments } send_async_email(msgd) # temporarily delete records after they're emailed to save db space try: models.Records.query.filter_by(task_id=task_id).delete() db.session.commit() except: db.session.rollback()
def get_file_stats_tsv(self): """Get file download/preview stats report.""" stats_json = json.loads(request.form.get('report')) # file_type = request.form.get('type') year = request.form.get('year') month = request.form.get('month').zfill(2) # File Format: logReport__YYYY-MM.zip zip_date = str(year) + '-' + str(month).zfill(2) zip_name = 'logReport_' + zip_date + '.zip' try: # Dynamically create zip from StringIO data into BytesIO zip_stream = package_reports(stats_json, year, month) # Make the send email function a task so it if request.form.get('send_email') == 'True': recepients = StatisticsEmail.get_all_emails() html_body = render_template( current_app.config['WEKO_ADMIN_REPORT_EMAIL_TEMPLATE'], report_date=zip_date, attached_file=zip_name) subject = zip_date + _(' Log report.') attachments = [ Attachment(zip_name, 'application/x-zip-compressed', zip_stream.getvalue()) ] ret = send_mail(subject, recepients, html=html_body, attachments=attachments) if ret: flash(ret, 'error') else: flash( _('Successfully sent the reports to the recepients.')) else: resp = make_response() resp.data = zip_stream.getvalue() resp.headers['Content-Type'] = 'application/x-zip-compressed' resp.headers['Content-Disposition'] = 'attachment; filename='\ + zip_name return resp except Exception as e: current_app.logger.error('Unexpected error: ', e) flash(_('Unexpected error occurred.'), 'error') return redirect(url_for('report.index'))
def template_ping(): """ Message(subject='', recipients=None, body=None, html=None, sender=None, cc=None, bcc=None, attachments=None, reply_to=None, date=None, charset=None, extra_headers=None, mail_options=None, rcpt_options=None) """ """Development configinde default olarak emailler supress edilmistir.""" attachments = [] with current_app.open_resource('static/assets/img/brand-logo2.png') as fp: attachments.append( Attachment(filename="image.png", content_type="image/png", data=fp.read())) html = send_mail_with_template( recipients=['*****@*****.**'], subject=_("Ornek mail"), template='email_template_ping.html', logo_text=_("Zopsedu"), title_text=_("Ornek Mail"), greeting=_("Merhaba"), greeting_name="Zopsedu", content_text="Lorem ipsum dolor sit amet, consectetur " "adipiscing elit. Curabitur et nisi vehicula, " "convallis dolor sed, pulvinar odio. Vestibulum " "fermentum faucibus sapien vestibulum " "consectetur. Etiam non blandit diam, " "non fermentum neque. " "Donec fringilla eget arcu in sagittis. Vestibulum " "ante ipsum primis in faucibus orci " "luctus et ultrices posuere ", button_href="http://v2.zopsedu.net", button_text="Zopsedu", content_end_text="Sevgilerle, <br>Zopsedu", attachments=attachments) return html
def test_send_message_with_attachments(email_task_app): """Test sending a message with attachments.""" with email_task_app.app_context(): filename = pkg_resources.resource_filename( __name__, os.path.join('attachments', 'invenio.svg')) content_type = 'image/svg+xml' data = pkg_resources.resource_string( __name__, os.path.join('attachments', 'invenio.svg')) attachments = [Attachment(filename, content_type, data)] msg = { 'subject': 'Test3', 'sender': '[email protected]', 'recipients': ['[email protected]'], 'attachments': attachments } send_email.delay(msg) result_stream = email_task_app.extensions['invenio-mail'].stream assert result_stream.getvalue().find( 'Content-Transfer-Encoding: base64') != -1 assert result_stream.getvalue().find( 'Content-Disposition: attachment;') != -1
def _send_user_email(user_id, contact_id, source, meta_message, data): """ Send a notification to the user email :param user_id: :param text_message: :param html_message: :return: """ email_address = None if contact_id: contact = superdesk.get_resource_service('contacts').find_one( req=None, _id=contact_id) email_address = next(iter(contact.get('contact_email') or []), None) data['recepient'] = contact elif user_id: user = superdesk.get_resource_service('users').find_one(req=None, _id=user_id) data['recepient'] = user if not user: return # Check if the user has email notifications enabled preferences = superdesk.get_resource_service( 'preferences').get_user_preference(user.get('_id')) email_notification = preferences.get( 'email:notification', {}) if isinstance(preferences, dict) else {} if not email_notification.get('enabled', False): return email_address = user.get('email') if not email_address: return admins = app.config['ADMINS'] data['subject'] = 'Superdesk assignment' + ': {}'.format( data.get('slugline') if data.get('slugline') else '') data['system_reciepient'] = get_assignment_acceptance_email_address() html_message = _get_email_message_html(source, meta_message, data) text_message = _get_email_message_string(source, meta_message, data) # Determine if there are any files attached to the event and send them as attachments attachments = [] if data.get('event') and data.get('event', {}).get('files'): for file_id in data.get('event', {}).get('files'): event_file = superdesk.get_resource_service( 'events_files').find_one(req=None, _id=file_id) media = app.media.get(event_file['media'], resource='events_files') fp = media.read() attachments.append( Attachment(filename=media.name, content_type=media.content_type, data=fp)) if data.get('assignment') and (data['assignment'].get('planning', {})).get('files'): for file_id in data['assignment']['planning']['files']: assignment_file = superdesk.get_resource_service( 'planning_files').find_one(req=None, _id=file_id) if assignment_file: media = app.media.get(assignment_file['media'], resource='planning_files') fp = media.read() attachments.append( Attachment(filename=media.name, content_type=media.content_type, data=fp)) else: logger.error( 'File {} attached to assignment {} not found'.format( file_id, data['assignment']['assignment_id'])) if data.get('assignment') and (data['assignment'].get('planning', {})).get('xmp_file'): file_id = data['assignment']['planning']['xmp_file'] xmp_file = superdesk.get_resource_service('planning_files').find_one( req=None, _id=file_id) if xmp_file: media = app.media.get(xmp_file['media'], resource='planning_files') fp = media.read() attachments.append( Attachment(filename=media.name, content_type=media.content_type, data=fp)) else: logger.error( 'XMP File {} attached to assignment {} not found'.format( data['assignment']['xmp_file'], data['assignment']['assignment_id'])) send_email(subject=data['subject'], sender=admins[0], recipients=[email_address], text_body=text_message, html_body=html_message, attachments=attachments)
def _transmit(self, queue_item, subscriber): config = queue_item.get('destination', {}).get('config', {}) try: # detect if it's been formatted by the Email formatter, is so load the item try: item = json.loads(queue_item['formatted_item']) if 'message_subject' not in item: item = {} except Exception: item = {} admins = app.config['ADMINS'] recipients = [ r.strip() for r in config.get('recipients', '').split(';') if r.strip() ] bcc = [ r.strip() for r in config.get('recipients_bcc', '').split(';') if r.strip() ] if not recipients and not bcc: raise PublishEmailError.recipientNotFoundError( LookupError('recipient and bcc fields are empty!')) subject = item.get('message_subject', 'Story: {}'.format(queue_item['item_id'])) text_body = item.get('message_text', queue_item['formatted_item']) html_body = item.get('message_html', queue_item['formatted_item']) # Attach feature media if required attachments = [] if config.get('attach_media') and item.get('renditions'): # The CID can be used to embbed the image in the html template email like <img src=CID:cid-value> cid = config.get('media_cid', '') # Get the rendition that has been nominated for attaching to the email rendition = config.get('media_rendition', '') media_item = item.get('renditions', {}).get(rendition) if media_item and rendition: media = app.media.get(media_item['media'], resource='upload') im = Image.open(media) if config.get('watermark', False): im = get_watermark(im) binary = io.BytesIO() im.save(binary, 'jpeg', quality=80) attachments.append( Attachment(filename=media.name, content_type=media.content_type, data=binary.getvalue(), headers=[('Content-ID', cid)])) # sending email synchronously send_email(subject=subject, sender=admins[0], recipients=recipients, text_body=text_body, html_body=html_body, bcc=bcc, attachments=attachments) except Exception as ex: raise PublishEmailError.emailError(ex, queue_item.get('destination'))
def _transmit(self, queue_item, subscriber): config = queue_item.get("destination", {}).get("config", {}) try: # detect if it's been formatted by the Email formatter, is so load the item try: item = json.loads(queue_item["formatted_item"]) if "message_subject" not in item: item = {} except Exception: item = {} admins = app.config["ADMINS"] recipients = [r.strip() for r in config.get("recipients", "").split(";") if r.strip()] bcc = [r.strip() for r in config.get("recipients_bcc", "").split(";") if r.strip()] if not recipients and not bcc: raise PublishEmailError.recipientNotFoundError(LookupError("recipient and bcc fields are empty!")) subject = item.get("message_subject", "Story: {}".format(queue_item["item_id"])) text_body = item.get("message_text", queue_item["formatted_item"]) html_body = item.get("message_html", queue_item["formatted_item"]) # Attach feature media if required attachments = [] if config.get("attach_media") and item.get("renditions"): # The CID can be used to embbed the image in the html template email like <img src=CID:cid-value> cid = config.get("media_cid", "") # Get the rendition that has been nominated for attaching to the email rendition = config.get("media_rendition", "") media_item = item.get("renditions", {}).get(rendition) if media_item and rendition: media = app.media.get(media_item["media"], resource="upload") im = Image.open(media) if config.get("watermark", False): im = get_watermark(im) binary = io.BytesIO() im.save(binary, "jpeg", quality=80) attachments.append( Attachment( filename=media.name, content_type=media.content_type, data=binary.getvalue(), headers=[("Content-ID", cid)], ) ) # sending email synchronously send_email( subject=subject, sender=admins[0], recipients=recipients, text_body=text_body, html_body=html_body, bcc=bcc, attachments=attachments, ) except Exception as ex: raise PublishEmailError.emailError(ex, queue_item.get("destination"))
def post(self, session): tickets = request.json["tickets"] pay = request.json["pay"] amount = 0 customer = None done = [] for uuid in tickets: ticket: TicketModel = TicketModel.query.filter_by( uuid=uuid).first() ticket.paid = pay db.session.commit() amount = amount + PriceModel.query.filter_by( uuid=ticket.price_id).first().value ticket_customer = customer = CustomerModel.query.filter_by( uuid=ticket.customer).first() if customer and ticket_customer.uuid != customer.uuid: return {"mail": False} else: customer = ticket_customer done.append(ticket) if config["MAIL_ENABLED"] and pay and len(done) > 0: msg_title = SettingModel.query.filter_by( key="ticket_mail_title").first().value msg_content = SettingModel.query.filter_by( key="ticket_mail_content").first().value if msg_title != '' and msg_content != '': cc = SettingModel.query.filter_by(key="mail_cc_paid").first() pdfs = [] for ticket in done: file = download.create_pdf(ticket) pdfs.append( Attachment(filename='ticket_' + ticket.uuid + '.pdf', content_type='application/pdf', data=file)) msg = Message(msg_title, recipients=[customer.email], attachments=pdfs) if cc and cc.value != '': msg.cc = [cc.value] customer_url = str( config['ENDPOINT']) + 'f/customer/' + customer.uuid msg_content = msg_content.replace( '{{name}}', customer.firstname + ' ' + customer.lastname) msg_content = msg_content.replace( '{{customer}}', '<a href="' + customer_url + '">' + customer_url + '</a>') msg_content = msg_content.replace('{{amount}}', str(int(amount))) msg_content = msg_content.replace('\n', '<br>') msg.html = msg_content mail.send(msg) return {"mail": True} return {"mail": False}