def send_mail(self): ''' Send emails ''' data = self.cleaned_data try: subject = F"[MillworkPioneers Website] Contact Form Request, by {data['name']}" message = F"""Somebody send an contact form request from website and below is the info: Name: {data['name']} Email: {data['email']} Phone: {data.get('phone', 'N/A')} Message: {data.get('message', 'No message')} """ from_email = settings.WORKING_EMAIL to_email = settings.WORKING_EMAIL send_mail(subject, message, from_email, [to_email], fail_silently=False) except Exception as e: logger.error("[Send email ERROR]: {}, type:{}".format(e, type(e))) else: logger.info("Success send email from :{}, email:{}".format( data['name'], data['email']))
def get_value(element, key, none_allowed=False): method_name = 'get_value' log_text = 'element[{}] - key[{}] - none_allowed[{}]'.format( str(element), str(key), str(none_allowed) ) log_utils.debug(log_text, method_name, __name__) if element is None: raise gen_exception.UndefinedParameterError('element') if key is None: raise gen_exception.UndefinedParameterError('key') try: value = element[key] except KeyError as error: log_text = '{} not defined in {}'.format(str(error), element) log_utils.error(log_text, method_name, __name__) value = None if value is None and not none_allowed: raise gen_exception.MissingValueError(key) log_text = 'value[{}]'.format(str(value)) log_utils.debug(log_text, method_name, __name__) return value
def vt_run(self, scan_type, QRY): url = f"{self.base_url}/{scan_type}/{QRY}" data = json.dumps(self.vt_connect(url)) json_resp = json.loads(data) if json_resp: good = 0 bad = 0 try: results = json_resp["data"]["attributes"] except AttributeError: pass else: if results["meaningful_name"]: logger.info("Filename: ", results["meaningful_name"]) for engine, result in results["last_analysis_results"].items(): if result["category"] == "malicious": bad += 1 logger.error( f"\u2718 {engine}: {result['category'].upper()}") else: good += 1 if bad == 0: logger.success( f"\u2714 {good} engines deemed '{QRY}' as harmless\n" ) # nopep8 else: logger.info(f"{bad} engines deemed '{QRY}' as malicious\n")
def grub(self, link) -> Union[dict, None]: """Получаем данные статьи по ссылке""" channel_name = self.__get_channel_name(link).lower() try: reader = getattr(self, channel_name) return reader.grub(link) except AttributeError: logger.error(f'Not found grabber for link: {link}') return None
def post(self, request): ''' Handle post ''' form = AskMailForm(request.POST) if form.is_valid(): form.send_mail() messages.success(request, "Successful subscribed!") return redirect('home') else: logger.error(F"[AshQuote ERROR form]: {form.errors}") messages.error(request, "Sorry wrong email, please try again") return redirect('home')
def _get_managed_element(element_type): method_name = "_get_managed_element" log_text = "element_type[{}]".format(str(element_type)) log_utils.debug(log_text, method_name, __name__) try: managed_element = dict_utils.get_value(MANAGED_ELEMENTS, element_type) except generic_exceptions.MissingValueError as mve: log_utils.error(mve, method_name, __name__) raise generic_exceptions.UnrecognizedElementTypeError(element_type) except generic_exceptions.UndefinedParameterError as upe: log_utils.error(upe, method_name, __name__) raise generic_exceptions.UnrecognizedElementTypeError(element_type) return managed_element
def geo_query_map(QRY): # Check if Geolite file exists geolite_check() # Used to resolve domains to ip address resolver = dns.resolver.Resolver() resolver.nameservers = ["1.1.1.1", "8.8.8.8", "8.8.4.4"] if DOMAIN.findall(QRY): try: response = resolver.query(QRY, "A") QRY = response.rrset[-1] map_maxmind(str(QRY)) except dns.resolver.NoAnswer as err: logger.error(f"[error] {err}") else: map_maxmind(QRY)
def vt_connect(self, url): try: resp = requests.get(url, headers=self.headers, timeout=5) resp.encoding = 'utf-8' if resp.status_code == 401: sys.exit("[error] Verify that you have provided a valid API key.") if resp.status_code != 200: print(f"[error] {resp.status_code} {responses[resp.status_code]}") #nopep8 else: return resp.json() except requests.exceptions.Timeout: logger.warning(f"[timeout] {url}") except requests.exceptions.HTTPError as err: logger.error(f"[error] {err}") except requests.exceptions.ConnectionError as err: logger.error(f"[error] {err}") except requests.exceptions.RequestException as err: logger.critical(f"[critical] {err}")
def post(self, request): form = CareerForm(request.POST, request.FILES) if form.is_valid(): attach_file = request.FILES.get("file", False) form.send_mail(attach_file) messages.success( request, "Thank you for your application! We'll contact you soon!") return redirect('home') else: logger.error(F"FOUND ERRORS ON CAREER FORM: {form.errors}") messages.error( request, "We found errors on form, please check them and try again!") messages.warning(request, F"{form.errors}") return render(request, self.template, { "careers_page": self.get_page_settings(), "form": CareerForm() })
def post(self, request): ''' Handle post ''' form = QuoteForm(request.POST, request.FILES) if form.is_valid(): quote = form.save() attach_file = request.FILES.get("file", False) form.send_mail(attach_file) messages.success(request, "Successful ask quote!") return redirect('home') else: logger.error(F"[AshQuote ERROR form]: {forms.errors}") messages.error( request, "We found some errors on the form, please fill up again and resend it" ) return redirect('home')
def send_mail(self, attach_file): ''' Custom send mail for career form ''' data = self.cleaned_data try: email = data["email"] name = data["name"] subject = F"[MillworkPioneers Website] Career application form, email:{data['email']}, name: {data['name']}" message = F"""Somebody send an application from website and below is the info: Name: {data['name']} Email: {data['email']} Phone: {data.get('phone', 'N/A')} Installation: {data['installation']} Union or UBC number: {data.get('union_ubc_number', 'N/A')} Office: {data['office']} Finish carpenter: {data['finish_carpenter']} Years of experience: {data.get('years_of_experience', 'N/A')} Message: {data.get('message', 'No message')} """ from_email = settings.WORKING_EMAIL to_email = settings.WORKING_EMAIL if settings.DEBUG: logger.info(F"EMAIL MSG: {message}") sent_email = EmailMultiAlternatives(subject, message, from_email, [to_email]) if attach_file: sent_email.attach(attach_file.name, attach_file.read(), attach_file.content_type) sent_email.send() import code code.interact(local=locals()) except Exception as e: logger.error("[Send email ERROR]: {}, type:{}".format(e, type(e))) else: logger.info("Success receive email:{}".format(email))
def send_mail(self): ''' Send email ''' try: email = self.cleaned_data["ask_email"] subject = "[MillworkPioneers Website] ASK EMAIL: {}".format(email) message = "Somebody ask for suscription with his/her email: {}".format( email) from_email = settings.WORKING_EMAIL to_email = settings.WORKING_EMAIL send_mail(subject, message, from_email, [to_email], fail_silently=False) except Exception as e: logger.error("[Send email ERROR]: {}, type:{}".format(e, type(e))) else: logger.info("Success receive email:{}".format(email))
def geo_query_map(QRY): # Check if Geolite file exists geolite_check() # Used to resolve domains to ip address resolver = dns.resolver.Resolver() resolver.nameservers = ['64.6.64.6', '64.6.65.6', '84.200.69.80', '84.200.70.40'] if DOMAIN.findall(QRY): try: response = resolver.query(QRY, 'A') QRY = response.rrset[-1] map_maxmind(str(QRY)) except dns.resolver.NoAnswer as err: logger.error(f"[error] {err}") except Exception as err: logger.warning(err) else: map_maxmind(QRY)
def vt_run(self, scan_type, QRY): url = f"{self.base_url}/{scan_type}/{QRY}" data = json.dumps(self.vt_connect(url)) json_resp = json.loads(data) if json_resp: good = 0 bad = 0 results = json_resp['data']['attributes'] try: if results['meaningful_name']: logger.info("Filename: ", results['meaningful_name']) except: pass for engine, result in results['last_analysis_results'].items(): if result['category'] == 'malicious': bad += 1 logger.error(f"\u2718 {engine}: {result['category'].upper()}") else: good += 1 if bad == 0: logger.success(f"\u2714 {good} engines deemed '{QRY}' as harmless\n") else: logger.info(f"{bad} engines deemed '{QRY}' as malicious\n")
def send_mail(self, attach_file): ''' Send mail ''' data = self.cleaned_data try: email = self.cleaned_data["email"] subject = "[MillworkPioneers Website] ASK QUOTE FORM: {}".format( email) message = F"""Somebody send a quote form from website and below is the info: Name: {data['name']} Email: {data['email']} Phone: {data.get('phone', 'N/A')} Company: {data['company']} Project: {data.get('project', 'N/A')} Bid Due: {data['bid_due'].strftime("%A, %d. %B %Y")} Start Date: {data['start_date'].strftime("%A, %d. %B %Y")} Prevailing Wage: {data.get('prevailing_wage', 'N/A')} Description: {data.get('description', 'No message')} """ from_email = settings.WORKING_EMAIL to_email = settings.WORKING_EMAIL sent_email = EmailMultiAlternatives(subject, message, from_email, [to_email]) if attach_file: sent_email.attach(attach_file.name, attach_file.read(), attach_file.content_type) sent_email.send() except Exception as e: logger.error("[Send email ERROR]: {}, type:{}".format(e, type(e))) else: logger.info("Success receive email:{}".format(email))