예제 #1
0
파일: main.py 프로젝트: BarbaraEMac/TrivBot
    def post(self, user):
        email = self.request.get('email')

        if is_good_email(email) and not user.first_name == '':
            Emailer.invite(email, user)
        else:
            self.response.set_status(400)
예제 #2
0
파일: main.py 프로젝트: BarbaraEMac/TrivBot
    def post(self, user):
        question = self.request.get('question')
        correct = self.request.get('correct')
        cat = self.request.get('category')
        diff = self.request.get('difficulty')
        incorrect_1 = self.request.get('incorrect_1')
        incorrect_2 = self.request.get('incorrect_2')
        incorrect_3 = self.request.get('incorrect_3')

        if not question == 'Question':
            q = Question(question=question,
                         opt_1=correct,
                         opt_2=incorrect_1,
                         opt_3=incorrect_2,
                         opt_4=incorrect_3,
                         answer=correct,
                         state='not_approved',
                         category=cat,
                         difficulty=diff,
                         submitter=user)
            q.put()

        Emailer.feedback(question, correct, incorrect_1, incorrect_2,
                         incorrect_3, user)

        self.redirect('/about')
예제 #3
0
파일: cron.py 프로젝트: BarbaraEMac/TrivBot
    def get(self):
        troupes = Troupe.all()
        winners = []
        players = []

        for t in troupes:
            members = t.get_uuid_memberlist()

            for m in members:
                logging.error("XX %s %s" % (m[0], m[1]))

            winners.append(User.get_by_uuid(members[0][1]))
            players.append(len(members))

            if len(members) > 1:
                winners.append(User.get_by_uuid(members[1][1]))
                players.append(len(members))

            if len(members) > 2:
                winners.append(User.get_by_uuid(members[2][1]))
                players.append(len(members))

        Emailer.adminMonthlySummary(winners, players)

        users = User.all()

        for u in users:
            # Make sure they played this month.
            if u.get_days_played() > 0:
                taskqueue.add(queue_name='dailyEmailQueue',
                              url='/queue/monthlySummary',
                              params={'uuid': u.uuid})
예제 #4
0
파일: main.py 프로젝트: BarbaraEMac/TrivBot
 def post( self, user ):
     email = self.request.get( 'email' )
     
     if is_good_email( email ) and not user.first_name == '':
         Emailer.invite( email, user )
     else:
         self.response.set_status( 400 )
예제 #5
0
파일: cron.py 프로젝트: BarbaraEMac/TrivBot
    def get( self ):
        troupes = Troupe.all()
        winners = []
        players = []

        for t in troupes:
            members = t.get_uuid_memberlist()

            for m in members:
                logging.error("XX %s %s" % (m[0], m[1]) )

            winners.append( User.get_by_uuid( members[0][1] ) )
            players.append( len(members) )
            
            if len(members) > 1:
                winners.append( User.get_by_uuid( members[1][1] ) )
                players.append( len(members) )
            
            if len(members) > 2:
                winners.append( User.get_by_uuid( members[2][1] ) )
                players.append( len(members) )
            
        Emailer.adminMonthlySummary( winners, players )

        users = User.all()

        for u in users:
            # Make sure they played this month.
            if u.get_days_played() > 0:
                taskqueue.add( queue_name = 'dailyEmailQueue', 
                               url        = '/queue/monthlySummary',
                               params     = {'uuid' : u.uuid} )
예제 #6
0
    def test_from_sitewide_integration(self):
        """Test the ability to load an Emailer from a sitewide integration."""
        integration = self._integration()
        emailer = Emailer.from_sitewide_integration(self._db)

        # The Emailer's configuration is based on the sitewide integration.
        eq_("smtp_username", emailer.smtp_username)
        eq_("smtp_password", emailer.smtp_password)
        eq_("smtp_host", emailer.smtp_host)
        eq_("me@registry", emailer.from_address)

        # Default EmailTemplates have been created for all known email types.
        for email_type in Emailer.EMAIL_TYPES:
            template = emailer.templates[email_type]
            eq_(Emailer.SUBJECTS[email_type], template.subject_template)
            eq_(Emailer.BODIES[email_type], template.body_template)

        # Configure custom subject lines and body templates for the
        # known email types, and build another Emailer.
        for email_type in Emailer.EMAIL_TYPES:
            integration.setting(email_type +
                                "_subject").value = ("subject %s" % email_type)
            integration.setting(email_type + "_body").value = ("body %s" %
                                                               email_type)
        emailer = Emailer.from_sitewide_integration(self._db)
        for email_type in Emailer.EMAIL_TYPES:
            template = emailer.templates[email_type]
            eq_("subject %s" % email_type, template.subject_template)
            eq_("body %s" % email_type, template.body_template)
예제 #7
0
파일: servers.py 프로젝트: TheDerpySage/BB
class Reporting(object):
    def __init__(self, bot, channel_id, givenServers, givenServices):
        self.servers = givenServers
        self.services = givenServices
        #the report list keeps track of down servers already reported so we dont repeat notifications
        self.report = []
        #the channel we send notifications to
        self.channel = bot.get_channel(channel_id)
        self.emailer = Emailer(bb_config.host, bb_config.username,
                               bb_config.password)

    async def process(self):
        temp = self.report.copy()
        for x in self.servers:
            # x[name, ip]
            if bool_ping(x[1]):
                if x[0] in self.report:
                    temp.remove(x[0])
                    await self.channel.send(":white_check_mark: " + x[0] +
                                            " is back up.")
                #else still up so no need to repeat
            else:
                if x[0] not in self.report:
                    temp.append(x[0])
                    await self.channel.send(":no_entry: " + x[0] +
                                            " is unresponsive.")
                #else still unresponsive so no need to repeat
        for x in self.services:
            # x[name, ip, port]
            if bool_socket(x[1], x[2]):
                if x[0] in self.report:
                    temp.remove(x[0])
                    await self.channel.send(":white_check_mark: " + x[0] +
                                            " is back up.")
            else:
                if x[0] not in self.report:
                    temp.append(x[0])
                    await self.channel.send(":no_entry: " + x[0] + " is down.")
        # Get our differences based on our two reports
        recovered = set(self.report) - set(temp)
        died = set(temp) - set(self.report)
        # Overwrite the report
        self.report = temp
        # Notify if there's something worth reporting
        if bb_config.send_alerts_to != '':
            if recovered or died:
                body = ""
                if died:
                    body += "The following have stopped responding\n"
                    for x in died:
                        body += x.split('.')[0] + "\n"
                    body += "\n"
                if recovered:
                    body += "The following have recovered\n"
                    for x in recovered:
                        body += x.split('.')[0] + "\n"
                    body += "\n"
                body += "Please login and check running services."
                self.emailer.send_email(bb_config.send_alerts_to, 'Alert!',
                                        body)
예제 #8
0
 def __init__(self, host: str, path: str, timestamp=datetime.datetime.now(), spreadsheet_id=SPREADSHEET_ID):
   self.host = host
   self.path = path
   self.renderer = SheetsRenderer(spreadsheet_id)
   self.fetcher: Fetcher = Fetcher(s, self.host)
   self.listing_cache: ListingCache = ListingCache("/tmp/cache-%s" % host, self.fetcher)
   self.emailer = Emailer(self.host, "/tmp/email_log")
   self.timestamp = timestamp
예제 #9
0
def envoiemail():
    now = datetime.datetime.now()
    timee = now.strftime("%d-%m-%Y %H:%M:%S")
    sender = Emailer()
    sendTo = '*****@*****.**'
    emailSubject = "Avertir jerome ou loic, Reboot du raspberry a " + timee
    emailContent = "une ou des sondes ne repondent plus " + timee
    sender.sendmail(sendTo, emailSubject, emailContent)
예제 #10
0
	def handle_new_signals(self):
		if self.to_email:
			emailer = Emailer()
			for a in self.new_signals_array:
				if len(a) > 0:
					sig = a[-1]
					if sig.type == Sig.BUY or sig.type == Sig.SELL:
						emailer.email_signal(sig)
예제 #11
0
    def post( self ):
        uuid = self.request.get( 'uuid' ) 
        u    = User.get_by_uuid( uuid )

        random.seed( uuid )

        time.sleep( random.randint(0, 29) )

        Emailer.dailyEmail( u )
예제 #12
0
파일: servers.py 프로젝트: TheDerpySage/BB
 def __init__(self, bot, channel_id, givenServers, givenServices):
     self.servers = givenServers
     self.services = givenServices
     #the report list keeps track of down servers already reported so we dont repeat notifications
     self.report = []
     #the channel we send notifications to
     self.channel = bot.get_channel(channel_id)
     self.emailer = Emailer(bb_config.host, bb_config.username,
                            bb_config.password)
예제 #13
0
    def post( self ):
        uuid = self.request.get( 'uuid' ) 
        u    = User.get_by_uuid( uuid )

        random.seed( uuid )

        time.sleep( random.randint(0, 29) )

        Emailer.monthlySummary( u )
       
        u.reset()
예제 #14
0
 def __init__ (self, recipes, attachment_types=["pdf"], do_text=True):
     Emailer.__init__(self)
     self.attachments_left = self.attachment_types = list(attachment_types)
     self.attached = []
     self.recipes = recipes
     self.rg = get_application()
     self.rd = self.rg.rd
     self.change_units=self.rg.prefs.get('readableUnits',True)
     if len(recipes) > 1:
         self.subject = _("Recipes")
     elif recipes:
         self.subject = recipes[0].title
예제 #15
0
 def __init__(self, recipes, attachment_types=["pdf"], do_text=True):
     Emailer.__init__(self)
     self.attachments_left = self.attachment_types = list(attachment_types)
     self.attached = []
     self.recipes = recipes
     self.rg = get_application()
     self.rd = self.rg.rd
     self.change_units = self.rg.prefs.get('readableUnits', True)
     if len(recipes) > 1:
         self.subject = _("Recipes")
     elif recipes:
         self.subject = recipes[0].title
예제 #16
0
    def check_game_availability(self):
        emailer = None
        sql_dao = SQLDao()
        try:
            sql_dao.build_hockey_games_table()
            try:
                emailer = Emailer(gmail_user, gmail_password)
            except Exception as e:
                print('Exception while starting emailer: {}'.format(e))
                print('proceeding with console messages instead...')
                emailer = lambda msg: println(msg)

            game_statuses = self.get_game_statuses(sql_dao)

            did_game_change = any(
                [g.did_game_become_available() for g in game_statuses])
            if did_game_change:
                print("A game changed to available, sending email...")
                emailer.send_game_status_emails(game_statuses)
            else:
                print("No game changed state, not sending email...")
                errors_getting_game_availability = any(
                    [g.is_game_sold_out is None for g in game_statuses])
                if errors_getting_game_availability:
                    print("Errors getting game availability, sending email...")
                    emailer.send_error_email()

        except Exception as e:
            print('Exception while starting emailer: {}'.format(e))

        finally:
            if emailer and not callable(emailer):
                print('Closing SMTP Connection')
                emailer.close()
예제 #17
0
	def check_page(self):
		print "checking..."
		if self.did_change():
			print "Sending email"
			emailer = Emailer(self.email)
			self.message += "\n" + self.url + " changed on " + str(datetime.datetime.now()) + "."
			emailer.send_message(self.message)
			emailer.notify(
					title = 'Website changed',
					subtitle = '',
					message = self.message.strip(),
					open = self.url
					)
			self.done = True
예제 #18
0
 def getNickName(self, name):
     _name = name.strip()
     if _name.encode('utf-8') in self.book:
         return self.book[_name.encode('utf-8')]
     else:
         emailer = Emailer()
         message = 'Dear Reminders Admin,' + \
             "\n\nPlease, have a look at {} nickname because it wasn't found in the contact book."\
             .format(name.encode('utf-8')) + \
             '\n\nThanks in advance for cooperation!!' + \
             '\n\nKind Regards,' + \
             '\nFernando'
         emailer.send_adm_msg(
             'Unknown Nickname for {}'.format(name.encode('utf-8')),
             message)
         return _name
예제 #19
0
    def test_run(self):
        class Mock(Emailer):
            sent = None

            def send(self, template_name, to_address):
                Mock.sent = (template_name, to_address)

        cmd_args = [
            "--host=a_host", "--port=25", "--username=a_user",
            "--password=a_password", "[email protected]",
            "--from-name=Administrator", "[email protected]"
        ]
        script = ConfigureEmailerScript(self._db)
        script.do_run(self._db, cmd_args=cmd_args, emailer_class=Mock)

        # The ExternalIntegration is properly configured.
        emailer = Emailer._sitewide_integration(self._db)
        eq_("a_user", emailer.username)
        eq_("a_password", emailer.password)
        eq_("a_host", emailer.url)
        eq_(25, emailer.setting(Emailer.PORT).int_value)
        eq_("*****@*****.**", emailer.setting(Emailer.FROM_ADDRESS).value)
        eq_("Administrator", emailer.setting(Emailer.FROM_NAME).value)

        # An email was sent out to the test address.
        template, to = Mock.sent
        eq_("test", template)
        eq_("*****@*****.**", to)
예제 #20
0
파일: main.py 프로젝트: BarbaraEMac/TrivBot
    def post( self, user ):
        question    = self.request.get( 'question' )
        correct     = self.request.get( 'correct' )
        cat         = self.request.get( 'category' )
        diff        = self.request.get( 'difficulty' )
        incorrect_1 = self.request.get( 'incorrect_1' )
        incorrect_2 = self.request.get( 'incorrect_2' )
        incorrect_3 = self.request.get( 'incorrect_3' )

        if not question == 'Question':
            q = Question( question=question, opt_1=correct, opt_2=incorrect_1, opt_3=incorrect_2, opt_4=incorrect_3, answer=correct, state='not_approved', category=cat, difficulty=diff, submitter=user )
            q.put()

        Emailer.feedback ( question, correct, incorrect_1, incorrect_2, incorrect_3, user )

        self.redirect( '/about' )
예제 #21
0
def watch_canary(f):
    initial_file_access_time = stat(f).st_atime
    sleep(5)

    while True:
        file_access_time = stat(f).st_atime

        if file_access_time != initial_file_access_time:

            gmail_address = environ["GMAIL_ADDR"]
            gmail_password = environ["GMAIL_PASS"]

            with Emailer("smtp.gmail.com", 465) as email:

                # Remove print statements when running as cronjob or
                # scheduled task
                if email.authenticate(gmail_address, gmail_password):
                    print("{*} Authentication successful!")
                else:
                    print("{-} Authentication unsuccessful!")

                subject = "[WARNING] Canary Triggered"
                now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
                message = f"[{now}] Someone accessed the canary file:\n\t {realpath(f)}"

                if email.send(gmail_address, subject, message):
                    print("{*} Successfully sent email!")
                else:
                    print("{*} Email could not be sent!")
            break
        sleep(5)
예제 #22
0
파일: app.py 프로젝트: Kimbsy/feed-me
    def loop(self):
        print('\nWhat would you like to do?')
        print('1) Load this week\'s meals')
        print('2) Generate new meals')
        print('3) Hold specific meals')
        print('4) Save current meals')
        if hasattr(self, 'meals'):
            print('5) Email shopping list for current meals')

        choice = input().replace(' ', '')

        if not choice.isnumeric():
            os.system('clear')
            print('please enter a number between 1 and 4')
            return
        else:
            choice = int(choice)

        if choice == 1:
            # @TODO: load saved meals
            os.system('clear')
            print('loading current meals...')
            self.meals = []
            self.print_meals()
        elif choice == 2:
            os.system('clear')
            print('generating meals...\n')
            self.meals = self.get_random_meals([])
            self.print_meals()
        elif choice == 3:
            print('make selections:')
            choices = self.get_choices()
            self.meals = self.get_random_meals(choices)
            os.system('clear')
            print('generating meals...\n')
            self.print_meals()
        elif choice == 4:
            os.system('clear')
            print('saving meals...')
            # @TODO: save meals
        elif choice == 5:
            os.system('clear')
            print('emailing shopping list...')
            emailer = Emailer(self.meals)
            emailer.send_list()
예제 #23
0
 def __init__(self):
     self.statistics = {
         'total_matches': 0,
         'swipes': 0,
         'cur_matches': 0,
         'match_rate': 0
     }
     statistics_path = 'tinder_statistics.csv'
     if os.path.exists(statistics_path):  # Get current statistics
         with open(statistics_path, newline='') as csvfile:
             csv_data = csv.reader(csvfile, delimiter=' ', quotechar='|')
             for row in csv_data:
                 self.statistics[row[0]] = float(row[1])
     else:
         open(statistics_path, 'w').close()
     self.current_matches = []
     match_ids_path = "match_ids.txt"  # Get already existing matches
     if os.path.exists(match_ids_path):
         with open(match_ids_path, 'r') as ids_file:
             for _id in ids_file:
                 self.current_matches.append(_id.rstrip("\n\r"))
     else:
         open(match_ids_path, 'w').close()
     self.account_token = config.tinder_token
     self.matches = {}
     self.last_like_at = None
     self.last_auth_at = None
     track_time = "track_time.txt"
     if os.path.exists(track_time) and os.stat(track_time).st_size != 0:
         with open(track_time, 'r') as track_f:
             for i, time in enumerate(track_f):  # this iterate only twice
                 if i == 0:
                     self.last_like_at = datetime.strptime(
                         time.split('@')[1].rstrip('\n\r'),
                         '%m/%d/%y %H:%M:%S')
                 if i == 1:
                     self.last_auth_at = datetime.strptime(
                         time.split('@')[1].rstrip('\n\r'),
                         '%m/%d/%y %H:%M:%S')
     else:
         f = open(track_time, 'w')
         f.write('last_liked@none\n')
         f.write('last_auth@none\n')
         f.close()
     self.emailer = Emailer()
예제 #24
0
파일: reddit.py 프로젝트: cjh232/BAPS-Bot
    def execute_search(self, product_flair, limit):

        # Search the subreddit for items matching the product_flair

        res = self.subreddit.new(limit=limit)

        emailer = Emailer(secrets.sender, secrets.receiver, secrets.user,
                          secrets.password, secrets.smtp_domain,
                          secrets.smtp_port)

        for submission in res:
            if submission.link_flair_text.lower() == product_flair.lower(
            ) and not submission.stickied:
                match_object = SimpleNamespace()

                match_object.title = submission.title
                match_object.url = submission.url
                match_object.created_utc = submission.created_utc

                emailer.appendMessage(match_object)

        # TODO: Send email when no submissions were found
        if emailer.getQueueLength() > 0:
            emailer.sendEmail()
        else:
            print("No submission were found...")
예제 #25
0
def main(subject: str, place: str = None) -> None:
    """ to update(merge) csv file if latest csv file is sent by outlook
    serch and save attached the latest csv file of email and merge main csv file
    """

    main_csv_path = os.path.join(PathConfig.DIR_PATH, PathConfig.CSV_PATH)
    backup_csv_path = os.path.join(PathConfig.DIR_PATH,
                                   PathConfig.BACKUP_CSV_PATH)
    tz = TimeZone().get_timezone(place=place)

    last_day = CsvHander().get_latest_day(csv_path=main_csv_path, tz=tz)
    is_latest, between_dates = Clock().is_latest(date=last_day, tz=tz)
    if not is_latest:
        new_csv_paths = []

        # search email with old dates
        for date in between_dates:
            attachments = Emailer().search_mail_and_save_attachments(
                subject = MailConfig.GET_MAIL_SUBJECT.format(
                    subject=subject, date=date),
                save_path = os.path.join(PathConfig.DIR_PATH, \
                    PathConfig.RAW_CSV_PATH.format(date=date)),
                folder_name = MailConfig.GET_MAIL_FOLDER,
                )
            if attachments:
                for attachment in attachments:
                    new_csv_paths.append(attachment)
                last_day = date

        # merge latest csv file to main csv
        if new_csv_paths:
            for new_csv_path in new_csv_paths:
                CsvHander().merge_csv(csv_path=main_csv_path,
                                      new_csv_path=new_csv_path)

            CsvHander().copy_csv(csv_path_from=main_csv_path,
                                 csv_path_to=backup_csv_path)

    Emailer().create_new_mail(subject=MailConfig.SEND_MAIL_SUBJECT.format(
        subject=subject, date=last_day),
                              body=MailConfig.BODY.format(path=main_csv_path),
                              to=MailConfig.get_to(),
                              cc=MailConfig.get_cc(),
                              attach_paths=[main_csv_path])
예제 #26
0
파일: cron.py 프로젝트: BarbaraEMac/TrivBot
    def get( self ):
        # Fetch question
        q = get_question()
        
        # And mark it as used!
        if q:
            q.state = 'used'
            q.put()

        # Get a new question
        new_q = Question.all().filter("state = ", 'unused').get()
        
        # Set the day to today!
        new_q.day   = triv_today( )
        new_q.state = 'in_use'

        # Save the new question
        new_q.put()

        if Question.all().filter('state = ', 'unused').count() <= 3:
            Emailer.outOfQuestions()
예제 #27
0
파일: cron.py 프로젝트: BarbaraEMac/TrivBot
    def get(self):
        # Fetch question
        q = get_question()

        # And mark it as used!
        if q:
            q.state = 'used'
            q.put()

        # Get a new question
        new_q = Question.all().filter("state = ", 'unused').get()

        # Set the day to today!
        new_q.day = triv_today()
        new_q.state = 'in_use'

        # Save the new question
        new_q.put()

        if Question.all().filter('state = ', 'unused').count() <= 3:
            Emailer.outOfQuestions()
예제 #28
0
class EmailerTest(unittest.TestCase):
    def setUp(self):
        self.emailer = Emailer("*****@*****.**")
        self.emailer.alert_recipient = "*****@*****.**"

    @patch.object(smtplib.SMTP, 'sendmail')
    @patch('smtplib.SMTP')
    def test_sendMessage_simple_sends(self, sendmail_mock, server_mock):
        self.emailer._send_message("*****@*****.**", "hello", "there")
        sendmail_mock.assert_called_once()

    @patch.object(Emailer, "_send_message")
    def test_onAlert_outsideHuman2_sendsMessage(self, send_message_mock):
        alert = Alert("outside", "human", 2)
        self.emailer.on_alert(alert)
        send_message_mock.assert_called_once_with(
            "*****@*****.**", "Alert",
            "What: human; Where: ouside; Level: 2")
        #test for call content

    @patch.object(Emailer, "_send_message")
    def test_onAlert_outsideHuman1_sendsMessage(self, send_message_mock):
        alert = Alert("outside", "human", 1)
        self.emailer.on_alert(alert)
        send_message_mock.assert_not_called()
예제 #29
0
 def start(self, progress):
     if progress == 1:
         with Init() as i:
             i.checkUtils()
     if progress == 2:
         with JobScraper() as js:
             js.checkScrape()
     if progress == 3:
         with ScrapeEmails() as se:
             se.begin()
     if progress == 4:
         with Emailer() as e:
             e.begin()
예제 #30
0
def main():
    global data
    students = False

    if students:
        emails = getEmailsStudents()
    else:
        emails = getEmailsFaculty()

    with Emailer() as email:
        success = email.Send(emails)

    if success:
        file = './cu_students_remaining.txt' if students else './cu_research_faculty_remaining.txt'
        with open(file, 'w') as fout:
            fout.writelines(data[400:])
예제 #31
0
 def check_page(self):
     print "checking..."
     if self.did_change():
         print "Sending email"
         emailer = Emailer(self.email)
         self.message += "\n" + self.url + " changed on " + str(
             datetime.datetime.now()) + "."
         emailer.send_message(self.message)
         emailer.notify(title='Website changed',
                        subtitle='',
                        message=self.message.strip(),
                        open=self.url)
         self.done = True
예제 #32
0
    def run(self):
        while True:
            with open('/root/NJITCourseTracker/courses.json') as data_file:
            	courses = json.load(data_file)
            
           	foundCourses = app.execute(courses)
            
            if len(foundCourses) != 0:
            	body = 'The following course(s) have just opened up: <br> <ul>'
            	
            	for foundCourse in foundCourses:
            		body = body + '<li>'+foundCourse+'</li>'

            	body = body + '</ul>'

            	email = Emailer('*****@*****.**', '*****@*****.**', 'NJIT Course Tracker - Course(s) Opened', body)

            	body.send()

            time.sleep(1800)
예제 #33
0
    def test__send_email(self):
        """Verify that send_email calls certain methods on smtplib.SMTP."""
        integration = self._integration()
        emailer = Emailer.from_sitewide_integration(self._db)
        mock = MockSMTP()
        emailer._send_email("you@library", "email body", mock)

        # Five smtplib.SMTP methods were called.
        connect, starttls, login, sendmail, quit = mock.calls
        eq_(('connect', (emailer.smtp_host, emailer.smtp_port), {}), connect)

        eq_(('starttls', (), {}), starttls)

        eq_(('login', (emailer.smtp_username, emailer.smtp_password), {}),
            login)

        eq_(('sendmail',
             (emailer.from_address, "you@library", "email body"), {}),
            sendmail)

        eq_(("quit", (), {}), quit)
예제 #34
0
def send_email_by_indexes(config: Configuration, excel: SalaryFileReader,
                          generator: EmailGenerator, emailer: Emailer):
    email = config['tester_email']
    user_info = get_user_info_by_index(excel)
    if user_info:
        email = input_email(
            '请输入邮箱: ' if email is None else '请输入邮箱 或直接使用 %s: ' % email, False,
            email)
        if email:
            config['tester_email'] = email
        else:
            email = config['tester_email']
        if not email:
            return False
        path = generator.make_file(user_info)
        print(path)
    else:
        print('Error index')
        return False
    print('---->', email)
    email_content = generator.make_email(user_info)
    return emailer.send(email, email_content['subject'],
                        email_content['content'], path)
    pass
예제 #35
0
        print 'ERROR - Could not join the thread pool!'
        sys.exit(-1)

    # finished crawling
    num_warmed = len(crawler.results)
    finished = (float(time.time() - started) / 60)

    # save the results to a csv file
    with open('%s/crawler-log.csv' % PATH, 'wb') as f:
        headers = ['URL', 'Status Code', 'Elapsed (ms)', 'Redirect']
        logger = csv.writer(f)
        logger.writerow(headers)
        logger.writerows(crawler.results)

    # prepare email
    emailer = Emailer()
    subject = "Warmed %i Pages" % num_warmed
    html = ("Warmed %i pages in %i minutes. Please review the attached"
            " log for more information on the pages crawled.") % (num_warmed,
                                                                  finished)
    attachments = ['%s/crawler-log.csv' % PATH]

    webhook = os.environ.get('WEBHOOK', False)
    protocol = os.environ.get('PROTOCOL', 'https')
    domain = os.environ.get('DOMAIN', False)

    # Send a Slack Webhook
    if webhook:
        payload = {
            'attachments': [{
                "fallback":
예제 #36
0
from video_requester import VideoRequest, Video
from emailer import Emailer

CHANNEL_ID = ''  # Insert channel ID
PLAYLIST_ID = ''  # Insert playlist ID
NUM_ITEMS = 20

mailer = Emailer('target_email', 'your_email', 'email_subject_line')  # Replace these with desired options

# Load all the previously checked videoIDs from the file
with open("video_log.txt", "a+") as f:
    already_checked = f.readlines()

# Request the videos and retrieve response in an array
requester = VideoRequest(CHANNEL_ID, PLAYLIST_ID, NUM_ITEMS)
requester.request_videos(NUM_ITEMS)
videos = requester.parse_response()

# Sort the videos with the corresponding query in the title into a new array
successes = []
for vid in videos:
    if "desired_query" in vid.title:
        successes.append(vid)

# Check that these videos have not already been notified for
for vid in successes:
    found = False
    if not already_checked:
        found = False

    for line in already_checked:
예제 #37
0
from csv_handler import generate_csv, get_list_from_csv
import os
import sys

if __name__ == '__main__':

    DEBUG = False

    if DEBUG:

        class Logger:
            @staticmethod
            def info(text):
                print(text)

    emailer = Emailer(os.getenv('EMAILER_ADDRESS'),
                      os.getenv('EMAILER_PASSWORD'))

    input_file = 'sample_in.csv'  # CSV with all therapists email
    output_file = 'sample_out.csv'  # CSV with all the already sent emails

    all_therapists = get_list_from_csv(input_file)
    all_sent_therapists = get_list_from_csv(output_file)
    all_sent_emails = [
        therapist['contact_email'] for therapist in all_sent_therapists
    ]

    NUM_OF_EMAILS_TO_SEND = None
    NUM_OF_EMAILS_SENT_NOW = 0
    if len(sys.argv) > 1:
        try:
            NUM_OF_EMAILS_TO_SEND = int(sys.argv[1])
예제 #38
0
def send_completion_mail(smtp, email_config, username, gethostname, filename,
                         home_dirs, summary):
    '''
    Config Setup
    >>> from ConfigParser import SafeConfigParser
    >>> cp = SafeConfigParser()
    >>> cp.add_section('email')
    >>> cp.set('email', 'user_domain', 'kumc.edu')
    >>> cp.set('email', 'sender', '*****@*****.**')
    >>> cp.add_section('output')
    >>> cp.set('output', 'home_dirs', '/home')

    >>> import os
    >>> fs = lafile.Readable('/', os.path, os.listdir, open)
    >>> config_dir = lafile.ConfigRd(cp, fs)

    Mock Host
    >>> gethostname = lambda : 'mock_host'

    Mock SMTP
    >>> mocksmtp = MockSMTP()

    Sending completion email
    >>> send_completion_mail(mocksmtp, config_dir / 'email', 'somebody',
    ...                      gethostname, 'data.db',
    ...                      (config_dir / 'output' / 'home_dirs').fullPath(),
    ...                      'some summary')
    MockSMTP:sendmail()
    ===================
    FROM:[email protected]
    TO:['*****@*****.**']
    ===================
    Content-Type: text/plain; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Subject: The dataset 'data.db' is now available
    From: [email protected]
    To: [email protected]
    <BLANKLINE>
    The dataset data.db is now available on mock_host at '/home/somebody/heron'
    <BLANKLINE>
    ====DATA SUMMARY====
    some summary

    Modify sendmail to raise an IOError
    >>> def sendmailex(sender, receiver, msg):
    ...     raise IOError
    >>> mocksmtp.sendmail = sendmailex

    Failure to send the e-mail will result in a logged warning *trust me*,
    but will otherwise continue on.
    >>> send_completion_mail(mocksmtp, config_dir / 'email', 'somebody',
    ...                      gethostname, 'data.db',
    ...                      (config_dir / 'output' / 'home_dirs').fullPath(),
    ...                      'some summary')
    '''
    if email_config.exists():
        domain = email_config.get('user_domain')

        #TODO get actual users email (from json)
        #It is an unfortunate hack that we use the [username]+[config domain]
        recipient = '{0}@{1}'.format(username, domain)
        recipient = '[email protected],[email protected]'
        emailer = Emailer(smtp, lambda: [r for r in recipient.split(',')])

        message_kwds = {'filename': filename,
                        'hostname': gethostname(),
                        'location': '%s/%s' % (home_dirs, username),
                        'summary': summary}
        body = 'The dataset {filename} is now available on {hostname} ' \
               'at \'{location}\'' \
               '\n\n====DATA SUMMARY====\n{summary}'.format(**message_kwds)
        subject = 'The dataset \'{filename}\' is now available'.format(
            **message_kwds)

        sender = email_config.get('sender')
        log.info('dfbuilder.py:send_completion_mail()\n From: %s\n To: %s'
                 % (sender, recipient))
        try:
            emailer.sendEmail(body, subject, sender)
        except Exception as ex:
            log.warning('Exception sending e-mail!',
                        exc_info=ex)