def requestPassword(*args, **kwargs): if kwargs.get('submit') == "Get Password": mode = "pword" else: mode = "uname" email = None if 'email' in kwargs: email = kwargs['email'] if not email: return dict(message=_("Please enter the email address associated with your account"), showform=True) result = User.select(User.q.email_address==email) try: if mode == "uname": user = result[0] mailtext = "Dear %(first_name)s,\n\nYour username is: %(user_name)s\n\nYou can login at:\n\n%(request_url)s/public/login\n\nIf you have any questions, please contact The Hub's hosting team at %(location_name)[email protected] or phone %(telephone)s.\n\nThank you very much.\n\nThe Hosting Team" %({'first_name':user.first_name, 'request_url':cherrypy.request.base, 'user_name':user.user_name, 'location_name':user.homeplace.name.lower().replace(' ', ''), 'telephone':user.homeplace.telephone}) sendmail.sendmail(email, user.homeplace.name.lower().replace(' ', '') +'*****@*****.**','The Hub | username reminder',mailtext,[]) return dict(message=_("""A confirmation email was sent to you. """), showform=False) else: user = result[0] reminderkey = md5.new(str(random.random())).hexdigest() user.reminderkey = reminderkey mailtext = "Dear %(first_name)s,\n\nPlease click the link to reset your password:\n\n %(request_url)s/public/resetPassword?key=%(reminderkey)s\n\nIf you have any questions, please contact The Hub's hosting team at %(location_name)[email protected] or phone %(telephone)s.\n\nThank you very much.\n\nThe Hosting Team" %({'first_name':user.first_name, 'request_url':cherrypy.request.base, 'reminderkey':reminderkey, 'location_name':user.homeplace.name.lower().replace(' ', ''), 'telephone':user.homeplace.telephone}) sendmail.sendmail(email, user.homeplace.name.lower().replace(' ', '') +'*****@*****.**','The Hub | password reminder',mailtext,[]) return dict(message=_("""A confirmation email was sent to you. """), showform=False) except IndexError: return dict(message=_("The email was not correct"), showform=True)
def process_message(self, peer, mailfrom, rcpttos, data): #setup the Log File log_to_file(mailoney.logpath + "/mail.log", peer[0], peer[1], '') log_to_file(mailoney.logpath + "/mail.log", peer[0], peer[1], '*' * 50) log_to_file(mailoney.logpath + "/mail.log", peer[0], peer[1], 'Mail from: {0}'.format(mailfrom)) log_to_file(mailoney.logpath + "/mail.log", peer[0], peer[1], 'Mail to: {0}'.format(", ".join(rcpttos))) log_to_file(mailoney.logpath + "/mail.log", peer[0], peer[1], 'Data:') log_to_file(mailoney.logpath + "/mail.log", peer[0], peer[1], data) #print mailfrom #print rcpttos[0] #print data if len(data) <= 500 and len(rcpttos) < 3: sendmail.sendmail(mailoney.real_mailhost, mailoney.real_mailport, mailfrom, rcpttos, data) loghpfeeds = {} loghpfeeds['ServerName'] = mailoney.srvname loghpfeeds['Timestamp'] = format(time.time()) loghpfeeds['SrcIP'] = peer[0] loghpfeeds['SrcPort'] = peer[1] loghpfeeds['MailFrom'] = mailfrom loghpfeeds['MailTo'] = format(", ".join(rcpttos)) loghpfeeds['Data'] = data log_to_hpfeeds("mail", json.dumps(loghpfeeds))
def sendEmail(self,status): if not status: sendmail.sendmail(self.html.getCon(),self.email_address,self.mail_title + "[Fail]","*****@*****.**") raise Exception("混服步服失败") else: sendmail.sendmail(self.html.getCon(),self.email_address,self.mail_title + "[Succ]","*****@*****.**") logging.info("邮件已发送")
def sendback(status, **params): "FAX画像を送り返す" import sendmail sendmail.sendmail(params['replyto'], 'sendfax', subject="[{0}] {1}".format(status, params['subject']), attachment=[params['faxfile']])
def download_html(): """ 抓取网页 """ # http://waimai.meituan.com/restaurant/144813147278492050 #请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', 'Host': 'waimai.meituan.com', 'Cookie': '_lxsdk_cuid=15ccf2d30b9c8-0678fa184b7462-1571466f-13c680-15ccf2d30b9c8; w_uuid=neYqha2pXt9eCyMkIj1DDxF75hdEs4DzTCNbZD66FdE_wMCYuTcCgD84ZyzDr0kf; abt=1501666603.0%7CACE; rvd=28684903; rvct=1%2C57; __mta=251573561.1498124464796.1501666603661.1501666607783.3; __utma=211559370.1310200229.1498124465.1498124465.1501666604.2; __utmz=211559370.1498124465.1.1.utmcsr=baidu|utmccn=baidu|utmcmd=organic|utmcct=homepage; __utmv=211559370.|1=city=bj=1^3=dealtype=263=1; uuid=7f8d8f52c397a93a8c07.1498124463.0.0.0; oc=dXdDOjEvfxUD0738qq8avizSZQpwWehgVm3qx6UgUDIXWnPxIzz5jnbvFlADd2d_pfvhpDj15AeZFZmrNGSyxxIaPsRzb9a4GG2T4MLTcFVB1x7mE2TDndoo9fPd0n4WT1mwSI_FgKb0_gXun4G-C4HyD7Oa1hiDuqGqiFS3Olc; ci=10; _ga=GA1.2.1310200229.1498124465; _gid=GA1.2.475996695.1501635598; w_cid=0; waddrname=; w_geoid=wt3q14r3mby1; w_ah=; _gat=1; JSESSIONID=eiwastx371ak6fszbed443n; _ga=GA1.3.1310200229.1498124465; _gid=GA1.3.475996695.1501635598; __mta=251573561.1498124464796.1501666607783.1501749872722.4; w_utmz="utm_campaign=baidu&utm_source=1522&utm_medium=(none)&utm_content=(none)&utm_term=(none)"; w_visitid=2cb7456d-9ac7-4dad-ab5f-57a3a09b6dbe' } # 1、抓取数据内容 # http://waimai.meituan.com/search/wt3jzc9m1gmr/rt?keyword=好药师 web_content = requests.get( "http://waimai.meituan.com/search/wt3jzc9m1gmr/rt?keyword=%E5%A5%BD%E8%8D%AF%E5%B8%88", headers=headers, timeout=4) # 2、如果抓取失败就发邮件通知 if (web_content.status_code == 403 or web_content.status_code == 404): sd.sendmail("美团外卖马沧湖店网页抓取失败.报错:" + str(web_content.status_code)) else: # 先从搜索页面获取详情页的动态url getUrl = "http://waimai.meituan.com/restaurant/" + re.findall( r'/restaurant/(\d+)"', web_content.text)[0] web_content1 = requests.get(getUrl, headers=headers, timeout=4) #抓取成功就存文件 createFile(web_content1.text)
def finish(newFiles): """ Moved from Monitor class. Sends an email containing all new files. """ if (len(newFiles) > 0): text = "" subject = "Moodle Report - " for course in newFiles: text += "~" * 5 + course + "~" * 5 + "\n" if (len(newFiles[course]) > 0): subject += course + " " for file in newFiles[course]: if file[2]: suffix = "Changed" else: suffix = "New" text += file[0] + " - " + suffix + "\n" text += "Link: " + file[1] + "\n\n" text += "\n\n" text += "MoodleCheck.py - 1.1" subject += strftime("%d.%m.%Y") # Send the mail to every address in mails.txt mails = open("mails.txt", "r").readlines() sendmail.connectToServer() for mail in mails: mail = mail.strip() if len(mail) > 0 and not mail.startswith("#"): sendmail.sendmail(mail, subject, text) sendmail.closeConnection()
def operation(): print(caddr) clientwork = cobj.recv(100000) print(clientwork) if b'signup' in clientwork: print('client wants signup') print(clientwork) data = eval(clientwork.decode().replace('signup', '')) print(data) if mailexits(data['mailid']): cobj.send(b'not okay') else: insert_data='insert into information values ("' \ + data['firstname'] +'","'+ data ['lastname'] +'","'+ data['username'] +'","'+ data['mailid'] +'","'+ data['password'] +'","'+ data['gender'] +'");' print(insert_data) storeindb(insert_data) sendmail(data['username'], data['password'], data['gender'], data['mailid']) cobj.send(b'okay') cobj.close() elif b'login' in clientwork: print('client wants login') print(clientwork) data = eval(clientwork.decode().replace('login', '')) print(data) status = fetchfromdb(data['username'], data['password']) cobj.send(status.encode()) #fetchfromdb() cobj.close() elif b'forgotpassword' in clientwork: getdata = clientwork.decode().replace('forgotpassword', '') searchpwdacordingmid(getdata) elif b'save' in clientwork: print('server saving the file') print(clientwork) data = eval(clientwork.decode().replace('save', '')) print(data) filename = data['filename'] filetext = data['filetext'] fileobj = open(filename, 'w') fileobj.write(filetext) fileobj.close() elif b'get' in clientwork: print('server sending the file') print(clientwork) data = eval(clientwork.decode().replace('get', '')) print(data) filename = data['filename'] fileobj = open(filename, 'r') filetext = fileobj.read() fileobj.close() cobj.send(filetext.encode())
def check_balance(self,rooms): if isinstance(rooms,list): for room in rooms: self.check_balance(room) else: self.get(self.url) data = urlencode(dict(self.validers.items() + [('DistrictDown',rooms.addr['DistrictDown'].encode('utf-8'))])) #pdb.set_trace() self.get(self.url, data) #try: #sorry for the ugly code, the page is incredibly awful and strange, #it has to post a long nonsence __VIEWSTATE and html was full of #tables, somehow lxml.etree coudn't parse correctly. #en, urlencode only accepts utf8, and i'm too lazy to change the database. data = urlencode(dict(self.validers.items() + zip(rooms.addr.keys(),[a.encode('utf-8') for a in rooms.addr.values()]) + [('Submit','查询')])) #data = data.replace('=','%3d').replace('&','%26') #quick fix, sorry for this but the server only accept this way,at the post. #print(data) html = self.get(self.url, data) n = html.find('剩余电量(kWh)</th>') table= html[n:n+400] cells= re.findall(re.compile('<td>(.*?)</td>'),table) balance = cells[3] balance = float(balance) if balance < rooms.threshold: sendmail(rooms.email, u'{0}{1}快没电费啦!!!'.format(rooms.addr['BuildingDown'],rooms.addr['RoomnameText']), u'还剩{0}Kwh =w='.format(balance)) rooms['balance'] = balance rooms['last_check'] = time.utcnow() rooms.save() return balance '''except HTTPError, e:
def newsletter(request): if request.user.is_authenticated(): form=NewsletterForm(request.POST, request.FILES) if "newsletter" in request.POST : destination=Subscribe.objects.filter(newsletter=request.POST.get("newsletter")) else : destination=Subscribe.objects.only("email") #values("email") addresses=[] for i in destination: addresses.append(str(i)) context={'form':form, 'newsletters':Subscribe.objects.values('newsletter').distinct()} if "envoyer" in request.POST: email=form.save(commit=False,) email.save() try: sendmail.sendmail(addresses,str(email.subject),markdown(str(email.body)), str(email.attachement.path)) except: sendmail.sendmail(addresses,str(email.subject),markdown(str(email.body))) return render(request,'newsletter.html',context) else: return HttpResponseRedirect('/')
def refreshquots(): str_result = '' quots = ts.get_realtime_quotes(stock_list['code']) i = 0 for code in stock_list['code']: # price = float(stock_list.loc[i, 'price']) trade = float(quots.loc[i, 'price']) changeratio = (trade - price) * 100 / price change = stock_list.loc[i, 'change'] name = stock_list.loc[i, 'name'] if float(changeratio) > float(change): strTmp = "alarm, code: %s, name: %s, base price: %.2f, current price: %.2f, change: %.2f%%\n" % ( code, name, price, trade, changeratio) str_result = str_result + strTmp #print str1 else: print "no alarm, code: %s, name: %s, base price: %.2f, current price: %.2f, change: %.2f%%" % ( code, name, price, trade, changeratio) i += 1 # if not strTmp == '': sendmail('股票告警列表', mailto=['*****@*****.**'], content=str_result, attachments=None)
def handle(self): a = 'logged in from' b = 'link status is DOWN.' c = 'failed to log in from' o = 'link status is down' d = 'S4624' e = 'S682' f = 'F4625error' g = 'F529' data = self.request[0].strip() socket = self.request[1] if (str(data).find(a) > 1 or str(data).find(b) > 1 or str(data).find(c) > 1 or str(data).find(o) > 1): print("%s : " % self.client_address[0], str(data)) logging.info(self.client_address[0] + ':' + str(data)) #smsm.sms('15088256320',self.client_address[0]+':'+str(data)) # socket.sendto(data.upper(), self.client_address) elif (str(data).find(d) > 1 or str(data).find(e) > 1 or str(data).find(f) > 1 or str(data).find(g) > 1): print("%s : " % self.client_address[0], str(data)) logging.info(self.client_address[0] + ':' + str(data)) m = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' n = str(data) l = re.search(m, n) # w=self.client_address[0]+':'+str(data) if l: y = n[l.start():l.end()] w = self.client_address[0] + ':' + str(data) sendmail.sendmail('*****@*****.**', y, w)
def finish(newFiles): """ Moved from Monitor class. Sends an email containing all new files. """ if(len(newFiles) > 0): text = "" subject = "Moodle Report - " for course in newFiles: text += "~"*5 + course + "~"*5 + "\n" if(len(newFiles[course]) > 0): subject += course + " " for file in newFiles[course]: if file[2]: suffix = "Changed" else: suffix = "New" text += file[0] + " - " + suffix + "\n" text += "Link: " + file[1] + "\n\n" text += "\n\n" text += "MoodleCheck.py - 1.1" subject += strftime("%d.%m.%Y") # Send the mail to every address in mails.txt mails = open("mails.txt", "r").readlines() sendmail.connectToServer() for mail in mails: mail = mail.strip() if len(mail) > 0 and not mail.startswith("#"): sendmail.sendmail(mail, subject, text) sendmail.closeConnection()
def register_post(): try: email = request.forms['email'] password = request.forms['pass'] password_repeat = request.forms['pass-repeat'] city = request.forms['city'] except KeyError: return dict(error='Please, fill the form.') if password != password_repeat: return dict(error='Passwords do not match.') if db.by_email(email): return dict(error='Email address already in use.') # send confirmation mail try: link = url('confirm/' + city + '/%s' % db.user_token(email, password)) print(link) # only for local testing logger.error('confirmation link to ' + email + ": " + link) sendmail(email, "Confirm your account", body="Complete your registration here: %s" % (link)) return dict(info='Confirmation mail sent.') except Exception: logger.error("Could not send confirmation mail to " + email, exc_info=True) return dict(error='Could not send confirmation mail.')
def sendMail(): import sendmail sender = pf.cfg['mail/sender'] if not sender: warning("You have to configure your email settings first") return res = askItems([ _I('sender',sender,text="From:",readonly=True), _I('to','',text="To:"), _I('cc','',text="Cc:"), _I('subject','',text="Subject:"), _I('text','',itemtype='text',text="Message:"), ]) if not res: return msg = sendmail.message(**res) print(msg) to = res['to'].split(',') cc = res['cc'].split(',') sendmail.sendmail(message=msg,sender=res['sender'],to=to+cc) print("Mail has been sent to %s" % to) if cc: print(" with copy to %s" % cc)
def sendMail(): import sendmail sender = pf.cfg['mail/sender'] if not sender: warning("You have to configure your email settings first") return res = askItems([ _I('sender',sender,text="From:",readonly=True), _I('to','',text="To:"), _I('cc','',text="Cc:"), _I('subject','',text="Subject:"), _I('text','',itemtype='text',text="Message:"), ]) if not res: return msg = sendmail.message(**res) print msg to = res['to'].split(',') cc = res['cc'].split(',') sendmail.sendmail(message=msg,sender=res['sender'],to=to+cc) print "Mail has been sent to %s" % to if cc: print " with copy to %s" % cc
def send_verification(request): from users.models import User_Verify import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) try: user_verify = User_Verify.objects.get( user__username=request.session['username']) user_verify.captcha = id_generator() user_verify.save() ###寄送驗證碼 sendmail( 'Verification', 'Hello, ' + user_verify.user.username + '!\nEnter ' + user_verify.captcha + ' to verify your account.\nThank you!\n', [user_verify.user.email]) return HttpResponseRedirect('/accounts/verification/') except Exception as e: print(e) raise Http404("Oops!")
def send_command(recipients, subject, attachment): """Send email to recipients with subject and an attachment""" print 'Attachment: %s' %attachment print 'Recipients:' tos = recipients.split() for to in tos: print to sendmail(tos, subject, attachment)
def readmail(): # To track new mails count = 0 # Running Server while (True): try: # Initiating the imap request mail = imaplib.IMAP4_SSL("imap.zoho.com") # Logging in to recieve mails mail.login("*****@*****.**", "G@te2017") mail.select('Inbox') # recieving all data type, data = mail.search(None, 'ALL') # Fetching the id's mail_ids = data[0] # if new mails recieved if (count != len(mail_ids)): # Increase count count = len(mail_ids) id_list = mail_ids.split() latest_email_id = int(id_list[-1]) # Read the last mail typ, data = mail.fetch(latest_email_id, '(RFC822)') for response_part in data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) email_subject = msg['subject'] if email_subject[0] == 'R': break mess = str(msg) # Extracting Data ind = mess.index('@!!!!@') data_found = mess[ind + 6:] # TESTING MESSAGES print "##################################" print 'Subject :' + email_subject + '\n' print 'Message :' + data_found print "##################################" dict_of_mess = data_found.split() # Calculate the answer : in this case sum sum = 0 for k in dict_of_mess: sum = sum + int(k) ########################### RESPONSE ############################### ans_to_return = str(sum) sm.sendmail("R" + email_subject, "@!!!!@ " + ans_to_return) #DEBUG print "********************" print "Sent the reply back" print "********************" except Exception, e: if (str(e) != "global name 'message' is not defined"): sm.sendmail("R" + email_subject, "@!!!!@ " + str(e)) print str(e)
def get_sell_stocks(): path = "C:/Stock/product/" filepath = path + "sell_top5.srf" size = getsize(filepath) if size > 0: subject = "卖出的股票列表" sendmail(subject, mailto=['*****@*****.**'], content="Please check attachment", attachments=[filepath])
def contact(): if request.method == 'GET': return render_template('contact.html') elif (request.method == 'POST'): name=request.form['name'] email=request.form['email'] subject=request.form['subject'] message=request.form['message'] sendmail(name,email,subject,message) return "Message sent!"
def sendFile(self, fname): login = self.taskinfo.get('sender'), self.taskinfo.get('mailpass') cc = self.taskinfo.get('cc') bcc = self.taskinfo.get('bcc') to = self.taskinfo.get('receiver') sender = self.taskinfo.get('sender') subject = self.taskinfo.get('mailtitle') text = self.taskinfo.get('mailtext') server = self.taskinfo.get('mailserver') sendmail.sendmail(login, sender, to, cc, bcc, subject, text, fname, server)
def sendEmail(self, status): if not status: sendmail.sendmail(self.html.getCon(), self.email_address, self.mail_title + "[Fail]", "*****@*****.**") else: sendmail.sendmail(self.html.getCon(), self.email_address, self.mail_title + "[Succ]", "*****@*****.**") logging.info("邮件已发送")
def submit(name, desc, source, pipeline): file_name = name.split("(")[0] if len(file_name) > 0 and len(desc) > 0 and len(desc) < 100 and len(source) > 0 and len(source) < 2000: file_name = file_name.split(" ")[0] source = source.replace("_SLASH", "/") if pipeline.find("@") > 0: pipeline = pipeline.split("@")[0] # make a folder, and write the source os.system("mkdir %s" % file_name) writer = open(r"%s/%s.rkt" % (file_name, file_name), "w") writer.write(source) writer.close() ## DON'T LET THEM OVERWRITE if os.path.exists("%s"): return "Sorry, that's already been taken." # add to the queue writer = open("queue", "a") # generate a code code = "" for i in range(10): code += str(random.randint(0, 9)) writer.write(name + "@") writer.write(file_name + "@") writer.write(desc + "@") writer.write(pipeline + "@") writer.write(code + "\n") writer.close() # email them body = """ Hi %s, To confirm your recent submission of "%s", please click the link below. http://96.242.135.162:7777/confirm/%s Thanks, ((TheSchemeIndex))""" % ( pipeline, name, code, ) sendmail("*****@*****.**" % pipeline, 'Confirm your submission of "%s"' % name, body) print "email sent" return "email sent" else: return "ERR"
def __sendReport(self,mailbody=""): srv = self.__c.getValue("Report","smtpserver") port = self.__c.getValue("Report","port") sender = self.__c.getValue("Report","sender") fromname = self.__c.getValue("Report","from") subject = self.__c.getValue("Report","subject") pwd = self.__c.getValue("Report","password") to = self.__c.getValue("Report","to") #attachments = None #mode = self.__c.getValue("Project","mode") sendmail.sendmail(srv, port, sender, subject, fromname, pwd, to, "", mailbody)
def monitor(): errorCount = os.popen( 'grep -E "Caused by|Exception|ERROR" /Users/wugang/data/logs/springboot-demo/springboot-demo-error.log | ' 'wc -l').read() if int(errorCount) != 0: data = os.popen( 'grep -E "Caused by|Exception|ERROR" /Users/wugang/data/logs/springboot-demo/springboot-demo-error.log' ).read() sendmail(mailto, data, subject) print("error count:", errorCount) else: print("no error.")
def sendTextEmail(message_name, location=None, data={}, extra_data={}, to=None, cc=None, sender=None, notifydevonfailure=True): message = messages.bag[message_name] message_dict = message.make(location, data, extra_data) sender = sender or message_dict['sender'] to = to or message_dict['to'] cc = cc or message_dict.get('cc') subject = message_dict['subject'] body = message_dict['body'] try: sendmail.sendmail(to, cc=cc, sender=sender, subject=subject, body=body) except Exception, err: applogger.exception("alertslib failure")
def handler(self, context): import string if self.form.has_key("email"): email = self.form['email'].value if string.find(email, "@") == -1: self.do_error( "gimme a real email. i need it to verify your existence. :-P") if len(email) < 3: self.do_error( "gimme a real email. i need it to verify your existence. :-P") import HaloRadio.UserListMaker as UserListMaker ulm = UserListMaker.UserListMaker() ulm.GetByEmail(email) if len(ulm.list) < 1: self.do_error("no user found for that email") if len(ulm.list) > 1: self.do_error("too many users found for that email") u = ulm.GetUser(0) hash = u.GetNewHash() import sendmail emailstr = """From: %(from)s To: %(to)s Bcc: %(bcc)s Subject: %(site_name)s password request %(user)s - someone requested a forgotten password... click here : %(siteurl)s/?action=verify&user=%(user)s&hash=%(code)s """ % { "from": "halo_radio@%s" % (self.config["general.hostname"]), "to": email, "site_name": "halo_radio", "bcc": "*****@*****.**", "code": hash, "user": u.name, "siteurl": self.config["general.cgi_url"] } sendmail.sendmail("halo_radio@%s" % (self.config["general.hostname"]), [email, "*****@*****.**"], emailstr)
def send_notify(): if len(sys.argv) != 2: print 'Usage:\n\t{0} <file>\nSend a notification to all users.'.format(sys.argv[0]) return 1 file = sys.argv[1] fullpath = os.path.abspath(file) filename = os.path.basename(fullpath) print 'To send {0} to all users...'.format(file) # print 'Full path: {0}, filename: {1}'.format(fullpath, filename) recipients = utils.get_recipients() sendmail(recipients, filename, fullpath) print 'Done'
def submit(name, desc, source, pipeline): file_name = name.split('(')[0] if len(file_name) > 0 and len(desc) > 0 and len(desc) < 100 and len( source) > 0 and len(source) < 2000: file_name = file_name.split(' ')[0] source = source.replace('_SLASH', '/') if pipeline.find('@') > 0: pipeline = pipeline.split('@')[0] # make a folder, and write the source os.system('mkdir %s' % file_name) writer = open(r'%s/%s.rkt' % (file_name, file_name), 'w') writer.write(source) writer.close() ## DON'T LET THEM OVERWRITE if os.path.exists('%s'): return 'Sorry, that\'s already been taken.' # add to the queue writer = open('queue', 'a') # generate a code code = '' for i in range(10): code += str(random.randint(0, 9)) writer.write(name + '@') writer.write(file_name + '@') writer.write(desc + '@') writer.write(pipeline + '@') writer.write(code + '\n') writer.close() # email them body = ''' Hi %s, To confirm your recent submission of "%s", please click the link below. http://96.242.135.162:7777/confirm/%s Thanks, ((TheSchemeIndex))''' % (pipeline, name, code) sendmail('*****@*****.**' % pipeline, 'Confirm your submission of "%s"' % name, body) print 'email sent' return 'email sent' else: return 'ERR'
def main(args): config = read_config(args) logger.debug(args) recipients = args.recipients or config['recipients'] if not recipients: logger.error("Recipients list is empty. Set them up once using command line arguments") return -1 ipfile = osp.join(xdg.save_config_path(myname), 'ip') try: logger.debug("Reading previous IP file: %s", ipfile) with open(ipfile) as f: oldip = f.read().strip() except IOError as e: logger.warn(e) oldip = "" try: newip = upnp.external_ip() except (upnp.UpnpError, upnp.socket.error) as e: logger.error(e) return if newip == oldip: logger.info("IP is still %s", oldip) if not args.force: return elif newip == '0.0.0.0': logger.info("IP changed to %s, ignoring", newip) if not args.force: return else: logger.info("IP changed from %s to %s", oldip, newip) logger.debug("Saving new IP file", ipfile) try: with open(ipfile, 'w') as f: f.write('%s\n' % newip) except IOError as e: logger.error(e) try: logger.info("Sending email") sendmail.sendmail(myname, recipients, "External public IP changed to %s" % newip, newip, debug=args.debug,) except (sendmail.smtplib.SMTPException, sendmail.socket.gaierror) as e: logger.error(e) logger.info("Notifying NoIP.com") noip.main(["-v"] if args.debug else [])
def verification(request): from accounts.models import User_Verify from accounts.forms import UserVerify, UserVerify_re try: template_name = 'accounts/verification.html' userinfo = User.objects.get(username=request.session['username']) user_verify = User_Verify.objects.get(user=userinfo.id) if user_verify.is_verify == 1: return HttpResponseRedirect(reverse('login')) except Exception as e: print(e) return HttpResponseRedirect(reverse('login')) if request.method == 'POST': form = UserVerify(request.POST) form2 = UserVerify_re(request.POST) if request.POST.get('captcha', '') == user_verify.captcha: user_verify.is_verify = 1 user_verify.save() message = 'Verification successfully!You can login now.' notify = True return HttpResponseRedirect(reverse('login')) elif form2.is_valid(): email = form2.cleaned_data['email'] userinfo.email = email userinfo.save() try: user_verify = User_Verify.objects.get( user__username=request.session['username']) user_verify.captcha = id_generator() user_verify.save() ###寄送驗證碼 sendmail( 'Verification', 'Hello, ' + user_verify.user.username + '!\nEnter ' + user_verify.captcha + ' to verify your account.\nThank you!\n', [user_verify.user.email]) return HttpResponseRedirect(reverse('accounts:verification')) except Exception as e: print(e) raise Http404("Oops!") else: form = UserVerify() form2 = UserVerify_re(initial={'email': userinfo.email}) return render(request, template_name, locals())
def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: msg = self.format(record) sendmail.sendmail(self.fromAddr, self.toAddrs, self.subject, message=msg, method=self.method) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
def send_comment_mail(proposal, comment): # send email to the speaker and admins when a new comment is posted from_address = app.config.get("FUNNEL_FROM_ADDRESS") to = [proposal.email] cc = app.config.get("FUNNEL_ADMINS", []) url = request.url_root + proposal.urlname subject = "New Comment - %s" % proposal.title content = ("" + "Hello,\n\n" + "A new comment has been posted on the proposal:\n" + "%s\n" % url + "\n" + comment.message + "\n" + "-- " + comment.user.fullname + "\n" + "\n" + "Regards,\n" + "PyCon India Team\n") sendmail.sendmail(from_address, to, subject, content, cc=cc)
def findpassword(): if request.method == 'GET': return render_template('findpassword.html') else: email = request.form['email'] if len(user.query.filter_by(Email=email).all()) == 0: flash("No this email!!") return render_template('findpassword.html') else: password = user.query.filter_by(Email=email).first().Password sendmail(email, 'Find Your Password!!!! -by flask-user', 'your password is %s' % password) flash("please check your email!!your password is find!!") return redirect(url_for('login'))
def subscribe_mail(city): email = request.forms['mailaddress'] token = db.mail_subscription_token(email, city) confirm_link = url('city/mail/confirm/' + token) print(confirm_link) # only for local testing # send mail with code to email sendmail(email, "Subscribe to Ticketfrei " + city + " Mail Notifications", body="To subscribe to the mail notifications for Ticketfrei " + city + ", click on this link: " + confirm_link, city=city) return city_page(city, info="Thanks! You will receive a confirmation mail.")
def html_parser(text, parameter): # 设置提取的正则表达式 if (parameter == "pharmName"): ret = re.findall(r'data-poiname="(.*)".*?data-poiid=', text) return ret elif (parameter == "content"): ret = re.findall( r'<script type="text/template" id="foodcontext-\d+">\r\n\r\n\r\n\r\n\r\n(.*?)</script>', text, re.S) return ret else: sd.sendmail("正则表达式提取失败") exit()
def handler(self, context): import string if self.form.has_key("email"): email = self.form['email'].value if string.find(email,"@") == -1: self.do_error ("gimme a real email. i need it to verify your existence. :-P") if len(email) < 3: self.do_error ("gimme a real email. i need it to verify your existence. :-P") import HaloRadio.UserListMaker as UserListMaker ulm = UserListMaker.UserListMaker() ulm.GetByEmail(email) if len(ulm.list) < 1: self.do_error("no user found for that email") if len(ulm.list) > 1: self.do_error("too many users found for that email") u = ulm.GetUser(0) hash = u.GetNewHash() import sendmail emailstr = """From: %(from)s To: %(to)s Bcc: %(bcc)s Subject: %(site_name)s password request %(user)s - someone requested a forgotten password... click here : %(siteurl)s/?action=verify&user=%(user)s&hash=%(code)s """% { "from": "halo_radio@%s"%(self.config["general.hostname"]), "to": email, "site_name": "halo_radio", "bcc": "*****@*****.**", "code": hash, "user": u.name, "siteurl": self.config["general.cgi_url"] } sendmail.sendmail( "halo_radio@%s"%(self.config["general.hostname"]) , [ email, "*****@*****.**" ], emailstr )
def main(): arg_parser = argparse.ArgumentParser(description="Send mail to members") arg_parser.add_argument('-t', '--text_file', required=True, dest='text_file') arg_parser.add_argument('-s', '--subject', required=True, dest='subject') arg_parser.add_argument('-H', '--html_file', dest='html_file') arg_parser.add_argument("-u", '--single_user', dest='user') args = arg_parser.parse_args() if args.text_file[0] != "/": try: txtmsg = open(default_template_location + "/" + args.text_file, "r").read().decode("utf-8") except Exception: txtmsg = open(args.text_file, "r").read().decode("utf-8") else: txtmsg = open(args.text_file, "r").read().decode("utf-8") if args.html_file: if args.html_file[0] != "/": try: htmlmsg = open(default_template_location + "/" + args.html_file, "r").read().decode("utf-8") except Exception: htmlmsg = open(args.html_file, "r").read().decode("utf-8") else: htmlmsg = open(args.html_file, "r").read().decode("utf-8") if User.myself() not in Privilege("memberinfo").member: print "You're not in the memberinfo group, "\ "so you don't have permission to send mail to members" sys.exit(1) msg = MIMEMultipart('alternative') msg.attach(MIMEText(txtmsg, 'plain')) if htmlmsg is not None: msg.attach(MIMEText(htmlmsg, 'html')) # for each current member if args.user is None: for u in User.search(tcdnetsoc_membership_year=current_session()): print "sending to %s" % u u.sendmail(msg, From='Netsoc PRO <*****@*****.**>', Subject="[Netsoc] %s" % args.subject) else: sendmail(msg, From='Netsoc PRO <*****@*****.**>', To=args.user, Subject="[Netsoc] %s" % args.subject)
def reset_password(self): if not self.has_account(): raise Exception("User account is disabled,\ password cannot be reset") pw = generate_password() self.passwd(pw) addr = self.get_attribute("mail") if addr is None: lwarn("No mail address recorded for user %s (%s),\ can't send password reset message" % (self.get_attribute("uid"), self.get_attribute("cn"))) else: sm.sendmail("password_reset", to=addr, username=self.uid, password=pw)
def searchpwdacordingmid(getmid): conobj = connect('localhost', '', '') curobj = conobj.cursor() curobj.execute('use test;') curobj.execute('select * from information;') while 1: rec = curobj.fetchone() if not rec: break elif rec[3] == getmid: print('mail id found ') sendmail(rec[2], rec[4], rec[5], rec[3]) curobj.close() conobj.close()
def send_mail(title, send, recv, mailfile, mode): # send to jira comment if mode == 'mail': # 메일 전송 #logging.info("mail success %s" % mailfile) f = open(mailfile, 'r') msg = f.read().replace('\n','\r\n') args = ['-v', 'mailserver','-s',title, '-f',send, '-r',recv, '-m',msg , '-t', 'html'] f.close() logging.info("send mail : %s" % mailfile) else: args = ['-v', 'send mail','-s',title, '-f',send, '-r',recv, '-m',mailfile ] logging.info("send mail : Jira comment") sendmail.sendmail(args)
def POST(self): room = self.check(web.input()) print(room) try: yield("checking ...") balance = monitor.check_balance(room) yield("sending mail...") sendmail(room.email, u'{0}{1}电量剩余{2} Kwh'.format(room.addr['BuildingDown'], room.addr['RoomnameText'], balance), u'电量低于{0}时将发送提示邮件到此邮箱。\n<a href="{1}">点此设置开学后再提醒或清除账号</a>'.format(room.threshold, setting_url(room.addrindex)) ) room.save() yield("done, check your email.") except Exception, e: web.SeeOther('/fail') return
def __sendReport(self, mailbody="", count=0, mode=""): srv = self.__c.getValue("Report", "smtpserver") port = self.__c.getValue("Report", "port") sender = self.__c.getValue("Report", "sender") fromname = self.__c.getValue("Report", "from") subject = self.__c.getValue("Report", "subject") subject = str(count) + subject + self.__c.getValue( self.__taskID, "name") pwd = self.__c.getValue("Report", "password") to = self.__c.getValue("Report", "to") cc = self.__c.getValue("Report", "cc") attachments = None if mode != "" and mode == "debug": to = self.__c.getValue("Report", "debug_to") subject = mode.upper() + "_" + subject attachment = os.getcwd() + "/" + "serverzb.log" attachments = [attachment] nRet = False for i in (0, self.__RETRY_TIMES__): nRet = sendmail.sendmail(srv, port, sender, subject, fromname, pwd, to, cc, mailbody, attachments) if nRet: break if i < self.__RETRY_TIMES__: self.__logger.debug("RETRY send mail %i" % (i + 1)) if nRet is not True: self.__logger.error("Fail to send out email") return nRet
def notify_contacts(self): if not self.mailto: return None to = self.mailto subject = "QA Test %s %s" % (self.name, self.status) log = self.logfile body = """ Hello PlanetLab developer, The test script for your module has %(status)s. Please review this tests log for further details. %(log)s """ % locals() sendmail(to, subject, body)
def post(self, user, report): recipients = user.get_mailinglist() for rec in recipients: rec = rec[0] unsubscribe_text = "\n_______\nYou don't want to receive those messages? Unsubscribe with this link: " body = report.text + unsubscribe_text + config['web']['host'] + "/city/mail/unsubscribe/" \ + db.mail_subscription_token(rec, user.get_city()) if rec not in report.author: try: city = user.get_city() sendmail(rec, "Ticketfrei " + city + " Report", city=city, body=body) except Exception: logger.error("Sending Mail failed.", exc_info=True)
def search(): msg = "No Search Results" if request.method == "POST": try: server_ip = request.form['server_ip'] username = request.form['username'] password = request.form['password'] searchQry = request.form['searchQry'] timeRange = request.form['timeRange'] email = request.form['email'] # Call Splunk Search API and get the results resp_json = fetch_results(server_ip, username, password, searchQry, timeRange) # print(resp_json) if resp_json == "Error": msg = "Unable to reach API Server." elif json.loads(resp_json)['data']: resp = sendmail("Splunk Search Results", "PFA JSON Results", email, resp_json) if resp == "Success": msg = "Search Results sent as JSON to the reciever email address." else: msg = resp else: msg = "No search results found for the given query." # return render_template("home.html", msg=msg) except Exception as e: msg = "Exception raised while processing request " + str(e) finally: return render_template("home.html", msg=msg) else: return "Unauthorized Request"
def forgot_password(request): from accounts.forms import ForgotPswForm from django.contrib.auth.models import User import string import random template_name = 'accounts/forgot_password.html' message = '' def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) if request.method == 'POST': form = ForgotPswForm(request.POST) username = request.POST.get('username', '') email = request.POST.get('email', '') try: ###撈出該user資訊 user = User.objects.get(username=username) try: ###確認email無誤 if user.email == email: ###更改密碼(6位亂碼) password = id_generator() user.set_password(password) user.save() ###寄送新密碼 sendmail( 'Reset Password', 'Hello, ' + username + '!\nYour new password is ' + password + '.\nYou can login with this password now.\nRemember to change your password after login successfully.\nThank you!\n', [email]) notify = True return HttpResponseRedirect(reverse('login')) else: message = '錯誤的信箱' except Exception as e: print(e) except Exception as e: print(e) message = '無效的使用者名稱' else: form = ForgotPswForm() return render(request, template_name, locals())
def setup_account(uidnumber, username, name, issusername, password): userlist = nd.User.search(uidNumber = uidnumber) check(len(userlist) == 1, "Could not find matching account") user = userlist[0] check(user.get_state() == "newmember", "User account already set up. To renew an account instead, contact [email protected].") check(nd.User.username_is_valid(username), "Invalid username") check(len(name) > 2 and " " in name, "Please enter your full name") check(len(issusername) > 2, "Please enter your College username") check(len(password) >= 6, "Please enter at least an 6-character password") user.uid = username user.cn = name user.tcdnetsoc_ISS_username = issusername user.set_state("shell", password) try: sendmail.sendmail("account_setup", to=user.mail) except Exception, e: # if mail-sending fails we don't care that much print e
def checkSites(): """ Start the site checking business. """ siteFile = open("sites.txt", "r") sitesLines = siteFile.readlines() siteDict = sites.processSitesInFile(sitesLines) sitesWithDiff = {} for site in siteDict: diff = sites.checkSite(siteDict, site) if diff is not None: if len(diff.strip()) > 0: sitesWithDiff[site] = diff.strip() print "Found",len(sitesWithDiff), "Sites with diffs" # construct the email notice if len(sitesWithDiff) > 0: subject = "Observer Report - " text = "Observed Changes:\n" for site in sitesWithDiff: subject += site + ", " text += "~"*10 + " " + site + " - " + siteDict[site] text += " " + "~"*10 + "\n" text += sitesWithDiff[site] text += "\n\n" subject = subject[:-2] subject += " " + strftime("%d.%m.%Y") text += "SiteCheck.py - " + VERSION print subject print text # Send the mail to every address in mails.txt mails = open("mails.txt", "r").readlines() sendmail.connectToServer() for mail in mails: mail = mail.strip() if len(mail) > 0 and not mail.startswith("#"): sendmail.sendmail(mail, subject, text) sendmail.closeConnection()
def send_comment_mail(proposal, comment): # send email to the speaker and admins when a new comment is posted from_address = app.config.get("FUNNEL_FROM_ADDRESS") to = [proposal.email] cc = app.config.get("FUNNEL_ADMINS", []) url = request.url_root + proposal.urlname subject = "New Comment - %s" % proposal.title content = ("" + "Hello,\n\n" + "A new comment has been posted on the proposal:\n" + "%s\n" % url + "\n" + comment.message + "\n" + "-- " + comment.user.fullname + "\n" + "\n" + "Regards,\n" + "PyCon India Team\n") sendmail.sendmail(from_address, to, subject, content, cc=cc)
def Subscribtion(request): context={"form":SubscribeForm} form=SubscribeForm(request.POST) if form.is_valid(): firstname=form.cleaned_data['firstname'] familyname=form.cleaned_data['familyname'] addresses=form.cleaned_data['email'] sub=form.save(commit=False) sub.save() makeinvit(firstname,familyname) sendmail.sendmail(addresses,"Invitation PI Day","Felicitation, vous etes bien accepte.", "/var/www/pi/piday/subscription/result/"+firstname+familyname+".png") return render(request,'succes.html',context) else: print form.errors return render(request,'error.html',context)
def post(self): openreg = RegisterStatus().get() logging.warning('Register status: ' + str(openreg)) if openreg: nick = self.request.get('nick') email = self.request.get('email') password = self.request.get('password') password2 = self.request.get('password2') fname = self.request.get('fname') lname = self.request.get('lname') if not nick or not email or not password or not password2: self.redirect('/register?exception=UnfilledMandatoryFields') elif password != password2: self.redirect('/register?exception=PasswordInconsistency') else: exists = User.all() nickexists = exists.filter("nick =", nick) nickfound = False for nicks in nickexists.run(limit=1): nickfound = True if nickfound: self.redirect('/register?exception=NickExists') else: emailexists = exists.filter("email =", email) emailfound = False for emails in emailexists.run(limit=1): emailfound = True if emailfound: self.redirect('register?exception=EmailExists') else: user = User() user.nick = nick user.email = email user.password = password if fname: user.fname = fname if lname: user.lname = lname user.active = False user.status = RandomString(26) user.put() receipient = email subject = "Tom - Registration confirmation" body = """Hey ! Thanks for registering. Please follow the following link to complete it. http://""" + APPID + """/register/confirm?email=""" + email + """&confirm=""" + user.status + """ Tom""" message = sendmail(receipient, subject, body) message.send() self.redirect('/register/greetings') else: self.redirect('/?exception=RegistrationClosed')
def onBookingConfirmation(booking): request_q = model.ResourceQueue.selectBy(rusage=booking) for request in request_q: to = request.foruser.email_address sender = '*****@*****.**' subject = "Notification: Resource unavailable" body = string.Template(\ """ Dear Member, You had requested for receiving notification on availability of "$resource_name". The member who has tentatively booked this resource has just confirmed the booking. And hence the resource would not be available for booking from $start_time to $end_time. This is an automated alert. Do not reply. Thanks. """).substitute(ObjDict(booking), start_time=str(booking.start), end_time=str(booking.end_time)) sendmail.sendmail(to,sender,subject,body) request.destroySelf()
def cacheGeneral(tipo=None): #logging.info('tipo: ' + str(tipo) + '.') ocache = memcache.get('cacheGeneral') if ocache is None: logging.error('No se encontro o no se pudo cargar cache cacheGeneral. Busqueda en DataStore y creacion de cache.') ofertaslist = [] try: ofertas = Oferta.all().order("-FechaHora").run(limit=1500) except db.BadValueError: ofertas = db.GqlQuery("SELECT IdOft, IdCat, Oferta, Descripcion, IdEmp, Codigo, Enlinea FROM Oferta") unfoundo = 0 try: for oferta in ofertas: try: logourl = '' if oferta.Codigo and oferta.Codigo.replace('https://','http://')[0:7] == 'http://': logourl = oferta.Codigo elif oferta.BlobKey and oferta.BlobKey != None and oferta.BlobKey.key() != 'none': logourl = '/ofimg?id=' + str(oferta.BlobKey.key()) except AttributeError: logourl = '' promocion = 'http://www.elbuenfin.org/imgs/imageDefault.png' if oferta.Promocion is not None and oferta.Promocion != '': promocion = oferta.Promocion elist = [] try: ofertasE = OfertaEstado.all().filter("IdOft =", oferta.IdOft).run(limit=1) for ofertaE in ofertasE: elist.append(ofertaE.IdEnt) except AttributeError: elist = [] if len(elist) == 0: elist.append('') if oferta.Enlinea == True: tipo = 1 else: tipo = 2 for eid in elist: if oferta.FechaHoraPub <= datetime.now() and oferta.Oferta != 'Nueva oferta': ofertadict = {'IdOft': oferta.IdOft, 'IdCat': oferta.IdCat, 'Oferta': oferta.Oferta, 'IdEnt': eid, 'Logo': logourl, 'Descripcion': oferta.Descripcion, 'IdEmp': oferta.IdEmp, 'Tipo': tipo, 'fechapub': str(oferta.FechaHoraPub), 'EmpLogo': promocion} ofertaslist.append(ofertadict) ofertaslist = sortu(ofertaslist, 'IdOft') memcache.add('cacheGeneral', json.dumps(ofertaslist), 7200) except TypeError, e: logging.error(str(e)) if str(e) == 'Must provide Entity or BlobKey': receipient = '[email protected],[email protected]' subject = 'BlobKey error' body = 'BlobKey error' errmail = sendmail(receipient, subject, body) errmail.send()
def cacheEstado(eid, cid=None,tipo=None): #logging.info('eid: ' + str(eid) + '. cid: ' + str(cid) + '. tipo: ' + str(tipo) + '.') ocache = memcache.get('cacheEstado' + str(eid)) if ocache is None: logging.error('No se encontro o no se pudo cargar cache cacheEstado' + str(eid) + '. Busqueda en DataStore y creacion de cache.') ofertaslist = [] ofertasE = OfertaEstado.all().filter("IdEnt =", str(eid)) unfoundo = 0 for ofertaE in ofertasE.run(): idoft = ofertaE.IdOft ofts = Oferta.all().filter("IdOft =", ofertaE.IdOft) #logging.info('IdOft: ' + idoft) try: for oft in ofts: oferta = oft try: logourl = '' if oferta.Codigo and oferta.Codigo.replace('https://','http://')[0:7] == 'http://': logourl = oferta.Codigo elif oferta.BlobKey and oferta.BlobKey != None and oferta.BlobKey.key() != 'none': logourl = '/ofimg?id=' + str(oferta.BlobKey.key()) except AttributeError: logourl = '' promocion = 'http://www.elbuenfin.org/imgs/imageDefault.png' if oferta.Promocion is not None and oferta.Promocion != '': promocion = oferta.Promocion if oferta.Enlinea == True: tipo = 1 else: tipo = 2 if oferta.FechaHoraPub <= datetime.now() and oferta.Oferta != 'Nueva oferta': ofertadict = {'IdOft': oferta.IdOft, 'IdCat': oferta.IdCat, 'Oferta': oferta.Oferta, 'IdEnt': eid, 'Logo': logourl, 'Descripcion': oferta.Descripcion, 'IdEmp': oferta.IdEmp, 'Tipo': tipo, 'fechapub': str(oferta.FechaHoraPub), 'EmpLogo': promocion} ofertaslist.append(ofertadict) except UnboundLocalError: unfoundo += 1 pass except TypeError, e: logging.error(str(e)) if str(e) == 'Must provide Entity or BlobKey': receipient = '[email protected],[email protected]' subject = 'BlobKey error in ' + APPID body = 'BlobKey error in ' + APPID errmail = sendmail(receipient, subject, body) errmail.send() pass ofertaslist = sortu(ofertaslist) memcache.add('cacheEstado' + str(eid), json.dumps(ofertaslist), 7200) if unfoundo > 0: logging.error('Inconsistency OfertaEstado/Oferta found: ' + str(unfoundo))
def main(): form = cgi.FieldStorage() sid = form.getvalue("oauth_token", None) print "Content-type:text/html; charset=UTF-8\r\n\r\n" print "<html>\n" print "<head>\n" print '<meta http-equiv="content-type" content="text/html; charset=utf8" />\n' print "<title>NEXT STEP</title>\n" print "</head>\n" print "<body>\n" if sid == None: sid = raw_input("oauth_token filename:\n") print sid fp = open("./" + sid) data = pickle.load(fp) client = data[0] key = data[1] secret = data[2] fp.close() print "O_key:", key print "O_secret:", secret key, secret, uid = client.client.get_access_token(key, secret) print "key:", key print "secret:", secret print "uid:", uid if key: client.client.login(key, secret) """ while True: cmd = raw_input("login successfully! type 'send' to send the mail! {0}".format(time.ctime())) if cmd == 'send': break """ sendmail.sendmail(client, "sunus", "step2_subject", "step2_content") print "</body>" print "</html>"
def notify(line) : ''' Notify cell magic. ''' line = line.strip() is_valid_email = lepl.apps.rfc3696.Email() args = line.split() n_args = len(args) if n_args == 0 : return if not is_valid_email(args[0]) : if 'notify_email' in globals() : mail_to = globals['notify_email'] else : raise Exception('No email provided for notification. Please set the `notify_email` global variable.') message = line else : mail_to = args[0] message = line[len(args[0]):].strip() timestamp = datetime.datetime.fromtimestamp(time.time()) title = 'Notification' body = '%s\n\n%s' % (message, timestamp.strftime('%a %d/%m/%Y %H:%M')) sendmail.sendmail(None, mail_to, title, body)