def new(): reciever = session['reply'] session['reply'] = None dao = MailDao() length = dao.numInbox(session['userid']) if ('log' in request.form): session['userid'] = None return login() elif ('rec' in request.form): if (isValidUser(request.form['rec'])): num = dao.numMails() now = datetime.datetime.now(timezone('US/Eastern')) textMail = request.form['text'] textMail = textMail.replace('\r\n', '<br>') mail = Mail(num, session['userid'], request.form['rec'], request.form['subj'], textMail, 0, 0, now.strftime("%m/%d/%Y %H:%M")) dao.insert(mail) session['mail'] = num return redirect(url_for('outbox')) else: num = dao.numMails() textMail = request.form['text'] textMail = textMail.replace('\r\n', '<br>') text = "Mail you tried to send:<br>To: " + request.form[ 'rec'] + "<br>Subject: " + request.form[ 'subj'] + "<br>" + textMail now = datetime.datetime.now(timezone('US/Eastern')) mail = Mail(num, 'System', session['userid'], "User doesn't exist", text, 0, 0, now.strftime("%m/%d/%Y %H:%M")) dao.insert(mail) session['mail'] = num return redirect(url_for('inbox')) return render_template('new.html', **locals())
def process_mails(self): mails = [] for root, dirs, files in os.walk(self.inpath): for filename in files: fp = os.path.join(root, filename) # Calc hash of source file hash = calc_hash(fp) if filename.endswith(".msg"): msg = os.path.join(self.export_dir, f"{hash}.msg") shutil.copyfile( fp, os.path.join(self.export_dir, f"{hash}.msg")) eml_hash = hash + ".eml" eml = os.path.join(self.export_dir, eml_hash) msg2eml_cmd = [f"msgconvert", "--outfile", eml, msg] exec_cmd(msg2eml_cmd) m = Mail(eml, filename, is_legacy_geoip=self.is_legacy_geoip) mails.append(m) elif filename.endswith(".eml"): eml = os.path.join(self.export_dir, f"{hash}.eml") shutil.copyfile(fp, eml) m = Mail(eml, filename, is_legacy_geoip=self.is_legacy_geoip) mails.append(m) self.db_manager.update_db(mails)
def _send_email(): # Send email in a loop, avoid sending simultaneously. sq = Sql() items = sq.check_item_need_to_remind() # monitor_items, alert_items logging.warning('This loop sent email: %s', items) for item in items[0]: # email, item_name, item_price, user_price, item_id, column_id item_url = 'https://item.jd.com/' + str(item[4]) + '.html' email_text = '您监控的物品:' + item[1] + ',现在价格为:' + item[2] + \ ',您设定的价格为:' + item[3] + ',赶紧购买吧!' + item_url email_subject = '您监控的物品降价了!' try: send_email = Mail(email_text, 'admin', 'user', email_subject, item[0]) send_email.send() time.sleep(Email_TIME) except: logging.critical('Sent email failure, skip in this loop: %s', item[0]) continue sq.update_status(item[5]) logging.warning('Sent monitor email SUCCESS: %s', item[0]) for item in items[1]: # email, item_name, item_price, discount, item_id, column_id, last_price item_url = 'https://item.jd.com/' + str(item[4]) + '.html' email_text = '您监控的类别中,物品:' + item[1] + ',上次监控价格为:' + item[6] + \ ',现在价格为:' + item[2] + ',降价幅度为:' + str(100 * float(item[3])) + '折,赶紧购买吧!' + item_url email_subject = '您监控类别中的物品大幅度降价了!' try: send_email = Mail(email_text, 'admin', 'user', email_subject, item[0]) send_email.send() time.sleep(Email_TIME) except: logging.critical('Sent email failure, skip in this loop: %s', item[0]) continue sq.update_status(item[5]) logging.warning('Sent monitor email SUCCESS: %s', item[0])
def send_mail(self, title, tolist, content): cf = ConfigParser.ConfigParser() filename = os.getcwd() + '/conf/mail.conf' cf.read(filename) smtpserver = cf.get("smtp", "smtpserver") smtpaccount = cf.get("smtp", "smtpaccount") smtppwd = cf.get("smtp", "smtppwd") subject = title + 'APM报警邮件' mail = Mail(smtpserver, smtpaccount, smtppwd) mail.send(subject, content, tolist) mail = Mail('127.0.0.1', '', '') mail.send(subject, content, tolist)
def main(): MAIL = 'M' NO_MAIL = 'N' # create Mail object, login get # number of unread emails, then logout g = Mail() g.login() numUnread = g.getNumUnread() g.logout() # create SConnection object and connect # to serial port s = SConnection() s.connectToSerial('COM3') # write message to serial depending on if # there are unread emails or not if numUnread > 0: s.writeToSerial(MAIL) else: s.writeToSerial(NO_MAIL) # close serial connection s.closeSerial()
def extract(self): self.base.append( Mail(email.message_from_string(self.data), ignorelist=self.ignore, geodb=self.geoipdb, size=sys.getsizeof(self.data))) self.f.close()
def event_check(controller, *args, **kwargs): event_name = kwargs['event_name'] from google.appengine.api.datastore_errors import BadValueError try: templates = MailModel.query(MailModel.touch_event==event_name).fetch() except BadValueError as e: return [{ 'event_name': event_name, 'message': str(e), 'status': 'failure' }] m = Mail(controller) return_msg = [] from datetime import datetime kwargs.update({ 'site_name': controller.host_information.site_name, 'now': controller.util.localize_time(datetime.now()), 'domain': controller.host_information.host, }) send_to = None if 'user' in kwargs and kwargs['user'] is not None: send_to = kwargs['user'].email if 'send_to' in kwargs: send_to = kwargs['send_to'] for template in templates: a = m.send_width_template(template=template, send_to=send_to, data=kwargs) return_msg.append({ 'mail': template.name, 'message': a['message'], 'status': a['status'] }) return return_msg
def extract(self): """Extracts mails from the archive and writes them in a list like-object which can than be iterated over""" geoipdb = geoip2.database.Reader(self.geofile) dat = self.arc.read() #Match delimiting From terms arr = re.split("\n\nFrom.*[0-9]{4}\n\n", dat) fromlines = [dat.split("\n")[0]] fromlines.extend([ froml.strip() for froml in (re.findall("\n\nFrom.*[0-9]{4}\n\n", dat)) ]) self.fromaddrs = [froml.split(" ")[1] for froml in fromlines] self.dates = [' '.join(froml.split(" ")[2:]) for froml in fromlines] self.arc.close() #Remove artifacts in first and last mail arr[0] = '\n'.join(x for x in arr[0].split('\n')[2:]) arr[-1] = '\n'.join(x for x in arr[-1].split('\n')[:-2]) self.base = [ Mail(email.message_from_string(x), geodb=geoipdb, archive=True, arcDate=self.dates[idx], ignorelist=self.ignore, size=sys.getsizeof(x)) for idx, x in enumerate(arr) ]
def index(): form = NameForm() if form.validate_on_submit(): name = User.query.filter_by(user_name=form.name.data).first() if name is None: #새로운 사용자 db에 추가 flash('db에 사용자가 추가되었습니다.') user = User(user_name=form.name.data, email=form.email.data) db.session.add(user) session['known'] = False else: session['known'] = True flash('메일로 크롤링 정보를 보내드렸습니다.') mail = Mail(naver_crawling(), form.email.data) t = threading.Thread(target=mail.naver_send_email) t.start() session['name'] = form.name.data session['email'] = form.email.data form.name.data = '' form.email.data = '' return redirect(url_for( 'index')) #post/rediret/get patter 기법. 마지막 요청을 post로 남기지 않기 위해. return render_template('index.html', form=form, name=session['name'], known=session.get('known', False))
def email_about_interview_to_applicant(name_input, email_input, new_interview): recipient_list = [email_input] subject = "New Interview" type = "To applicant about interview data" try: message = """ Hi {name_input}, Your interview is at {time}, with {mentor} and {mentor2}. Please arrive 15 minutes early. Good luck! """.format(name_input=name_input, time=new_interview.interviewslot.start, mentor=new_interview.interviewslot.mentor.name, mentor2=new_interview.interviewslot.mentor2.name) except: message = """ Hi {name_input}, Our schedule is full, we could not give you an interview date yet. If you do not get one within a week, please contact 06-1-1234567. Thank you. """.format(name_input=name_input) interview_email = Mail(recipient_list, message, subject) interview_email.send() message = textwrap.shorten(message, width=140, placeholder="...") new_email = Email.create(subject=subject, message=message, type=type, submissiondate=datetime.datetime.now(), recipient_name=name_input, recipient_email=email_input)
def email_about_code_and_city_to_applicant(name_input, email_input, application_code, applicant_school): recipient_list = [email_input] subject = "New Application" type = "To applicant about personal data" message = """ Hi {name_input}, Your application process to Codecool has been started! The city you have been assigned to is {city}. Your application code and your login password to the site is {code}. Good luck! :) """.format(name_input=name_input, code=application_code, city=applicant_school.name) application_email = Mail(recipient_list, message, subject) application_email.send() message = textwrap.shorten(message, width=140, placeholder="...") new_email = Email.create(subject=subject, message=message, type=type, submissiondate=datetime.datetime.now(), recipient_name=name_input, recipient_email=email_input)
def main(send=False): key = get_value('key') html = None # get movie info for all categories for cat in CATEGORIES: td = Tmdb(key, cat) movies = td.get_movies(NUM_RES) ca = Cache(os.path.basename(cat)) ca.shelve_results(movies) newMovies = ca.shelve_results(movies) movieObjects = ca.shelve_get_items(newMovies) # only new ones op = Output(movieObjects) if html is None: html = [op.generate_header()] catPrettified = cat.title().replace("_", " ") html.append(op.generate_category_title(catPrettified)) html.append(op.generate_movie_html_div()) # save html f = open(OUTFILE, "w") f.write("\n".join(html)) f.close() # email if send: subject = "Sharemovi.es / %s movies / week %s" % ( ", ".join(CATEGORIES), str(THIS_WEEK)) sender = get_value('sender') recipients = load_emails('recipients') ma = Mail(sender) ma.mail_html(recipients, subject, "\n".join(html))
def mail_notify(msg): """ To 接受者(must) Cc 抄送(option) Bcc 密送(option) From 发送者(must) Subject 邮件主题 Smtpserver smtp服务器(must) Username 发送用户名(must) Password 发送密码(must) Sender 发送者(option) """ msg = msg.encode('utf-8') config_info = { "To": ["*****@*****.**"], 'From': "*****@*****.**", 'Subject': "分析日志监控到异常".decode('UTF-8'), 'Smtpserver': "smtp.163.com", 'Username': "******", 'Password': "" } msg = msg.replace("\n", "<br>").replace(" ", " ") mail = Mail(config_info) mail.add_text(msg) mail.add_text("<br><br>") ifconfig = os.popen("/sbin/ifconfig").read() ifconfig = ifconfig.replace("\n", "<br>").replace(" ", " ") mail.add_text(ifconfig) mail.send()
def sendMail(self): #link = self.webRTCaddress() topic = "nao_robot/camera/top/camera/image_raw" text = "The assistance robot and smart house has detected a fall. To check, please see the video from this address " #+ link text = text + "/stream_viewer?topic=" + topic mail = Mail(text) mail.sendMail()
def main(): IsConnected = False ConnectedChanged = False if CheckConnection(): IsConnected = True ConnectedChanged = True while True: IsConnected_new = CheckConnection() if IsConnected == IsConnected_new: ConnectedChanged = ConnectedChanged else: ConnectedChanged = not ConnectedChanged if ConnectedChanged: IsConnected = CheckConnection() if IsConnected: IP = GetIP() mail = Mail() server = mail.Login() mail.SendMail(server, IP) ConnectedChanged = False else: IsConnected = CheckConnection() else: continue
def main(): (opts, args) = cli() key = get_value('key') td = Tmdb(key, opts.category) if opts.listing: li = Listing(opts.category) movies = li.get_movies() prefix = "list_" subject = "Week %s: %s" % (THIS_WEEK, li.title) else: movies = td.get_movies(opts.numres) prefix = "" subject = "%s movies - week %s" % (opts.category.title().replace("_", " "), THIS_WEEK) ca = Cache(prefix + os.path.basename(opts.category)) newMovies = ca.shelve_results(movies) if opts.listing: movieObjects = ca.shelve_get_items(movies) # allow dups else: movieObjects = ca.shelve_get_items(newMovies) # only new ones op = Output(movieObjects) html = [op.generate_header()] html.append(op.generate_movie_html_div()) if opts.printres: print "\n".join(html) if opts.mailres: sender = get_value('sender') recipients = load_emails('recipients') ma = Mail(sender) ma.mail_html(recipients, subject, "\n".join(html))
def recuperar_senha(self, email): colecao = self.db.usuarios usuario = colecao.find_one({'email': email}) if usuario == None: return senha = usuario['senha'] mail = Mail() mail.send_message(senha, email)
def send_data(self, text, subject, attachments): mail = Mail(self.sender_name, self.sender_email, self.recipient_email, text, self.cc, subject, self.content_type, attachments) ans = self.get_server_answer(mail.full_text) ans_code = extract_codes(ans) if '250' not in ans_code: raise SmtpException(ans)
def test_count_html_tags(self): """Count HTML tags inside mail.""" f = open('data/1/0419.a42a284750591b454968a76dfab38370', "r", encoding="utf-8") mail = Mail(f.read()) f.close() self.assertEqual(77, mail.count_html_tags(mail.content), 'HTML tags count is incorrect.')
def do_PUT(self): ips = Read_xml.ips alerts = Read_xml.alerts mails = Read_xml.mails ip = str(self.headers).split(" ")[1].split(":")[0] length = int(self.headers['Content-Length']) content = self.rfile.read(length) #Send PUT Respond self.send_response(200) #Decryption the incoming data from HHTP PUT Request secret_key = '4569803458932015' cipher = AES.new(secret_key, AES.MODE_ECB) cpu = cipher.decrypt(base64.b64decode(json.loads(content)["cpu"])) cpu = eval(cpu) memory = cipher.decrypt(base64.b64decode( json.loads(content)["memory"])) memory = float(memory) uptime = cipher.decrypt(base64.b64decode( json.loads(content)["uptime"])) uptime = float(uptime) #Storing the data to the database DB(cpu, memory, uptime, ip) #check for Alerts to send mail index = 0 for check in ips: if ip == check: if alerts[index, 0][0] == 'memory': if memory >= float(str(alerts[index, 0][1]).split("%")[0]): Mail(index, cpu, memory, mails) else: pass elif alerts[index, 1][1] == 'cpu': if np.mean(cpu) >= float( str(alerts[index, 1][1]).split("%")[0]): Mail(index, cpu, memory, mails) else: pass else: print " couldn't find the IP of the alerted client" index += 1
def main(): config = Config() mail = Mail(config) while True: try: mail.check() time.sleep(10 * 60) # 10 minutes except KeyboardInterrupt: break
def sign(self): url = 'http://www.kuaipan.cn/index.php?ac=common&op=usersign' req = urllib2.Request(url) fd = self.opener.open(req) signReturnJson = fd.read() sign_js = json.loads(signReturnJson) if sign_js['state'] == -102: print(u"has signed today!") Mail().SendMail(u'快盘签到', ["*****@*****.**"], u"今日已经在其他地方签到", "fyi.") elif sign_js['state'] == 1: o = u"签到成功! 获得积分:%d,总积分:%d;获得空间:%dM\n" % ( sign_js['increase'], sign_js['status']['points'], sign_js['rewardsize']) print o Mail().SendMail(u'快盘签到', ["*****@*****.**"], u"签到成功", o) else: print(u"sign failed!") fd.close()
def sendReports(self, option): """ Send out reports via email """ msg = {} # mail header and body mail = '' server = {} # smtp server m = Mail() # smtp server address and tcp port server['addr'] = self.opts['smtp_host'] server['port'] = self.opts['smtp_port'] # smtp (static content) read from ini file msg['from'] = self.opts['smtp_from'] Wrapper.msg('Sending out reports') if option == 'report': # for each report in report directory except summary.txt for f in os.listdir(self.opts['outdir'] + '/' + TODAY): if f != 'summary.txt': report = self.opts['outdir'] + '/' + TODAY + '/' + f name = f.split('.')[0] # mail header + body msg['message'] = 'Hi,\n\nplease find attached the Nessus ' \ 'report for this week.\n\nBest Regards,\n\n' \ "Rocket Internet's Security Team" msg['subject'] = '[{0}] Your new Nessus report for {1} ' \ 'is ready'.format(name, TODAY) msg['to'] = self.ini.config.get('addressbook', name) # build and send mail mail = m.buildMail(msg, (report, )) m.sendMail(server, mail, self.opts['smtp_login'], tls=True) else: report = self.opts['outdir'] + '/' + TODAY + '/' + 'summary.txt' with open(report, 'r') as f: report_data = f.read() # mail header + body msg['message'] = 'Hi,\n\nplease find below the Nessus ' \ 'Summary Report for this week:\n\n' msg['message'] += report_data msg['message'] += "\n\nBest Regards,\n\nRocket Internet's " \ "Security Team" msg['subject'] = 'Nessus Summary Report ({0})'.format(TODAY) msg['to'] = self.ini.config.get('addressbook', 'Summary') # build and send mail mail = m.buildMail(msg, (report, )) m.sendMail(server, mail, self.opts['smtp_login'], tls=True) return
def test_remove_html_tags(self): """Count HTML tags inside mail.""" f = open('data/1/0419.a42a284750591b454968a76dfab38370', "r", encoding="utf-8") mail = Mail(f.read()) f.close() self.assertEqual(-1, mail.remove_html_tags(mail.content).find('<IMG'), 'Not all HTML tags were removed') self.assertEqual(True, mail.remove_html_tags(mail.content).find('sitting in our database alone, which contains bank') != -1, 'Text was removed from mail')
def service_actions(self): global ANSWERED self._curr_date = datetime.now() if (self._curr_date > self._to_answer_date): print("> Too late to answer, sending data to your family...") #Remove the generated file corresponding to the previous token to_delete = "alive=" + self.RequestHandlerClass._id + ".html" os.remove(to_delete) if (os.path.isfile(to_delete)) else None #Send mail mail = Mail("Alarm") mail.send_alarm() exit(0) if (not self._is_send or ANSWERED): #Remove the generated file corresponding to the previous token to_delete = "alive=" + self.RequestHandlerClass._id + ".html" os.remove(to_delete) if (os.path.isfile(to_delete)) else None #Waiting for date to correspond to next checkup while self._curr_date < self._next_checkup_date: #sleep(2) self._curr_date = datetime.now() #Generate an url token self.RequestHandlerClass._id = secrets.token_urlsafe(32) #Generate a file where user arrive before being redirected to index.html with open("alive=" + self.RequestHandlerClass._id + ".html", "w+"): print("> Generated html page linked to token") #Send Checkup Email checkmail = Mail("Checkup") checkmail.send_checkup(self.RequestHandlerClass._id) #Setting next checkup in 30 days self._next_checkup_date = self._curr_date + timedelta(days=30) if ANSWERED: self._to_answer_date = self._next_checkup_date + timedelta( days=2) self._is_send = True ANSWERED = False
def __init__(self): self.user_id = '' self.db = DBSession() self.session = requests.session() self.corn_types = CORN_TYPE self.corns = {} # stop/active self.status = 'stop' self.warn_interval = WARN_INTERVAL self.warn_time = None self.mail = Mail() self.session.headers.update(HEADER)
def __init__(self): # add parser object to class attribute self.parser = reqparse.RequestParser() # add required argument sms self.parser.add_argument("sms", type=str, required=True) # add elastic search class object to this class attribute self.elastic = Elastic() # add mail class object to this class attribute self.mail = Mail()
def notify(self, svn_info, mail_address, cur_revision): print "notify revision is " + str(cur_revision) mail = Mail(config.email_smtp, "svn monitor", "to " + mail_address, "new revision: " + str(cur_revision), svn_info.path + " updated current revision is: " + str(cur_revision)) if config.email_use_ssl: mail.starttls() mail.login(config.email_user, config.email_pwd) mail.send(config.email_user, mail_address) return
def send_plain_mail(self, receiver, subject, body): ''' User uses Mail class object, receiver and subject strings and body html message This method does all the logic script create_session method creates SMTP session for the User to login in e-mail acc attach_message attaches html body to the message object of mail send_mail ends session and sends e-mail to receiver ''' plain_mail = Mail(self, receiver, subject, body) plain_mail.create_session() plain_mail.attach_message() plain_mail.send_mail()
def parse(self, number, data): try: dec_data = data.decode() except Exception: dec_data = data.decode("windows-1251") d = self.main_parse(dec_data) attachments = self.get_attachments(dec_data) try: return Mail(number, d["subject"], d["from"], d["size"], d["to"], d["date"], d["message"], attachments) except: raise