class WeatherInformation(): def __init__(self): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() self.owmapikey = self.configuration['WEATHER_API_KEY'] self.owm = pyowm.OWM(self.owmapikey) def get_weather_info(self,city): self.city=city observation = self.owm.weather_at_place(city) w = observation.get_weather() latlon_res = observation.get_location() lat = str(latlon_res.get_lat()) lon = str(latlon_res.get_lon()) wind_res = w.get_wind() wind_speed = str(wind_res.get('speed')) humidity = str(w.get_humidity()) celsius_result = w.get_temperature('celsius') temp_min_celsius = str(celsius_result.get('temp_min')) temp_max_celsius = str(celsius_result.get('temp_max')) fahrenheit_result = w.get_temperature('fahrenheit') temp_min_fahrenheit = str(fahrenheit_result.get('temp_min')) temp_max_fahrenheit = str(fahrenheit_result.get('temp_max')) self.bot_says = "Today the weather in " + city +" is :\n Maximum Temperature :"+temp_max_celsius+ " Degree Celsius"+".\n Minimum Temperature :"+temp_min_celsius+ " Degree Celsius" +": \n" + "Humidity :" + humidity + "%" return self.bot_says
def send_email_to_botuser_local(recepient_email, message, id): try: config_reader = ConfigReader() configuration = config_reader.read_config() # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = configuration['SENDER_EMAIL'] # storing the receivers email address msg['To'] = ",".join(recepient_email) # storing the subject msg['Subject'] = configuration['EMAIL_SUBJECT'] # string to store the body of the mail body = message # attach the body with the msg instance msg.attach(MIMEText(body, 'text')) filename = "report" + str(id) + ".jpg" attachment = open("LocalReport/" + filename, 'rb') # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload((attachment).read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) # attach the instance 'p' to instance 'msg' msg.attach(p) # creates SMTP session smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security smtp.starttls() # Authentication smtp.login(msg['From'], configuration['PASSWORD']) # Converts the Multipart msg into a string text = msg.as_string() # sending the mail smtp.sendmail(msg['From'], recepient_email, text) print('email send') # terminating the session smtp.quit() except Exception as e: print('the exception is ' + str(e))
class LuisConnect(ActivityHandler): def __init__(self): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() self.luis_app_id = self.configuration['LUIS_APP_ID'] self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY'] self.luis_endpoint = self.configuration['LUIS_ENDPOINT'] self.luis_app = LuisApplication(self.luis_app_id, self.luis_endpoint_key, self.luis_endpoint) self.luis_options = LuisPredictionOptions(include_all_intents=True, include_instance_data=True) self.luis_recognizer = LuisRecognizer( application=self.luis_app, prediction_options=self.luis_options, include_api_results=True) self.log = Log() async def on_message_activity(self, turn_context: TurnContext): weather_info = WeatherInformation() luis_result = await self.luis_recognizer.recognize(turn_context) result = luis_result.properties["luisResult"] json_str = json.loads((str(result.entities[0])).replace("'", "\"")) weather = weather_info.get_weather_info(json_str.get('entity')) self.log.write_log(sessionID='session1', log_message="Bot Says: " + str(weather)) await turn_context.send_activity(f"{weather}")
def news(req): sessionID = req.get("session") session = re.compile("sessions/(.*)") sessionID = session.findall(sessionID)[0] result = req.get("queryResult") user_says = result.get("queryText") try: config_reader = ConfigReader() configuration = config_reader.read_config() url = "http://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=" + \ configuration['NEWS_API'] res = requests.get(url) jsonRes = res.json() articles = jsonRes["articles"] news = list() for i in range(len(articles)): title = articles[i]["title"] author = articles[i]["author"] news_final = str(i + 1) + ". " + \ str(title) + " - " + str(author) news.append(news_final) fulfillmentText = "\n".join(news) bot_says = fulfillmentText return {"fulfillmentText": fulfillmentText} except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") except Exception as err: print(f"Other error occurred: {err}")
def webhook(): config_reader = ConfigReader() configuration = config_reader.read_config() req = request.get_json(silent=True, force=True) print("Request:") print(json.dumps(req, indent=4)) intent_check = req.get("queryResult").get("intent").get("displayName") if intent_check == "CountryCases_menu": res = getCountryName(req) elif intent_check == "StateCases_menu": res = getStateName(req) elif intent_check == "MyAreaCases_menu": res = getUserDetails(req) elif intent_check == "GlobalCases_menu": res = globalCases(req) elif intent_check == "indiaCases_menu": res = indiaCases(req) elif intent_check == "News": res = news(req) elif intent_check == "Helpline_Menu": res = helpLine(req) res = json.dumps(res, indent=4) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
class EmailSender: def send_email_to_student(self, recepient_email, message, mess): try: self.config_reader=ConfigReader() self.configuration=self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address self.msg['To'] = recepient_email # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail #body = "This will contain attachment" body=message + mess # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.msg['From'] , recepient_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is '+str(e))
class EmailSender: def sendEmailDistrict(self, name, email, district, confirmedCases, body): try: self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = "WeBlaze <*****@*****.**>" # storing the receivers email address self.msg['To'] = email # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail body = body.replace("name", name) body = body.replace("district", district) body = body.replace("num_cases", confirmedCases) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.configuration['SENDER_EMAIL'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.configuration['SENDER_EMAIL'], email, self.text) print("Email sent to district user!") # terminating the session self.smtp.quit() except Exception as e: print('the exception is ' + str(e))
def webhook(): config_reader = ConfigReader() configuration = config_reader.read_config() client = MongoClient( "mongodb+srv://your_username:"******"MONGO_PASSWORD"] + "@cluster0-p5lkb.mongodb.net/dialogflow?retryWrites=true&w=majority") db = client.dialogflow req = request.get_json(silent=True, force=True) print("Request:") print(json.dumps(req, indent=4)) intent_check = req.get("queryResult").get("intent").get("displayName") if (intent_check == "AboutCorona" or intent_check == "CountryCases" or intent_check == "CovidMap" or intent_check == "CovidTest" or intent_check == "Fallback" or intent_check == "Goodbye" or intent_check == "Menu" or intent_check == "MyAreaCases" or intent_check == "MythBuster" or intent_check == "Precaution" or intent_check == "QuarantineTips" or intent_check == "StateCases" or intent_check == "Symptoms" or intent_check == "Welcome"): res = saveToDb(req, db) elif intent_check == "GetCountryName": res = getCountryName(req, db) elif intent_check == "GetStateName": res = getStateName(req, db) elif intent_check == "GetUserDetails": res = getUserDetails(req, db) elif intent_check == "GlobalCases": res = globalCases(req, db) elif intent_check == "IndiaCases": res = indiaCases(req, db) elif intent_check == "News": res = news(req, db) res = json.dumps(res, indent=4) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
def covid_news(req): config_reader = ConfigReader() configuration = config_reader.read_config() news = [] url = "http://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=" + configuration[ 'NEWS'] response = rq.get(url) text = response.text a = json.loads(text) for i in range(20): title = a['articles'][i]['title'] author = a['articles'][i]['author'] news_feed = str(i + 1) + ". " + str(title) + " - " + str(author) news.append(news_feed) fulfillmentText_two = "\n".join(news) return fulfillmentText_two
def get_engine(): driver = [item for item in pyodbc.drivers()][-1] print(pyodbc.drivers()) try: config_reader = ConfigReader() configuration = config_reader.read_config() SERVER = configuration['SERVER'] DATABASE = configuration['DATABASE'] DRIVER = driver USERNAME = configuration['USERNAME'] PASSWORD = configuration['DB_PASSWORD'] DATABASE_CONNECTION = f'mssql://{USERNAME}:{PASSWORD}@{SERVER}/{DATABASE}?driver={DRIVER}' engine = create_engine(DATABASE_CONNECTION) print(engine) return engine except Exception as e: print('Exception occured in DB:' + str(e))
class EmailSender: def send_email_to_student(self, recepient_email): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() host = 'smtp.gmail.com' port = 587 message = MIMEMultipart() message['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address message['To'] = recepient_email self.p = MIMEBase('application', 'octet-stream') # storing the subject message['Subject'] = self.configuration['EMAIL_SUBJECT'] #message['To'] = "*****@*****.**" #message['From'] = "*****@*****.**" #message['subject'] = "Test01" #message['Password']='' body = "Hi You just ordered a Pizza from PizzaBot by Chayan!" html_body = MIMEText(body, 'plain') message.attach(html_body) username = "******" passw = '' conn = smtplib.SMTP(host, port) conn.ehlo() conn.starttls() conn.ehlo() conn.login(username, passw) conn.sendmail('*****@*****.**', message['To'], message.as_string()) #conn.sendmail(user, receiver, message.as_string()) conn.quit()
def upload_to_aws(local_file, bucket, s3_file, type): config_reader = ConfigReader() configuration = config_reader.read_config() ACCESS_KEY = configuration['AZ_ACCESS_KEY'] SECRET_KEY = configuration['AZ_SECRET_KEY'] s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) try: s3.upload_file(local_file, bucket, s3_file, ExtraArgs={'ContentType': type}) print("Upload Successful") return True except FileNotFoundError: print("The file was not found") return False except NoCredentialsError: print("Credentials not available") return False
def processRequest(req): config_reader = ConfigReader() configuration = config_reader.read_config() server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(configuration['SENDER_EMAIL'], configuration['PASSWORD']) print("login") sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") parameters = result.get("parameters") cust_name = parameters.get("name") intent = result.get("intent").get('displayName') action = req.get('queryResult').get('action') print(action) if (intent == 'information'): cust_contact = parameters.get("mobile") print(cust_contact) cust_email = parameters.get("email") print(cust_email) pin_code = parameters.get("pin_code") url = "https://api.postalpincode.in/pincode/" + str(pin_code) response = rq.get(url) test = response.text a = json.loads(test) try: district = a[0]['PostOffice'][0]['District'] print(district) state = a[0]['PostOffice'][0]['State'] print(state) country = a[0]['PostOffice'][0]['Country'] print(country) except Exception as e: print(e) covid_case = "https://api.covid19india.org/state_district_wise.json" response_one = rq.get(covid_case) test_one = response_one.text a_one = json.loads(test_one) case = a_one[state]['districtData'][district]['confirmed'] country_link = "https://corona.lmao.ninja/v2/countries" response_country = rq.get(country_link) test_country = response_country.text a_country = json.loads(test_country) print(len(a_country)) total = a_country[92]['cases'] active_case = a_country[92]['active'] death = a_country[92]['deaths'] subject = 'Covid-19 precaution and case' me = "Total Case in India {}\nActive Case in India {}\nTotal Deaths in India {}\n".format( total, active_case, death) me_one = "There are {} cases in {}\n\nTo prevent the spread of COVID-19:\n".format( case, district) point_one = "1.Clean your hands often. Use soap and water, or an alcohol-based hand rub.\n" point_two = "2.Maintain a safe distance from anyone who is coughing or sneezing.\n" point_three = "3.Don’t touch your eyes, nose or mouth.\n" point_four = "4.Cover your nose and mouth with your bent elbow or a tissue when you cough or sneeze.\n" point_five = "5.Stay home if you feel unwell.\n" point_six = "6.If you have a fever, a cough and difficulty breathing, seek medical attention. Call in advance.\n" point_seven = "7.Follow the directions of your local health authority." m = me + me_one + point_one + point_two + point_four + point_five + point_six + point_seven message_one = 'Subject: {}\n\n{}'.format(subject, m) try: server.sendmail(configuration['SENDER_EMAIL'], cust_email, message_one) except Exception as e: print("E-mail is not valid") print("Email has been sent to ", cust_email) server.quit()
class EmailSender: def send_email_to_student(self, recepient_email, message, cust_name, responseId, lstCases): try: self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address self.msg['To'] = ",".join(recepient_email) # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail #body = "This will contain attachment" imgUrl = os.path.join(os.path.abspath('static/images'), responseId + ".png") self.get_cases_bar(responseId, lstCases, imgUrl) fp = open(imgUrl, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') self.msg.attach(msgImage) body = message body = body.replace('cust_name', cust_name) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.msg['From'], recepient_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is ' + str(e)) def get_case_image(self, responseId, lstCases): exp_vals = lstCases[2::] exp_labels = [ "isolation_case_count", "total_case_count", "active_case_count", "discharged_case_count", "death_count" ] imgUrl = "C:/Mohan/" + responseId + ".jpg" plt.axis("equal") plt.pie(exp_vals, labels=exp_labels, radius=1.5, autopct='%0.1f%%', explode=[0, 0, 0, 0, 0]) plt.savefig(imgUrl, bbox_inches="tight", pad_inches=1, transparent=True) def get_cases_bar(self, responseId, lstCases, imgUrl): exp_vals = list(lstCases[0]) exp_vals = exp_vals[2::] exp_labels = [ "Isolation cases", "Total positive casse", "Active cases", "Discharged cases", "Death cases" ] fig, ax = plt.subplots() width = 0.35 # the width of the bars index = np.arange(len(exp_labels)) rects1 = ax.bar(index - width / 2, exp_vals, width) # this is for plotting purpose ax.set_ylabel('No of Cases') ax.set_title('Covid-19 cases report') ax.set_xticks(index) ax.set_xticklabels(exp_labels) def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate( '{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) # Set the x-axis limit plt.setp(ax.get_xticklabels(), fontsize=10, rotation='vertical') plt.savefig(imgUrl, bbox_inches="tight", pad_inches=1, transparent=True)
class EmailSender: def send_email_to_student(self, recepient_email, message): try: self.config_reader=ConfigReader() self.configuration=self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address self.msg['To'] = ",".join(recepient_email) # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail body = "This will contain attachment" body=message fileToSend = './DataScrap/corona_report.csv' # print(f'path in email file: {os.getcwd()}') ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset self.attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") self.attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(fileToSend, "rb") self.attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fileToSend, "rb") self.attachment = MIMEBase(maintype, subtype) self.attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(self.attachment) self.attachment.add_header("Content-Disposition", "attachment", filename='India Corona Report.csv') self.msg.attach(self.attachment) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.msg['From'] , recepient_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is '+str(e)) def send_email_to_support(self,cust_name,cust_email,cust_contact,course_name,body): try: self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the subject self.msg['Subject'] = self.configuration['SALES_TEAM_EMAIL_SUBJECT'] # string to store the body of the mail # body = "This will contain attachment" body = body.replace('cust_name',cust_name) body = body.replace('cust_contact', cust_contact) body = body.replace('cust_email', cust_email) # body = body.replace('cust_pincode', user_pincode) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.support_team_email = self.configuration['SALES_TEAM_EMAIL'] self.smtp.sendmail(self.msg['From'], self.support_team_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is ' + str(e))
class EmailSender: def send_email_to_user(self, recepient_email, message): try: self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address self.msg['To'] = recepient_email # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail #body = "This will contain attachment" body = message # attach the body with the msg instance self.msg.attach(MIMEText(body, "plain")) filename = "PreventionandManagementofCOVID19.pdf" # In same directory as script # Open PDF file in binary mode with open(filename, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) # Add attachment to message and convert message to string self.msg.attach(part) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.msg['From'], recepient_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is ' + str(e))
class EmailSender: def sendEmailToSupport(self, name, email, user_query): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = "iNeuron Megatron Chatbot <*****@*****.**>" # storing the receivers email address self.msg['To'] = "*****@*****.**" # storing the subject self.msg['Subject'] = "Customer query" body = """We have a customer query, which we were not able to answer as of now. Here is the query:- {}\n Customer-name:- {}\n Customer-email:- {}\n Please have a look into this. \n\n\n\n Regards, Team iNeuron """.format(user_query,name,email) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login( self.configuration['SENDER_EMAIL'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail( self.configuration['SENDER_EMAIL'], self.msg['To'], self.text) print("Email sent to support team!") # terminating the session self.smtp.quit() return "Email sent to support team!" def sendEmailToSupportForRecording(self, name, email, batch, day): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = "iNeuron Megatron Chatbot <*****@*****.**>" # storing the receivers email address self.msg['To'] = "*****@*****.**" # storing the subject self.msg['Subject'] = "Recording Uploading query" body = """We have a query that recording is not uploaded in dashboard. Here is the details:- Batch:- {} Day:- {} Customer-name:- {} Customer-email:- {} Please have a look into this. Regards, Team iNeuron """.format(batch,day,name,email) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login( self.configuration['SENDER_EMAIL'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail( self.configuration['SENDER_EMAIL'], self.msg['To'], self.text) print("Email sent to support team!") # terminating the session self.smtp.quit() return "Email sent to support team!" def sendEmailToSupportForFileNotFound(self, name, email, batch, topic): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = "iNeuron Megatron Chatbot <*****@*****.**>" # storing the receivers email address self.msg['To'] = "*****@*****.**" # storing the subject self.msg['Subject'] = "File not found query" body = """We have a query that File is not uploaded in dashboard. Here is the details:- Batch:- {} Topic:- {} Customer-name:- {} Customer-email:- {} Please have a look into this. Regards, Team iNeuron """.format(batch,topic,name,email) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login( self.configuration['SENDER_EMAIL'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail( self.configuration['SENDER_EMAIL'], self.msg['To'], self.text) print("Email sent to support team!") # terminating the session self.smtp.quit() return "Email sent to support team!" def sendEmailToSupportForDashboardAccess(self, name, email, batch): self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = "iNeuron Megatron Chatbot <*****@*****.**>" # storing the receivers email address self.msg['To'] = "*****@*****.**" # storing the subject self.msg['Subject'] = "Dashboard access query" body = """We have a query that some user has not received dashboard access. Here is the details:- Batch:- {} Customer-name:- {} Customer-email:- {} Please have a look into this. Regards, Team iNeuron """.format(batch,name,email) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login( self.configuration['SENDER_EMAIL'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail( self.configuration['SENDER_EMAIL'], self.msg['To'], self.text) print("Email sent to support team!") # terminating the session self.smtp.quit() return "Email sent to support team!"
class EmailSender: def send_email_to_student(self, recepient_email, message): # print("recepient_email",recepient_email) # print("message",message) try: self.config_reader=ConfigReader() self.configuration=self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address self.msg['To'] = ",".join(recepient_email) # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail #body = "This will contain attachment" body=message # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() print("sender_email xx",self.msg['From']) print("pass xx",self.configuration['PASSWORD']) # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.msg['From'] , recepient_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is email xx '+str(e)) def send_email_to_support(self,cust_name,cust_email,cust_contact,course_name,body): try: self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the subject self.msg['Subject'] = self.configuration['SALES_TEAM_EMAIL_SUBJECT'] # string to store the body of the mail # body = "This will contain attachment" body = body.replace('cust_name',cust_name) body = body.replace('cust_contact', cust_contact) body = body.replace('cust_email', cust_email) body = body.replace('course_name', course_name) # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.support_team_email = self.configuration['SALES_TEAM_EMAIL'] self.smtp.sendmail(self.msg['From'], self.support_team_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is ' + str(e))
from run_model_distilbert import DistilBERT_Model from config_reader import ConfigReader from api_file import Sent_Generation from web_scraping import scraping from database import mongo_connection import numpy as np import waitress from wsgiref import simple_server import warnings warnings.filterwarnings("ignore") app = Flask(__name__) # Load Config File config_reader = ConfigReader() configuration = config_reader.read_config() # Calling API File api_fun = Sent_Generation() # Calling scraping file scrape_data = scraping() # Calling model # model = ELMo_Model() model = DistilBERT_Model() # Connecting MongoDB database_connection = mongo_connection() # home page @app.route('/') @cross_origin()