def test_send_email_html(mock_send, mock_render_to_string): """ If only the HTML version of the template is available, the plain text message should be empty. """ mock_render_to_string.side_effect = render_html context = {'foo': 'bar'} template_name = 'foo' email_utils.send_email(context=context, template_name=template_name) assert mock_render_to_string.call_count == 2 assert mock_render_to_string.call_args_list[0][1] == { 'context': context, 'template_name': '{}.html'.format(template_name), } assert mock_render_to_string.call_args_list[1][1] == { 'context': context, 'template_name': '{}.txt'.format(template_name), } assert mock_send.call_count == 1 assert mock_send.call_args[1] == { 'html_message': html_message, 'message': '', }
def handle(project, request): sample_pk = int(request.POST.get('samplePK', '')) sample = Sample.objects.get(pk=sample_pk) has_error = bool(int(request.POST.get('has_error', ''))) if has_error: # notify CCCB print 'Error with circRNA worker' email_utils.send_email(os.path.join(settings.BASE_DIR, settings.GMAIL_CREDENTIALS), \ "There was a problem with the circRNA worker for sample %s" % sample.name, \ settings.CCCB_EMAIL_CSV.split(','), '[CCCB] Problem with circRNA worker') else: sample.processed = True sample.save() # now check to see if everyone is done all_samples = project.sample_set.all() if all([s.processed for s in all_samples]): project.in_progress = False project.paused_for_user_input = False project.completed = True project.status_message = 'Complete' project.next_action_text = '-' project.next_action_url = '' project.has_downloads = True project.save() tasks.finish_circ_rna_process.delay(project.pk)
def send_email(self): """ Send an email containing the verification token to the email address being verified. """ verification_url_template = app_settings.EMAIL_VERIFICATION_URL if verification_url_template is not None: verification_url = verification_url_template.format(key=self.token) else: verification_url = None context = { "email": self.email, "user": self.email.user, "verification": self, "verification_url": verification_url, } template = "email_auth/emails/verify-email" email_utils.send_email( context=context, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email.address], subject=_("Please Verify Your Email Address"), template_name=template, ) self.time_sent = timezone.now() self.save()
def wrapup(x, kwargs): print 'in wrapup function, x=%s' % x print 'in wrapup function, kwargsX=%s' % kwargs project = Project.objects.get(pk=kwargs['project_pk']) project_owner = project.owner.email message = 'Your file transfer from Dropbox is complete! Return to the page or refresh' message_html = HTML_BODY % message email_utils.send_email(os.path.join(settings.BASE_DIR, settings.GMAIL_CREDENTIALS), message_html, [project_owner,], '[CCCB] Dropbox transfer complete')
def send_verification_email(user): token = default_token_generator.make_token(user) url = build_verification_link(user, token) send_email(subject='회원가입을 축하드립니다.', context={'url': url}, recipient_list=[user.email], from_email=settings.EMAIL_HOST_USER, template_name='email_auth/verify_email_template')
def notification_logic(username, password, host, database, sensor, lower_threshold, upper_threshold, relaxation, to): mydb, cursor = connect_database(username, password, database, host) crossed, value = observe(cursor, database, sensor, lower_threshold, upper_threshold) if crossed and not check_if_sent(cursor, database, sensor, relaxation): store_info(cursor, mydb, sensor) message = compose_email(to, 'Alert notification', sensor, value) send_email(message) cursor.close() mydb.close()
def check_completion(project_pk, code_map, bucket_name): ''' params project_pk: code_map: bucket_name: bucket name ''' while code_map: for code_info_map in code_map: code, samplename, vcffilename, cloud_dge_dir = code_info_map script = ' '.join(["gcloud alpha genomics operations describe", code, "--format='yaml(done, error, metadata.events)'"]) proc = subprocess.Popen(script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = proc.communicate() out_map = yaml.safe_load(stdout) done_status = out_map["done"] #errors[code] = out_map["error"] # setting up file locations if done_status == True: # data format may be altered: #samplename = code_info_map["samplename"] #vcffilename = code_info_map["vcffilename"] #cloud_dge_dir = code_info_map["bucket_path"] #samplename, vcffilename, cloud_dge_dir = code_info_map # fix this!!! project = Project.objects.get(pk=project_pk) storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) # ToDo fix the path to file (must be sent to app) destination = os.path.join(cloud_dge_dir, os.path.basename(vcffilename)) vcf_blob = bucket.blob(destination) public_link = LINK_ROOT % (bucket.name, vcf_blob.name) r = Resource(project=project, basename=samplename, public_link=public_link, resource_type='VCF files') r.save() del code_map[code] time.sleep(900) project.completed = True project.in_progress = False project.has_downloads = True project.status_message = "Completed variant calling" message_html = """ <html> <body> Your variant calling analysis has finished. Log-in to download your results. </body> </html> """ email_utils.send_email(message_html, [project.owner.email,], \ '[CCCB] Variant calling analysis completed')
def t_send_email(): try: mail = ema.init_mail() ema.send_email(mail, { "BODY": "test body", "EMAIL_SUBJECT": "test email subject" }) ema.quit_mail(mail) except Exception as e: print("Error : The email test failed" + str(e))
def send_email(stock_symbol, rate_of_change): email_content = {} stock_symbol = "stock_symbol : " + str(stock_symbol) + "\n" rate_of_change = "rate_of_change : " + str(rate_of_change) + "\n" email_content["BODY"] = stock_symbol + rate_of_change email_content["EMAIL_SUBJECT"] = "**** Stock ALERT ****" mail = ema.init_mail() ema.send_email(mail, email_content) ema.quit_mail(mail) print("email sent :" + str(email_content))
def scan_hacker_news(request): top_stories = get(top_stories_url).json() cloud_stories = [] for story_id in top_stories: story = get(item_url.format(story_id)).json() if 'cloud' in story['title'].lower(): cloud_stories.append(story) if cloud_stories: send_email(cloud_stories)
def test_send_email_neither(mock_send, mock_render_to_string): """ If neither template can be loaded, an exception should be thrown and no email should be sent. """ mock_render_to_string.side_effect = TemplateDoesNotExist('foo') with pytest.raises(email_utils.NoTemplatesException): email_utils.send_email('foo') assert mock_send.call_count == 0
def send_duplicate_notification(self): """ Send a notification about a duplicate signup. """ email_utils.send_email( from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email], subject=_('Registration Attempt'), template_name='rest_email_auth/emails/duplicate-email', ) logger.info('Sent duplicate email notification to: %s', self.email)
def send_duplicate_notification(self): """ Send a notification about a duplicate signup. """ email_utils.send_email( from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email], subject=_("Registration Attempt"), template_name=app_settings.PATH_TO_DUPLICATE_EMAIL_TEMPLATE, ) logger.info("Sent duplicate email notification to: %s", self.email)
def _send_missing_email_notification(self): """ Send an email to the provided address informing the user they need to register or add the email to their account before they can verify it. """ email_utils.send_email( context={"email": self.validated_data["email"]}, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.validated_data["email"]], subject=_("Unregistered Email Address"), template_name="email_auth/emails/unregistered-email", )
def send_verification_email(self): context = { "username": self.username, "verification_token": self.verification_key } send_email( context=context, from_email='*****@*****.**', recipient_list=[self.email], subject='Please do not reply this message', template_name='virtualclass/email-verification', ) self.email_sent_time = timezone.now() self.save()
def dropbox_transfer(request, project_pk): print 'in drbx' print project_pk HTML_BODY = '<html><body>The following files were not named correctly and did not transfer. Please correct them and try again. <ul>%s</ul></body></html>' try: project_pk = int(project_pk) project = Project.objects.get(pk=project_pk) if project.owner == request.user: print request.POST is_sample_datasource_upload = request.POST.get('sample_source_upload') print is_sample_datasource_upload file_links = request.POST.get('transfer_files') file_links = [x.strip() for x in file_links.split(',')] print file_links all_transfers = [] misnamed_file_list = [] err_func = tasks.on_chord_error.s() for i,f in enumerate(file_links): print 'try to transfer %s' % f file_name = f.split('/')[-1] try: helpers.determine_filetype(file_name) destination = os.path.join(project.bucket, settings.UPLOAD_PREFIX, file_name) destination = destination.replace(' ', '_') print 'make transfer with %s' % file_name all_transfers.append(tasks.dropbox_transfer_to_bucket.s(f, destination, project.pk, is_sample_datasource_upload)) except helpers.UndeterminedFiletypeException as ex: print 'problem with %s' % file_name misnamed_file_list.append(file_name) if len(misnamed_file_list) > 0: print 'send a message- %s' % misnamed_file_list file_str = ''.join(['<li>%s</li>' % x for x in misnamed_file_list]) print file_str message_html = HTML_BODY % file_str print message_html email_utils.send_email(os.path.join(settings.BASE_DIR, settings.GMAIL_CREDENTIALS), message_html, [project.owner.email,], '[CCCB] Error with Dropbox transfer') #callback = tasks.wrapup.s(project=project) [task.link_error(err_func) for task in all_transfers] print 'about to invoke callback' #callback = tasks.wrapup.s(kwargs={'project':project}) callback = tasks.wrapup.s(kwargs={'project_pk': project.pk}) #callback = tasks.wrapup.s(kwargs={'project_pk': project.pk}).on_error(tasks.on_chord_error.s()) #callback = tasks.wrapup.s(kwargs={'project_pk': project.pk}).set(link_error='on_chord_error') print'about to do chord' r = chord(all_transfers)(callback) print 'done with chord' return HttpResponse('') except: return HttpResponseBadRequest('')
def send_duplicate_notification(self): """ Send an email notifying the user that this email address has already been registered. """ context = {"email": self} template = "email_auth/emails/duplicate-email" email_utils.send_email( context=context, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.address], subject=_("Your Email Address has Already Been Registered"), template_name=template, )
def send_email(self): """ Send a verification email to the associated email address. """ email_utils.send_email( context={ 'name': self.email.user.name, 'token': self.token, }, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email.address], subject=_('Please Verify Your Email'), template_name='account/emails/verify-email', ) logger.info("Sent verification %r to email %r", self, self.email)
def send(self): """ Send the password reset token to the user. """ context = { 'reset_url': app_settings.PASSWORD_RESET_URL.format(key=self.key), } email_utils.send_email( context=context, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email.email], subject=_('Reset Your Password'), template_name='rest_email_auth/emails/reset-password', ) logger.info('Sent password reset email to %s', self.email)
def send(self): """ Send the password reset token to the user. """ context = { "reset_url": app_settings.PASSWORD_RESET_URL.format(key=self.key) } email_utils.send_email( context=context, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email.email], subject=_("Reset Your Password"), template_name=app_settings.PATH_TO_RESET_EMAIL_TEMPLATE, ) logger.info("Sent password reset email to %s", self.email)
def finalize(project_pk): project = Project.objects.get(pk=project_pk) bucket_name = project.bucket storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) all_contents = bucket.list_blobs() all_contents = [x for x in all_contents] # turn iterator into list config_params = cp_.parse_config() # get the files that are in the result folder: outfiles = {} outfiles['BAM Files'] = [] bam_pattern = '%s/.*.bam$' % config_params['output_bucket'] outfiles['BAM Files'].extend([x for x in all_contents if re.match(bam_pattern, x.name) is not None]) bai_pattern = '%s/.*.bam.bai$' % config_params['output_bucket'] outfiles['BAM Files'].extend([x for x in all_contents if re.match(bai_pattern, x.name) is not None]) outfiles['Quantification table'] = [x for x in all_contents if x.name == os.path.join(config_params['output_bucket'], config_params['merged_counts_filename'])] # add user's privileges to these: for key, filelist in outfiles.items(): for f in filelist: print 'grant ownership on %s' % f acl = f.acl entity = acl.user(project.owner.email) entity.grant_read() acl.save() # register the files with the download app public_link = LINK_ROOT % (bucket.name, f.name) r = Resource(project=project, basename = os.path.basename(f.name), public_link = public_link, resource_type = key) r.save() set_meta_cmd = 'gsutil setmeta -h "Content-Disposition: attachment; filename=%s" gs://%s/%s' % (os.path.basename(f.name), bucket_name, f.name) print 'set meta cmd: %s' % set_meta_cmd process = subprocess.Popen(set_meta_cmd, shell = True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode != 0: print 'Error while setting metadata on %s. STDERR was:\n %s' % (f.name, stderr) print 'send notification email' message_html = write_completion_message(project) email_utils.send_email(os.path.join(settings.BASE_DIR, settings.GMAIL_CREDENTIALS), message_html, [project.owner.email,], 'Your pooled CRISPR analysis has completed')
def send_duplicate_notification(self): """ Send a notification to the user who owns this address letting them know a duplicate registration attempt was made. """ email_utils.send_email( context={ 'email': self.address, 'name': self.user.name, }, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.address], subject=_('Duplicate Email Registration'), template_name='account/emails/duplicate-email', ) logger.info( "Sent duplicate email registration notification to %r", self, )
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) html_email = '' if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) send_email(body, html_email, to_email, subject)
def handler(event, context): # read in data from environment project_name = os.environ["project_name"] notification_email = os.environ["notification_email"] state_table = os.environ["dynamodb_state_table_name"] # read in data passed to the lambda call stackset_id = event["stackset_id"] stackset_email = event["stackset_email"] # Get config from dynamodb dynamodb_client = boto3.client("dynamodb") state_data = dynamodb_client.get_item( TableName=state_table, Key={"stacksetID": { "S": stackset_id }})["Item"] for instance_data in fetch_stackset_instances(stackset_id=stackset_id): template_data = { "region": instance_data["region"], "os": instance_data["operatingSystemName"], "instance_type": instance_data["instanceType"], "instance_name": instance_data["instanceName"], "ip": instance_data["private_ip"], "expiry": datetime.fromisoformat( state_data["expiry"]["S"]).strftime("%-I %p %d %B"), } send_email( template_name="provision_success", template_data=template_data, source_email= f"Instance Provisioning ({project_name}) <{notification_email}>", to_email=stackset_email, )
def send(self, request): """ Send an invitation message to the email address associated with the instance. Args: request: The request that was made to trigger the send. This is used to build the full URL for accepting the invite. """ email_utils.send_email( context={ 'accept_url': f'{request.get_host()}{self.accept_url}', 'client': self.client, }, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email], subject=ugettext('Client Administrator Invitation'), template_name='vms/emails/client-admin-invite', ) logger.info('Sent client admin invitation to %s', self.email)
def test_send_email(mock_send, mock_render_to_string): """ The send email function should load the plain text and HTML versions of the template, and send an email with them. """ mock_render_to_string.side_effect = render_both context = {'foo': 'bar'} from_email = '*****@*****.**' recipient_list = ['*****@*****.**'] subject = 'Test Email' template_name = 'foo' email_utils.send_email( context=context, from_email=from_email, recipient_list=recipient_list, subject=subject, template_name=template_name, ) assert mock_render_to_string.call_count == 2 assert mock_render_to_string.call_args_list[0][1] == { 'context': context, 'template_name': '{}.html'.format(template_name), } assert mock_render_to_string.call_args_list[1][1] == { 'context': context, 'template_name': '{}.txt'.format(template_name), } assert mock_send.call_count == 1 assert mock_send.call_args[1] == { 'from_email': from_email, 'html_message': html_message, 'message': text_message, 'recipient_list': recipient_list, 'subject': subject, }
def dropbox_transfer_to_bucket(source_link, destination, project_pk, is_sample_datasource_upload): project = Project.objects.get(pk=project_pk) cmd = 'wget -q -O - "%s" | gsutil cp - gs://%s' % (source_link, destination) print cmd p = subprocess.Popen(cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: print 'Failed on transfering %s' % source_link.split('/')[-1] print stdout print '--'*10 print stderr #message = 'our Dropbox file (%s) could not be determined. Please consult the instructions on how to name files for the application. Then try again.' % source_link.split('/')[-1] else: print 'Done transferring from %s' % source_link try: helpers.add_datasource_to_database(project, destination[len(project.bucket)+1:], is_sample_datasource_upload) except helpers.UndeterminedFiletypeException as ex: project_owner = project.owner.email message = 'The file type of your Dropbox file (%s) could not be determined. Please consult the instructions on how to name files for the application. Then try again.' % source_link.split('/')[-1] message_html = HTML_BODY % message email_utils.send_email(os.path.join(settings.BASE_DIR, settings.GMAIL_CREDENTIALS), message_html, [project_owner,], '[CCCB] Problem with Dropbox transfer') raise ex
def dropbox_transfer_complete(request): print 'received request from dropbox worker completion' print request.POST if 'token' in request.POST: b64_enc_token = request.POST['token'] enc_token = base64.decodestring(b64_enc_token) expected_token = settings.TOKEN obj=DES.new(settings.ENCRYPTION_KEY, DES.MODE_ECB) decrypted_token = obj.decrypt(enc_token) if decrypted_token == expected_token: print 'token matched' master_pk = int(request.POST.get('masterPK', '')) transfer_pk = int(request.POST.get('transferPK', '')) try: transfer = DropboxFileTransfer.objects.get(pk=transfer_pk) transfer.is_complete = True transfer.save() master = DropboxTransferMaster.objects.get(pk = master_pk) all_transfers = master.dropboxfiletransfer_set.all() if all([x.is_complete for x in all_transfers]): print 'delete transfer master' li_string = ''.join(['<li>%s</li>' % os.path.basename(x.source) for x in all_transfers]) msg = "<html><body>Your file transfer to Dropbox has completed! The following files should now be in your Dropbox:<ul>%s</ul></body></html>" % li_string # note that the email has to be nested in a list print 'will send msg: %s\n to: %s' % (msg,master.owner.email) email_utils.send_email(os.path.join(settings.BASE_DIR, settings.GMAIL_CREDENTIALS), msg, [master.owner.email,], '[CCCB] Dropbox transfer complete') master.delete() else: print 'wait for other transfers to complete' return HttpResponse('Acknowledged.') except Exception as ex: print 'caught some exception: %s' % ex.message return HttpResponseBadRequest('') else: print 'token did not match' return HttpResponseBadRequest('') else: print 'token NOT in request' return HttpResponseBadRequest('')
def send(self): """ Send a verification email to the user. """ context = { 'verification_url': app_settings.EMAIL_VERIFICATION_URL.format(key=self.key), } email_utils.send_email( context=context, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email.email], subject=_('Please Verify Your Email Address'), template_name='rest_email_auth/emails/verify-email', ) logger.info( 'Sent confirmation email to %s for user #%d', self.email.email, self.email.user.id, )
def send(self): """ Send a verification email to the user. """ context = { "verification_url": app_settings.EMAIL_VERIFICATION_URL.format(key=self.key) } email_utils.send_email( context=context, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email.email], subject=_("Please Verify Your Email Address"), template_name=app_settings.PATH_TO_VERIFY_EMAIL_TEMPLATE, ) logger.info( "Sent confirmation email to %s for user #%d", self.email.email, self.email.user.id, )