Example #1
0
    def get(self):
        send_to = self.get_argument("to", "")
        subject = self.get_argument("subject", "")
        context = self.get_argument("message", "")
        html = self.get_argument("html", "")
        if send_to.find(','):
            send_to_list = send_to.split(',')
        else:
            send_to_list = [send_to]
        subject = urllib.unquote(subject)
        html = urllib.unquote(html)

        if not html:
            s = SendEmail(send_to_list, subject, context)
            if s.send_mail():
                self.write("Succeed")
            else:
                self.write("Failed")
        else:
            if '\n' in html:
                html = html.replace('\n', '<br>')
            s = SendEmail(send_to_list, subject, html)
            if s.send_mail_html():
                self.write("Succeed")
            else:
                self.write("Failed")
Example #2
0
    def send_invitations(self):
        """
        Assigns secret santa to every participant and sends an email
        invite to respective members informing the same.
        """
        event_date_str = self.txt_date.get()
        if event_date_str:
            try:
                event_date = datetime.strptime(event_date_str, '%m/%d/%Y')
            except ValueError:
                messagebox.showerror("Error", "Invalid date format.")
                return

            event_date_str = datetime.strftime(event_date, "%A - %d %b, %Y")
        else:
            event_date_str = '-'

        budget = self.txt_budget.get()
        try:
            budget = int(budget)
        except ValueError:
            messagebox.showerror("Error", "Invalid budget value.")
            return

        email_dict = {}
        participants = []
        for i in range(NO_OF_ENTITIES):
            email = self.txt_email[i].get()
            name = self.txt_name[i].get()
            if name and email:
                email_dict[email] = name
                participants.append(email)
            else:
                if email and not name:
                    messagebox.showerror("Error", f"Name not found for entity no. {i+1}.")
                    return

                if name and not email:
                    messagebox.showerror("Error", f"Email mandatory for entity no. {i+1}.")
                    return

        if (len(participants)) < 2:
            messagebox.showerror("Error", "Insufficient participants.")
            return

        random.shuffle(participants)

        email_formatter = EmailFormatter(event_date_str, budget)
        for i, _ in enumerate(participants):
            giver = participants[i]
            receiver = participants[(i + 1) % (len(participants))]
            send_email = SendEmail(['smtp.gmail.com', 587, \
                                    '*****@*****.**', 'xxxxxxxxx'], True)
            send_email.send(from_name="Secret Santa Generator",
                            to_address=[giver], \
                            subject=email_formatter.subject(email_dict[giver]), \
                            body=email_formatter.body(email_dict[giver], \
                                                      email_dict[receiver]))

        messagebox.showinfo("Success", "Invitations sent.")
Example #3
0
 def __init__(self, url, cookies2=None, proxies=None, cookies=None):
     self.url = url
     self.proxies = proxies
     self.email = SendEmail()
     # cookies = cookies2 if cookies2 else self._get_cookies()
     self.session = requests.Session()
     self.session.cookies = cookiejar_from_dict(cookies)  # session设置cookie
     headers = {
         'Accept':
         'application/json, text/javascript, */*; q=0.01',
         'Accept-Encoding':
         'gzip, deflate, br',
         'Accept-Language':
         'zh-CN,zh;q=0.9',
         'Connection':
         'keep-alive',
         'Host':
         'antirobot.tianyancha.com',
         'Cookies':
         cookies,
         'Referer':
         'https://antirobot.tianyancha.com/captcha/verify?return_url={}&rnd='
         .format(self.url),
         'User-Agent':
         'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
         'X-CSRFToken':
         'null',
         'X-Requested-With':
         'XMLHttpRequest',
     }
Example #4
0
def flush_msg():
    global queue
    messages = queue
    queue = []
    for msg in messages:
        myLogger.log(msg)
        SendEmail(msg, msg)
Example #5
0
 def compare_send_email(self, item_id, item_price_inner, item_name_inner):
     cursor = conn.cursor()
     sql = 'select user_price from monitor where item_id = %s' % item_id
     print '查询语句为:', sql
     cursor.execute(sql)
     user_price = cursor.fetchone(
     )  # user_price: tuple user_price[0]: decimal item_price: unicode
     if float(
             user_price[0]) >= float(item_price_inner):  # 转为float才可以对比,可以改进
         sql = 'update monitor set status = 0 where item_id = %s' % item_id
         cursor.execute(sql)
         conn.commit()
         sql = 'select user_email from user where user_id = ( select user_id from monitor where item_id = %s )' % item_id
         cursor.execute(sql)
         user_email = cursor.fetchone()
         user_email = str(user_email[0])  # 改进
         email_text = '您监控的商品:' + str(item_name_inner) + ',现在价格为:' + str(
             item_price_inner) + ',您设定的价格为:' + str(
                 user_price[0]) + '  赶紧抢购吧!'
         email_zhuti = '您监控的商品降价了!'
         sendemail = SendEmail(email_text, 'admin', 'user', email_zhuti,
                               user_email)
         sendemail.send()
         print '该商品降价,已发送邮件提醒用户'
     cursor.close()
Example #6
0
    def get(self):
        logging.info("SummaryTask starting...")

        # init class and variables
        bucket_name = os.environ.get(
            'BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
        bucket = '/' + bucket_name
        trendManager = TrendManager()
        dataModelConverter = DataModelConverter()
        csvUtils = CsvUtils()
        cloudStorageUtils = CloudStorageUtils()

        previous_day_timestamp = int(time.time()) - Globals._1_DAY
        q_futures = []
        for region in self.getRegions():
            try:
                date = TimezoneAwareDate(region, self.request.get('date'))
                trendsJson = self.getTrends(region, trendManager)
                self.saveToCloudStorage(dataModelConverter, csvUtils,
                                        cloudStorageUtils, trendsJson, region,
                                        bucket, date)
                self.saveToDatastore(q_futures, trendsJson, region, date)
                self.deleteFromDatastore(q_futures, region,
                                         previous_day_timestamp)

            except Exception, e:
                traceback.print_exc()
                Error(msg=str(e), timestamp=int(time.time())).put()
                SendEmail().send('Error on SummaryTask', str(e))
                self.retry()
Example #7
0
    def __init__(self, conf_file):
        self.pidfile = "/tmp/hermes.pid"
        self.conf_file = conf_file
        self.conf_data = self.__read_conf()

        # Initiate objects
        self.file_system = FileSystem(self.conf_data['archive_path'])
        self.mail = SendEmail(self.conf_data['mail'])
Example #8
0
    def notify(self, subject, body, email_to):

         # initialize send mail class
         send_email = SendEmail()

         # print(body)
         send mail to active users
         send_email.send(email_to, subject, body)
         send_email.quit()
    def readDateInfo(self, retry=True):
        try:
            result = self.rpc.get_result()
            if result.status_code == 200:
                data = result.content
                jsonData = json.loads(data)
                return jsonData['formatted'].split()[0]
            else:
                if retry:
                    time.sleep(1)
                    return self.readDateInfo(False)
                else:
                    SendEmail().send('Error on TimezoneAwareDate',
                                     'Timezonedb api request error.')

        except Exception, e:
            traceback.print_exc()
            Error(msg=str(e), timestamp=int(time.time())).put()
            SendEmail().send('Error on TimezoneAwareDate', str(e))
Example #10
0
def email_alarm(participants, test):
  plist = []
  for p in participants:
    if p['email_address'] != '':
       plist.append(p['email_address'])
  if plist:
    logstr = "Send email to: %s" % ", ".join(plist)
    log.info(logstr)
    # Now send all email notifications
    send_email = SendEmail(*db.email_settings())
    for email_addr in plist:
      send_email.deliver('*****@*****.**', email_addr, *db.email_notification(test))
Example #11
0
def config_log(directory,
               log_name,
               max_files_uncompressed=1,
               max_level="IMPORTANT",
               compress=True,
               develop=False,
               send_email=False,
               to_emails=None,
               from_email=None,
               pwd=None,
               send_sms=False,
               to_phones=None,
               auth_id=None,
               auth_token=None):
    """
    Configure log using a default pattern and create a new level (important).

    Args:
        directory: folder to save logs;
        log_name: first part of the log name;
        max_files_uncompressed: max number of remaining not compressed files;
        max_level: max level of log;
        compress: indicates if compress the logs or no;
        develop: set output from logging.important to standard ouput (normal print);
        send_email: boolean to activate or not alert by Email on CRITICAL, ERROR or NOTIFY leve.;
        to_emails (needed if send_email is True): list of emails to receive alert;
        from_email (needed if send_email is True): email used to send email alert;
        pwd (needed if send_email is True): from_email password;
        send_sms: boolean to receive or not alert by SMS on CRITICAL, ERROR or NOTIFY level;
        to_phones (needed if send_sms is True): list of phones to receive alert;
        auth_id (needed if send_sms is True): auth id from Plivo;
        auth_token (needed if send_sms is True): auth token from Plivo;
    """
    end_with = '.log'
    directory = _to_path(directory)

    if not path.exists(directory):
        makedirs(directory)

    email_handler = None
    sms_handler = None
    if send_email:
        email_handler = SendEmail(log_name, to_emails, from_email, pwd)

    if send_sms:
        sms_handler = SendSMS(log_name, to_phones, auth_id, auth_token)

    _set_logger(directory, log_name, _get_log_level(max_level), develop,
                email_handler, sms_handler)

    if compress and not develop:
        _clean_up_logs(directory, log_name, end_with, max_files_uncompressed)
Example #12
0
 def compare_send_email(self, user_id_inner, item_id_inner, item_price_inner, item_name_inner):
     cursor = self.conn.cursor()
     try:
         sql = 'select user_price from monitor where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner)
         # print 'SQL query: ', sql
         cursor.execute(sql)
         user_price = cursor.fetchone()  # user_price: tuple, user_price[0]: decimal, item_price: unicode
     except mysql.connector.errors.InternalError:
         note = '拥有重复商品,每个商品只能有一个监控,否则会导致监控失败。'
         sql = 'update monitor set note = \'%s\' where item_id = %s and user_id = %s' % (note, item_id_inner, user_id_inner)
         print 'Have same item id in one user, skip this round.'
         cursor.execute(sql)
         self.conn.commit()
         cursor.close()
         return
     if float(item_price_inner) == -1.00:  # 抓取到-1不发邮件,状态依然为1
         note = '商品已经下架或者ID不正确。'
         sql = 'update monitor set note = \'%s\' where item_id = %s and user_id = %s' % (note, item_id_inner, user_id_inner)
         print 'Wrong item price: -1, skip this round.'
         cursor.execute(sql)
         self.conn.commit()
         cursor.close()
         return
     if float(user_price[0]) >= float(item_price_inner):  # 转为float才可以对比,可以改进
         # try:
         sql = 'update monitor set status = 0 where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner)
         cursor.execute(sql)
         self.conn.commit()
         sql = 'select user_email from user where user_id = %s' % user_id_inner
         cursor.execute(sql)
         user_email = cursor.fetchone()
         user_email = str(user_email[0])  # linux可用,win会报下面的错误
         # item_url = 'https://item.jd.com/' + item_id_inner + '.html'  # 邮件网址,怀疑是垃圾邮件原因
         email_text = '您监控的商品:' + item_name_inner + ',' + ',现在价格为:' + item_price_inner + ',您设定的价格为:' + str(user_price[0]) + '  赶紧抢购吧!'.encode('utf-8')
         email_text = email_text
         email_zhuti = '您监控的商品降价了!'
         sendemail = SendEmail(email_text, 'admin', 'user', email_zhuti, user_email)
         sendemail.send()
         print '该商品降价,已发送邮件提醒用户'
         '''
         except UnicodeEncodeError as e:
             sql = 'update monitor set status = 1 where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner)
             cursor.execute(sql)
             self.conn.commit()
             print '发送邮件过程中发生错误,等待下轮重试,正在监控状态继续', e
         except UnicodeDecodeError as e:
             sql = 'update monitor set status = 1 where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner)
             cursor.execute(sql)
             self.conn.commit()
             print '发送邮件过程中发生错误,等待下轮重试,正在监控状态继续', e
         '''
     cursor.close()
def send_mail():
    while RedisA.exists_key(UserEmail):
        user_email = RedisA.rc.lpop(UserEmail)
        mail = SendEmail()
        prefix = 'EMA'
        title = '亚马逊自助采集服务'
        # context = '您的采集任务已完成,请登录网页( https://data.banggood.cn/bgbdp/index#/dataApplication/ponelThree )查看采集结果。'
        # msg = MIMEText(context, 'plain', 'utf-8')
        with open('email.html', encoding='utf-8') as f:
            context = f.read()
            msg = MIMEText(context, 'html', 'utf-8')
        mail.send_message(prefix, user_email, title, msg)
    print('wait 30 s')
    time.sleep(30)
Example #14
0
def sendEmail():
    start = int(time.time())

    path = r''
    receiver1 = ['xxxxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxx']

    c = Crawler(path)
    count = c.doJob()

    send = SendEmail()
    send.getInstanse(receiver1, count)

    i = int(time.time()) - start

    interval = 86400 - i
    timer = threading.Timer(interval, sendEmail)
    timer.start()
Example #15
0
def contact():
   form = ContactForm()
   if request.method == 'POST':
	if form.validate() == False:
	   flash('All fields are required.')
	   return render_template('contact_form.html', form=form)
	else:
		post =Contact(name=request.form['name'],email=request.form['email'],phone_number=request.form['phone_number'],message=request.form['message'])
		db.session.add(post)
		db.session.commit()
		name =request.form['name']
		sender_email = request.form['email']
		to_email = '*****@*****.**'
		message = request.form['message']
		phone = request.form['phone_number']
		SendEmail().send_email_from_website(name,sender_email, to_email, message,phone)

	   # return render_template('success.html')
	   	return redirect(url_for('response_contact'))
   elif request.method == 'GET':
       return render_template('contact_form.html', form=form)
    def get(self):
        logging.info("GetTrendsTask starting...")

        try:
            # create twitter client
            client = TwitterApi(
                consumer_key=Crenditals.CONSUMER_KEY,
                consumer_secret=Crenditals.CONSUMER_SECRET,
                access_token_key=Crenditals.CLIENT_TOKEN,
                access_token_secret=Crenditals.CLIENT_SECRET)

            q_futures = []
            for region in Globals.REGIONS:
                # request trends from twitter
                response = client.getTrendsByWoeid(woeid=region)
                # get current timestamp in seconds
                timestamp = int(time.time())
                # put trends to db
                entityList = []
                for trend in response:
                    entityList.append(
                        TrendWindow(
                            name=trend['name'],
                            woeid=region,
                            timestamp=timestamp,
                            time=10,
                            volume=trend['tweet_volume']))
                q_futures.extend(ndb.put_multi_async(entityList))
                self.updateCacheValues(region, entityList)

            # wait all async put operations to finish.
            ndb.Future.wait_all(q_futures)
        except ValueError as v_e:
            logging.error(v_e)
            # self.retry()
        except Exception, e:
            traceback.print_exc()
            Error(msg=str(e), timestamp=int(time.time())).put()
            SendEmail().send('Error on GetTrendsTask', str(e))
class JiraIssueHandler():
    http_headers = None
    sendEmail = SendEmail()
    utils = GeneralUtils()

    def __init__(self):
        self.http_headers = {**JIRA_AUTH, **JIRA_CONTENT, **JIRA_ACCEPT}

    def createIssueFields(self, project, issuetype, summary, description, assignee, components=[], versions=[]):
        if (len(components) == 0):
            return Fields(project, issuetype, summary, description, assignee)
        else:
            return FieldsTestExec(project, issuetype, summary, description, assignee, components, versions)

    def createIssue(self, project, issuetype, summary, description, assignee, components=[], versions=[]):
        fields = self.createIssueFields(project, issuetype, summary, description, assignee, components, versions)
        issueData = IssueData(fields)
        post_url = JIRA_ISSUE_URL
        post_data = json.dumps(issueData.__dict__, default = obj_to_dict)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        response_content = response.json()
        print("{} na criacao da issue: {}".format(self.utils.codeToStr(response.status_code, 201), response_content))
        return Response(
            Response.STATUS_OK if response.status_code == 201 else Response.STATUS_ERROR, 
            response_content['key'] if response.status_code == 201 else str(response.status_code),
            response_content)

    def createIssueWithRawData(self, projectKey, issuetypeName, summary, description, assigneeName, component="", version=""):
        project = Project(projectKey)
        issuetype = IssueType(issuetypeName)
        assignee = Assignee(assigneeName)
        components = list()
        versions = list()
        if (component):
            components.append(Component(component))
        if (version):
            versions.append(Version(version))

        return self.createIssue(project, issuetype, summary, description, assignee, components, versions)

    def createIssueLink(self, issueLinkType, inwardIssue, outwardIssue):
        issueLink = IssueLink(issueLinkType, inwardIssue, outwardIssue)
        post_url = JIRA_ISSUELINK_URL
        post_data = json.dumps(issueLink.__dict__, default = obj_to_dict)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        print("{} na criacao do link {} entre {} e {}".format(self.utils.codeToStr(response.status_code, 201), issueLinkType, inwardIssue, outwardIssue))
    
    def getIssueSummary(self, issueKey):
        get_url = JIRA_ISSUE_GET_SUMMARY_URL.format(issueKey)
        response = requests.get(get_url, headers = self.http_headers)
        print("Status Code:", response.status_code)
        issueSummary = ""
        if (response.status_code == 200):
            response_content = response.json()
            issueSummary = response_content['fields']['summary']
        print("Summary da issue(%s): %s" % (issueKey, issueSummary))        
        return issueSummary

    def createIssueLinkWithRawData(self, typeName, inIssueKey, outIssueKey):
        issueLinkType = IssueLinkType(typeName)
        inwardIssue = WardIssue(inIssueKey)
        outwardIssue = WardIssue(outIssueKey)
        self.createIssueLink(issueLinkType, inwardIssue, outwardIssue)    

    def changeIssueTransition(self, issueKey, transitionId, resolutionName=""):
        transition = Transition(transitionId)
        issueTransitionData = IssueTransition(transition)

        if (resolutionName):
            resolution = Resolution(resolutionName)
            fields = FieldResolution(resolution)
            issueTransitionData = IssueTransitionResolution(transition, fields)

        post_url = JIRA_ISSUE_TRANSITION_URL.format(issueKey)
        post_data = json.dumps(issueTransitionData.__dict__, default = obj_to_dict)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        print("{} na alteracao do status da issue {} para {}".format(self.utils.codeToStr(response.status_code, 204), issueKey, transitionId))

    def createIssueTestExec(self, projectKey, summaryPrefix, assigneeName):
        dateTime = datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
        summary ="{} - {}".format(summaryPrefix, dateTime)
        testExecIssue = self.createIssueWithRawData(projectKey, ISSUE_TESTEXEC_NAME, summary, summary, assigneeName, COMPONENT_APP_NAME, AFFECTED_VERSION_NAME)
        return testExecIssue.key

    def addTestToTestExec(self, testExecIssueKey, tests):
        testExecAddTest = TestExecAddTest(tests)
        post_url = JIRA_TESTEXEC_ADD_TEST_URL.format(testExecIssueKey)
        post_data = json.dumps(testExecAddTest.__dict__, default = obj_to_dict)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        print("{} na adição dos Tests {} para o Test Exec {}".format(self.utils.codeToStr(response.status_code,200), str(tests), testExecIssueKey))

    def initIssueTestExec(self, issueTestExecKey, casoDeTesteKeys):
        self.addTestToTestExec(issueTestExecKey, casoDeTesteKeys)
        self.changeIssueTransition(issueTestExecKey, TESTEXEC_STATUS_IN_PROGRESS)
        for key in casoDeTesteKeys:
            self.changeIssueTransition(key, TEST_STATUS_RETESTING_ID)
            testRunId = self.getTestRunId(issueTestExecKey, key)
            self.changeIssueTestRunStatus(testRunId, TESTRUN_STATUS_TODO)

    def finishIssueTestExec(self, issueTestExecKey, resolution=""):
        self.changeIssueTransition(issueTestExecKey, TESTEXEC_STATUS_DONE, resolution)

    def initIssueTestRun(self, issueTestExecKey, issueTestKey):
        self.changeIssueTransition(issueTestKey, TEST_STATUS_IN_PROGRESS_ID)
        testRunId = self.getTestRunId(issueTestExecKey, issueTestKey)
        self.changeIssueTestRunStatus(testRunId, TESTRUN_STATUS_EXECUTING)

    def addDefectToTestRun(self, testRunIssueId, issueBugKey):
        issueBugKeyArr = [issueBugKey]
        post_url = JIRA_TESTRUN_ADD_DEFECT_URL.format(testRunIssueId)
        post_data = json.dumps(issueBugKeyArr)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        print("{} na adição do bug {} para o test run {}".format(self.utils.codeToStr(response.status_code, 200), issueBugKey, testRunIssueId))

    def addAttachmentToTestRun(self, testRunIssueId, data, filename, contentType="image/png"):
        testRunAttachment = TestRunAttachment(filename, contentType, data)
        post_url = JIRA_TESTRUN_ADD_ATTACHMENT_URL.format(testRunIssueId)
        post_data = json.dumps(testRunAttachment.__dict__, default = obj_to_dict)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        print("{} na adição da evidencia {} para o test run {}".format(self.utils.codeToStr(response.status_code, 200), filename, testRunIssueId))

    def addAttachmentToTestExecAndTest(self, issueTestExecKey, issueTestKey, data, filename, contentType="image/png"):
        testRunId = self.getTestRunId(issueTestExecKey, issueTestKey)
        self.addAttachmentToTestRun(testRunId, data, filename, contentType)

    def getTestRunId(self, testExecIssueKey, testIssueKey):
        get_url = JIRA_TESTRUN_GET_ID_URL.format(testExecIssueKey, testIssueKey)
        response = requests.get(get_url, headers = self.http_headers)
        print("Status Code:", response.status_code)
        testRunId = 0
        if (response.status_code == 200):
            response_content = response.json()
            testRunId = response_content['id']
        print("Id da TestExecutionKey(%s) e TestIssueKey(%s): %s" % (testExecIssueKey, testIssueKey, str(testRunId)))        
        return testRunId

    def changeIssueTestRunStatus(self, testRunIssueId, status):
        put_url = JIRA_TESTRUN_CHANGE_STATUS_URL.format(testRunIssueId, status)
        put_data = {}
        response = requests.put(put_url, headers = self.http_headers, data = put_data)
        print("Status Code:", response.status_code)
        print("{} na alteracao do status do Test Run {} para {}".format(self.utils.codeToStr(response.status_code, 200), testRunIssueId, status))  

    def addIssueWatcher(self, isseueBugKey, watcher):
        post_url = JIRA_ISSUE_ADD_WATCHER_URL.format(isseueBugKey)
        post_data = json.dumps(watcher)
        print(post_data)
        response = requests.post(post_url, headers = self.http_headers, data = post_data)
        print("Status Code:", response.status_code)
        print("{} na adição do usuario {} como wathcer para o bug {}".format(self.utils.codeToStr(response.status_code, 200), watcher, isseueBugKey))        

    def createBugAndAddToTestRun(self, projectKey, issueTestExecKey, issueTestKey, bugSummary, bugDescription, bugAssignee):
        response = self.createIssueWithRawData(projectKey, ISSUE_BUG_NAME, bugSummary, bugDescription, bugAssignee)
        if (response.status == Response.STATUS_OK):
            #jiraIssueHandler.createIssueLinkWithRawData(ISSUELINKTYPE_BLOCKS_BY, issueTestKey, response.key)
            #self.addIssueWatcher(response.key, bugAssignee)
            testRunId = self.getTestRunId(issueTestExecKey, issueTestKey)
            self.addDefectToTestRun(testRunId, response.key)
            
        return response

    def finishIssueTestRun(self, issueTestExecKey, issueTestKey, testRunStatus, testResolution=""):
        self.changeIssueTransition(issueTestKey, TEST_STATUS_DONE_ID, testResolution)
        testRunId = self.getTestRunId(issueTestExecKey, issueTestKey)
        self.changeIssueTestRunStatus(testRunId, testRunStatus)

    #Simula envio de email de notificação do bug pelo Jira
    #TODO: configurar JIRA para enviar assim que o Bug for criado
    def sendBugEmailNotification(self, testExecIssueKey, testIssueKey, bugIssueKey):
        testExecInfo = JiraIssueInfo(testExecIssueKey, self.getIssueSummary(ISSUE_TESTEXEC_KEY))
        testIssueInfo = JiraIssueInfo(testIssueKey, self.getIssueSummary(testIssueKey))
        bugIssueInfo = JiraIssueInfo(bugIssueKey, self.getIssueSummary(bugIssueKey))
        subject = self.utils.getEmailSubject(testExecInfo, testIssueInfo, bugIssueInfo)
        messageText = self.utils.getTextlEmailMessage(testExecInfo, testIssueInfo, bugIssueInfo)
        messageHtml = self.utils.getHtmlEmailMessage(testExecInfo, testIssueInfo, bugIssueInfo)
        self.sendEmail.send(EMAIL_TO_NOTIFICATION, EMAIL_CC_NOTIFICATION, subject, messageText, messageHtml)
# -*- coding: utf-8 -*-

from send_email import SendEmail

mailto_list = ['*****@*****.**']
subject = 'Time to book dinner !!!!!!!'
msg = 'Time to book dinner !!!!!!!'
s = SendEmail(mailto_list, subject, msg)
if s.send_mail():
    print("发送成功")
else:
    print("发送失败")
import time
from store import AmazonStorePro
from settings import MYSQL_CONFIG_SERVER
from send_email import SendEmail
import datetime

sql_asin = "update crawler_amazon_track_task set wtc_crawl_time=%s where wtc_status=1"


def update_time(ut):
    store = AmazonStorePro(**MYSQL_CONFIG_SERVER)  # 服务器本地切换
    store.execute_sql(sql_asin, ut)
    store.close()


if __name__ == '__main__':
    crawl_time = '23:50:55'
    crawl_date_time = '{} {}'.format(time.strftime("%Y-%m-%d"), crawl_time)
    crawl_date = datetime.datetime.strptime(crawl_date_time,
                                            "%Y-%m-%d %H:%M:%S")
    set_crawl_date = crawl_date - datetime.timedelta(days=1)
    print(set_crawl_date)
    update_time(set_crawl_date)
    send_email = SendEmail()
    context = '采集任务时间设置为: {}'.format(set_crawl_date)
    send_email.send_message('设置任务采集时间', '*****@*****.**', '成功设置任务采集时间',
                            context)
Example #20
0
from threading import Thread
import network_test_class as ntc
from send_email import SendEmail
from getpass import getpass

if __name__ == '__main__':

    # Define all parameters in order to send frequent email-reports
    email_report = SendEmail()
    email_report.sender_from_email = input("Type email address for login:"******"Type email address for receiving the report:")
    email_report.password = getpass(
        "Type your password for login to email account and hit enter:")

    # Start thread which does the actual network analysis
    Thread(target=ntc.InteractivePlots()).start()

    # Start thread which sends frequent email reports
    Thread(target=email_report.send_weekly_report())
sys.path.append('./function')
from HTMLTestRunner import HTMLTestRunner
from send_email import SendEmail

test_dir = './interface'
test_report = './report'
discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py')


def new_report(testreport):
    lists = os.listdir(testreport)
    #查找最新报告
    lists.sort(key=lambda fn: os.path.getmtime(testreport + "\\" + fn))
    file_new = os.path.join(testreport, lists[-1])
    #print(file_new)
    return file_new


if __name__ == "__main__":
    em = SendEmail()
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = './report/' + now + '_result.html'
    fp = open(filename, 'wb')
    runner = HTMLTestRunner(stream=fp,
                            title='Test Report',
                            description='Implementation Example with:')
    runner.run(discover)
    fp.close()

    new_report = new_report(test_report)
    em.sendemail(new_report)
Example #22
0
def log_and_email(msg, title="提醒"):
    log(msg)
    SendEmail(title, msg)
from get_message import GetMessage
from send_email import SendEmail
from database import Database

if __name__ == '__main__':
    # Define variables to connect to MySQL database
    user = '******' # Set username of MySQL server
    password = '' # Set password of MySQL server
    d = Database(user, password)

    n = int(input("Number of queries"))
    for query in range(n):
        email=input("Email address")
        series = input("TV Series").split(',')
        message = "\n"
        #Create an object for Database class
        #Connect to database and insert the data in the table.
        d.write(email,series)
        for i in series:
            #Create an object for GetMessage class which can determine the next episode date of the TV Series.
            m = GetMessage(i)
            #print(a.get_imdb_url())
            message+="Tv series name: "+i+"\n"
            message+="Status: "+m.get_episode_date()+"\n"
            #print(message)
            message+="\n"

        #Send the result to user's email
        e = SendEmail(email,message)
        e.send()
Example #24
0
import time

from hello import Hello
from send_email import SendEmail

email = SendEmail()


def send_email(msg):
    email.send('hello_goddess', msg, ['*****@*****.**'])


def main():
    hello = Hello(True, ['葛'])
    hello.inform(send_email)
    while True:
        hello.get_sport_rank()
        hello.add_friend()
        hello.get_friend()
        hello.save_to_mysql()
        time.sleep(3 * 60)


if __name__ == '__main__':
    main()