def create_resource(request): if request.method == 'POST': form = ResourceForm(request.POST, request.FILES) files = request.FILES.getlist('images') if form.is_valid(): with transaction.atomic(): res = form.save(commit=True) res.author = request.user res.save() for file in files: file = ResourceImage(image=file) file.resource = res file.save() mailer = Mailer() mailer._send_email( CDCRC_MEDIA_EMAIL, 'Approval Request for New Resource {}'.format(res.title), '{} has added a resource titled {}. Please take a look.'. format(res.author.username, res.title)) return render_message( request, 'Approval Pending', 'Thanks for sharing the resource...it will be posted on the website after being approved by our team!' ) else: return render_message( request, 'Error', 'There was an error in creating the resource') else: form = ResourceForm() return render(request, 'info/resource_create.html', context={'form': form})
def send_email(self, subject="Submitted", reason="Job submission successful"): try: dir_path = "/tmp" email_list = self.params["email"].replace(" ", "") email_to = "{0}@cisco.com".format(self.params["submitter"]) for email in email_list.split(','): if email == "": continue if not email.endswith("@cisco.com"): email += "@cisco.com" email_to = "{0},{1}".format(email_to, email) input_dict = {} input_dict["submitter"] = self.params["submitter"] input_dict["submit_id"] = self.params["submit_id"] input_dict["status"] = subject input_dict["reason"] = reason subject = "N9k Sanity Job {0} Submission: {1}".format( self.params["submit_id"], subject) j2env = J2Env() template_file = 'job_submission_email.html' out_file = "{0}/{1}".format(dir_path, "req_creation_mail.html") # print(out_file) j2env.create_file(template_file, input_dict, out_file) mailer = Mailer(email_to) mailer.send_html_mail(subject, out_file) except BaseException as e: log.error("Exception in send mail:" + repr(e))
def contact_us_form(request): if request.method == 'POST': form = ContactUsForm(request.POST) if form.is_valid(): contact_us_obj = form.save(commit=True) mailer = Mailer() mailer._send_email( PRIMARY_ALERT_EMAILS, '[ALERT] New Registration on Website: {}'.format( contact_us_obj.name), 'Please reach out to {} from {} who has registered on the CDCRC Website.\n Contact Info - {}, {}.\nMessage- {}' .format(contact_us_obj.name, contact_us_obj.organization, contact_us_obj.email, contact_us_obj.phone, contact_us_obj.message), ) return render_message( request, 'Thanks!', 'Our team will reach out to you shortly. You can also call us at {} whenever you want!' .format(PRIMARY_PHONE)) else: return render_message(request, 'Error', 'There was an error in filling the form..') else: title = 'Contact Us Form' form = ContactUsForm() return render(request, 'info/contact_us_form.html', context={ 'title': title, 'form': form })
def __init__(self, config): self.name = 'ip_manager' self.config = config self.sql_helper = SqlIpManager() self._mailer = Mailer(config) self.vendors = [] self._vendor_initialized = True for vendor_name in config.get('VENDORS', []): logger.info('vendor[{0}] with config[{1}].'.format( vendor_name, config['VENDORS'][vendor_name])) if config['VENDORS'][vendor_name]['enabled']: if vendor_name == 'zmhttp': self.vendors.append( ZmHttp(config['VENDORS'][vendor_name], self.sql_helper, vendor_name)) elif vendor_name == 'horocn': self.vendors.append( Horocn(config['VENDORS'][vendor_name], self.sql_helper, vendor_name)) else: logger.warning( 'unknown vendor[{0}] with config[{1}].'.format( vendor_name, config['VENDORS'][vendor_name])) self.seeker_info = None self.update_time = datetime.datetime.now() today = datetime.datetime.now() report_time_str = '{0}-{1}-{2} {3}'.format( today.year, today.month, today.day, config['ROUTINE'].get('report_time', '23:55:00')) self._next_report_time = datetime.datetime.strptime( report_time_str, "%Y-%m-%d %H:%M:%S") if datetime.datetime.now() > self._next_report_time: self._next_report_time = self._next_report_time + datetime.timedelta( days=1)
def post(self, request): form = SignupForm(request.POST, request.FILES) if form.is_valid(): # Creating user and profile try: with transaction.atomic(): new_user = User(username=form.cleaned_data['login'], password=make_password( form.cleaned_data['password']), email=form.cleaned_data['email'], avatar=form.cleaned_data['avatar'], reg_date=datetime.datetime.now()) new_user.save() Mailer().send(new_user.email, 'sign_up', context={"login": new_user.username}) return HttpResponseRedirect('/signup/done/') except Exception as error: message = 'Error while adding new user: '******'Error while adding new user, check fields ' return render(request, "index/signup.html", { "form": form, "message": message, "trends": Trend.get_trends() })
def __init__(self, config): self.name = 'cdfbj_subscriber' self._config = config self._sql_helper = SqlCdfBj() self._message_queue = [] self._workers = [] self._mailers = [] self._mailer = Mailer(config)
def __init__(self, name, config, user_id_set): threading.Thread.__init__(self) self.name = name self._running = True self._config = config self._sql_helper = SqlCdfBj() self._mailer = Mailer(config) self._user_id_set = user_id_set self._mutex = threading.Lock() self._mail_tasks = []
def create_issue_followup(request, pk): if request.method == 'POST': form = IssueFollowupForm(request.POST) if form.is_valid(): next_reminder = datetime.datetime.strptime( request.POST['next_reminder'], '%m/%d/%Y %H:%M').strftime('%Y-%m-%d %H:%M') print(next_reminder) followup_obj = form.save(commit=False) issue_obj = Issue.objects.get(pk=pk) followup_obj.issue = issue_obj issue_obj.next_reminder = next_reminder issue_obj.save() followup_obj.save() for assignee in request.POST.getlist('assignees'): followup_obj.assignees.add( TeamMemberProfile.objects.get(pk=int(assignee))) followup_obj.save() mailer = Mailer() #alert the assignees for assignee in followup_obj.assignees.all(): #send alert via mail to the assignees mailer.send_issue_followup_alert_to_assignee( [assignee.user.email], assignee.user.first_name + " " + assignee.user.last_name, 'CDCRC System Alert: ' + followup_obj.issue.title, followup_obj.issue.title, followup_obj.comment, followup_obj.get_detail_url(request)) #alert the creator mailer.send_issue_followup_alert_to_creator( [followup_obj.issue.creator.user.email], request.user.first_name + " " + request.user.last_name, 'CDCRC System Alert: ' + followup_obj.issue.title, followup_obj.issue.title, followup_obj.comment, followup_obj.get_detail_url(request)) mailer.send_issue_followup_alert_to_follower( [request.user.email], request.user.first_name + " " + request.user.last_name, 'CDCRC System Alert: ' + followup_obj.issue.title, followup_obj.issue.title, followup_obj.comment, followup_obj.get_detail_url(request)) return HttpResponseRedirect( reverse('internal:issue_detail', kwargs={'pk': pk})) else: form = IssueFollowupForm() return render(request, 'internal/create_issue_followup.html', context={'form': form})
def __init__(self, name, config, goods_id_list, message_queue): threading.Thread.__init__(self) self.name = name self._running = True self._config = config self._sql_helper = SqlCdfBj() self._http_util = HttpUtil(config) self._mailer = Mailer(config) self._goods_id_list = goods_id_list # 负责查询的产品id self._update_time = time.time() self._ip_util = IpUtil(config) self._mutex = threading.Lock() self._message_queue = message_queue
def signup(request): if request.method=='POST': form = SignupForm(request.POST) if form.is_valid(): to_email = form.cleaned_data.get('email') print(to_email) if not to_email.endswith('@iitrpr.ac.in'): return render_message(request, 'Access Denied', 'Sorry ... only IIT Ropar domain emails can be used to sign up!') mailer = Mailer() user = form.save(commit=False) user.is_active = False user.username = to_email try: user.save() current_site = get_current_site_from_env() message = render_to_string('accounts/activate_account_email.html', { 'user': user, 'domain': current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) response=mailer.send_email(to_email, 'CDCRC User Registration Activation', message ) print("Mail Response: ", response) if(response=='fail'): raise Exception('Mail Service is down! 😢') return render_message(request, 'Email Confirmation', 'To activate your account, please see your email!' ) except IntegrityError as e: if 'UNIQUE constraint failed' in str(e): return render_message(request, 'User Exists', 'An account with this user already exists!' ) else: raise Exception('DB Integrity Error Occurred') except Exception as e: # Deleting the user user.delete() return render_message(request, 'An error occurred while creating your account', 'Trace: '+ str(e) ) else: form = SignupForm() return render(request, 'accounts/signup.html', {'form': form})
def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): to_email = form.cleaned_data.get('email') if not to_email.endswith('@iitrpr.ac.in'): return render_message( request, 'Access Denied', 'Sorry ... only IIT Ropar domain emails can be used to sign up!' ) mailer = Mailer() user = form.save(commit=False) user.is_active = False user.username = to_email try: user.save() current_site = get_current_site_from_env() message = render_to_string( 'accounts/activate_account_email.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) response = mailer._send_email( to_email, 'CDCRC User Registration Activation', message) print("Mail Response: ", response) if (response == 'fail'): raise Exception('Mail Service is down! 😢') return render_message( request, 'Email Confirmation', 'Thank you for joining CDCRC Internal Network. We have sent an activation link to your email. Once verified, you can access plethora of resources on the webpage. Hope to see you onboard soon!' ) except Exception as e: # Deleting the user if user.id != None: print("Deleting user: ", user.id) user.delete() return render_message( request, 'An error occurred while creating your account', 'Trace: ' + str(e)) else: form = SignupForm() return render(request, 'accounts/signup.html', {'form': form})
def post(self, request): form = LotCreditForm(request.POST) if form.is_valid(): lot_id = int(form.cleaned_data['lot_id']) lot = Lot.objects.get(id=lot_id) message_context = { 'name': form.cleaned_data['name'], 'phone': form.cleaned_data['phone'], 'email': form.cleaned_data['email'] } subject = 'Заявка на покупку в кредит, лот: ' + lot.name result = Mailer().send_template_message([settings.EMAIL_TO], 'credit_message', subject, message_context) return JsonResponse({'result': result}, safe=False)
def post(self, request): form = BrandForm(request.POST) if form.is_valid(): brand_id = int(form.cleaned_data['id']) brand = Brand.objects.get(id=brand_id) message_context = { 'name': form.cleaned_data['name'], 'phone': form.cleaned_data['phone'], 'email': form.cleaned_data['email'], 'message': form.cleaned_data['message'] } subject = 'Помощь в подборе ' + brand.name result = Mailer().send_template_message([settings.EMAIL_TO], 'brand_message', subject, message_context) return JsonResponse({'result': result}, safe=False)
def open_issue(request): if request.method == 'POST': pk = request.POST['issue_id'] issue = Issue.objects.get(pk=pk) issue.status = 'open' issue.save() mailer = Mailer() #send open alert to creator mailer.send_issue_open_alert_to_creator( [issue.creator.user.email], issue.creator.user.first_name + " " + issue.creator.user.last_name, request.user.first_name + " " + request.user.last_name, 'CDCRC System Alert: ' + issue.title, issue.title, issue.get_detail_url(request)) return HttpResponseRedirect( reverse('internal:issue_detail', kwargs={'pk': pk}))
def post(self, request): form = SupplierContactForm(request.POST) if form.is_valid(): supplier_id = int(form.cleaned_data['id']) supplier = Supplier.objects.get(id=supplier_id) message_context = { 'name': form.cleaned_data['name'], 'phone': form.cleaned_data['phone'], 'email': form.cleaned_data['email'], 'message': form.cleaned_data['message'] } subject = 'Cообщение для постащика ' + supplier.full_name result = Mailer().send_template_message([settings.EMAIL_TO], 'supplier_message', subject, message_context) return JsonResponse({'result': result}, safe=False)
def post(self, request): form = RegisterForm(request.POST, request.FILES) if form.is_valid(): new_user = User().add_user(form.cleaned_data) if new_user: Mailer().send(new_user.email, 'sign_up', context={"login": new_user.username}) return HttpResponseRedirect('/register/done/') else: message = 'Ошибка при регистрации пользователя: ' + str( form.cleaned_data) else: message = 'Ошибка при регистрации пользователя, проверьте поля ' return render(request, "user/register.html", { "form": form, "message": message, "context": Context.get(request) })
def create_issue(request): if request.method == 'POST': form = IssueForm(request.POST) if form.is_valid(): issue_obj = form.save(commit=False) issue_obj.status = 'open' team_member_profile = TeamMemberProfile.objects.get( user=request.user) issue_obj.creator = team_member_profile issue_obj.save() for assignee in request.POST.getlist('assignees'): issue_obj.assignees.add( TeamMemberProfile.objects.get(pk=int(assignee))) issue_obj.save() mailer = Mailer() #send mail alert to the creator of this issue mailer.send_issue_create_alert_to_creator( [request.user.email], request.user.first_name + " " + request.user.last_name, 'CDCRC System Alert: ' + issue_obj.title, issue_obj.title, issue_obj.priority.upper(), issue_obj.get_detail_url(request)) #send mail alert to the assignees for assignee in issue_obj.assignees.all(): mailer.send_issue_create_alert_to_assignee( [assignee.user.email], assignee.user.first_name + " " + assignee.user.last_name, 'CDCRC System Alert: ' + issue_obj.title, issue_obj.title, issue_obj.priority.upper(), issue_obj.get_detail_url(request)) return HttpResponseRedirect( reverse('internal:issue_detail', kwargs={'pk': issue_obj.pk})) else: form = IssueForm() return render(request, 'internal/create_issue.html', context={'form': form})
def send_email(self, subject="Finished", reason="Sanity Job Completed"): try: dir_path = "/tmp" email_to = self.email input_dict = {} input_dict["submitter"] = self.job.submitter input_dict["submit_id"] = self.job.submit_id input_dict["status"] = subject input_dict["reason"] = "{0} on testbed {1}".format( reason, self.job.testbed) subject = "N9k Sanity Job {0} Status: {1}".format( self.job.submit_id, subject) j2env = J2Env() template_file = 'job_submission_email.html' out_file = "{0}/{1}".format(dir_path, "req_creation_mail.html") # print(out_file) j2env.create_file(template_file, input_dict, out_file) mailer = Mailer(email_to) mailer.send_html_mail(subject, out_file) except BaseException as e: log.error("Exception in send mail:" + repr(e))