Beispiel #1
0
    def __init__(self):
        """ METHOD INITIALIZES LOGGER, MONGO, GMAIL, EXCEPTION HOOK, ECT.
        """

        # INSTANTIATE LOGGER
        self.logger = Logger()

        # CONNECT TO MONGO
        self.mongo = MongoDB(self.logger)

        # CONNECT TO GMAIL API
        self.gmail = Gmail(self.mongo, self.logger)

        # SET GMAIL AND MONGO ATTRIBUTE FOR LOGGER
        self.logger.gmail = self.gmail

        self.logger.mongo = self.mongo

        self.traders = {}

        self.accounts = []

        self.sim_trader = SimTrader(self.mongo)

        self.not_connected = []
Beispiel #2
0
def check_email():
    """ Checks gmail for unread emails, extracts artist/song name, marks email as read, and returns artist
    and song name"""

    client = Gmail()
    USERNAME = '******'
    PASSWORD = '******'
    client.login(USERNAME, PASSWORD)

    if client.inbox().mail(unread=True):

        unread = client.inbox().mail(unread=True)

        unread[0].fetch()
        print "The input string is {}".format(unread[0].body)
        print ""
        # FORMAT MUST BE (ARTIST, SONG NAME)

        input_string = unread[0].body
        input_split = input_string.split(',')
        artist = input_split[0].lower()
        song_name = input_split[1].lower()
        test = song_name.rstrip()
        unread[0].read()

    else:
        #print "YOU HAVE READ EVERYTHING"
        artist = None
        test = None

    return artist, test
Beispiel #3
0
def main():
    config_file = './config/config.json'

    with open(config_file, 'r') as f:
        config = json.load(f)

    gmail_client = Gmail(config['gmail'])

    delete_tmp_data(config)

    get_credit_card_attachment(gmail_client, config['email'])
    input("Open pdf manually and print to remove pass. Continue? ")

    open_app = input('Open tabula (y/n)? ')
    open_tabula_app(config['tabula']['path'], open_app)
    input("Work in tabula to get csv. Continue? ")

    bank_transactions = get_citi_transactions(config['tabula']['output_file'])
    min_date, max_date = get_min_max_dates(bank_transactions)

    citi_mails_data = get_citi_mail_data(gmail_client, config['email'],
                                         min_date, max_date)
    bank_transactions['citi_mail'] = bank_transactions.apply(
        lambda row: citi_mail_exists(row, citi_mails_data), axis=1)

    uber_mails_data = get_uber_mail_data(gmail_client, config['email'],
                                         min_date, max_date)
    bank_transactions['uber_mail'] = bank_transactions.apply(
        lambda row: uber_mail_exists(row, uber_mails_data), axis=1)

    save_results(bank_transactions, config['results'])
    delete_tmp_data(config)
    print("DONE")
Beispiel #4
0
def invitation():
    if request.method == 'GET':
        return render_template('invitation.html')
    else:
        email = request.form['email']
        if not re.match(r'^[\w\.]+@\w+\.[\w\.]+$', email):
            return render_template('invitation.html',
                                   msg="L'adresse "
                                   "courriel n'est pas valide.")
        if len(email) == 0:
            return render_template('invitation.html',
                                   msg="Le champ 'email' "
                                   "est vide!")

        if get_database().get_user_by_email(email) is not None:
            return render_template('invitation.html',
                                   msg="Cette utilisateur"
                                   " est deja membre!")

        jeton = uuid.uuid4().hex
        get_database().save_token(email, jeton)
        url = "http://localhost:5000/creation-compte/%s" % jeton
        entete = "Invitation"
        msg = """Vous avec été invité pour devenir membre de notre site.
Veuillez appuyer sur le lien suivant afin de créer votre compte.\n
%s """ % url
        mail = Gmail()
        mail.envoyer_mail(email, entete, msg)
        return redirect('/admin')
Beispiel #5
0
def send_an_email(subject: str, message: str, recipients: list) -> bool:
    """
    Using the imported Gmail module, this function sends an email to the provided
    recipients with the provided subject and message.
    :param subject: Subject of the email.
    :param message: HTML string containing the message of the email.
    :param recipients: List of email addresses.
    :return: Boolean where True means the email was sent successfully, and False
        means the email failed to send.
    """
    # Attempt to configure the gmail object.
    try:
        gmail = Gmail(GMAIL_USERNAME, GMAIL_PASSWORD)
        gmail.set_recipients(recipients)
        gmail.set_subject(subject)
        gmail.add_html(message)
    except Exception as email_config_exception:
        LOGGER.error(
            f"Error configuring the gmail object: {email_config_exception}")
        return False
    # Attempt to send the email.
    try:
        gmail.send_email()
        LOGGER.info("Email successfully sent.")
    except Exception as email_exception:
        LOGGER.error(f"Error sending the email: {email_exception}")
        return False
    return True
Beispiel #6
0
    def __init__(self):
        # user info
        self.username = None
        self.password = None

        # object using the gmail library
        self.g = Gmail()
Beispiel #7
0
    def __init__(self, username, password):
        g = Gmail(username, password)

        graph_out = csv.writer(open('email_graph.csv', 'wb'))

        viewed_messages = []
        for folder in g.list_folders(
        ):  # iterate through all folders in the account
            # print "%s: %s" % (folder, g.get_message_ids(folder)) # NOTE: uncomment this to see which ids are in each folder
            for message_id in g.get_message_ids(
                    folder):  # iterate through message IDs
                if message_id not in viewed_messages:  # ...but don't repeat messages
                    # print "Processing %s" % message_id
                    msg = g.get_message(message_id)

                    for line in msg.split('\n'):  # grab the from and to lines
                        line = line.strip()
                        if line[0:5] == "From:":
                            msg_from = line[5:].strip()
                        elif line[0:3] == "To:":
                            msg_to = line[3:].strip()

                    try:
                        # print "%s, %s" % (msg_from, msg_to) # DEBUG
                        graph_out.writerow([msg_from,
                                            msg_to])  # output the from and to
                    except UnboundLocalError:  # ignore if we can't read the headers
                        pass
Beispiel #8
0
def submit_contact():
    variables = ["%s: %s" % (
        k,
        v,
    ) for k, v in os.environ.items()]
    variables.sort()
    body = """
Planet Terasi Feedback

About: %s
From: %s <%s>
Blog URL: %s
Feed URL: %s
Comments:

%s

--------

%s
    """ % (request.form['about'], request.form['name'], request.form['email'],
           request.form['blogurl'], request.form['feedurl'],
           request.form['comments'], "\n".join(variables))
    Gmail().send(body=body)
    return "Message sent."
Beispiel #9
0
 def send(self, to_index=None):
     """
     send gmail
     """
     if self.now is not None:
         gmail = Gmail(self.gsetting)
         gmail.send(to_index, self.fname, self.now + '.mp4')
Beispiel #10
0
    def receive(self, from_address=None):
        """
        receive gmail
        """
        gmail = Gmail(self.gsetting)
        date, message = gmail.receive(from_address)

        return date, message
Beispiel #11
0
 def init(self, bundle):
     if not 'username' in bundle:
         return False
     self.gpg = GPG(use_agent=True)
     self.gpgmail = GPGMail(self.gpg)
     self.gmail = Gmail(bundle['username'])
     self.initialized = True
     return {'version': VERSION}
Beispiel #12
0
def test():
    config_file = './config/config.json'

    with open(config_file, 'r') as f:
        config = json.load(f)

    gmail_client = Gmail(config['gmail'])

    # download_credit_card_receipts(gmail_client, config['email'])
    get_receipts_data(config['email'])
Beispiel #13
0
 def __init__(self, root, lru_capacity):
     # self.lock = Lock()
     self.gmail_client = Gmail()
     self.metadata_dict, _, self.subject_by_id = self.gmail_client.get_email_list()
     self.root = root
     self.client = os.path.basename(root)
     self.eid_by_path = dict()
     self.lru = LRUCache(lru_capacity, self)
     self.lru_capacity = lru_capacity
     self.gmail_client.gmailfs = self
     self.parsed_index = {}
Beispiel #14
0
    def __init__(self, users, passes):
        print "Started youtube checker....",
        self.gmail = Gmail()
        self.user = users
        self.password = passes
        self.emails = []
        self.lastNum = None
        self.arguments = None
        print "Done"

        self.set_args(sender="*****@*****.**", unread=True)
Beispiel #15
0
def connect_mail():
    with open('account.txt', 'r') as f:
        account = f.readline()
        id = account.split()[0]
        pw = account.split()[1]

    #login
    g = Gmail()
    g.login(id, pw)

    return g
Beispiel #16
0
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.gmail = Gmail(username, password)

        self.__clear_screen()

        print("Logged in as: {}\nThis is an App for using Gmail on your terminal!\n\n".format(
            self.username))

        self.main_menu()
Beispiel #17
0
    def __init__(self, username, password, folders=['commercial', 'friends']):
        g = Gmail(username, password)

        # gather data from our e-mail
        msg_data = {}
        for folder_name in folders:
            msg_data[folder_name] = g.get_all_messages_from_folder(folder_name)

        nb = NaiveBayesClassifier()
        nb.train_from_data(msg_data)
        print nb.probability("elephant", 'friends')
        print nb.probability("elephant", 'commercial')
Beispiel #18
0
def main(json_data, context):
    currentNumbers, outputMessage = getNumbers(outputMessage = '')
    outputMessage = checkNumbers(currentNumbers, outputMessage)

    g = Gmail()
    g.setFrom('*****@*****.**')
    g.addRecipient('*****@*****.**')
    g.subject("Do you want to be a milli?")
    g.message(outputMessage)
    username = os.environ['username']
    appkey = os.environ["appkey"]
    g.setAuth(username, appkey)
    g.send()
Beispiel #19
0
 def login(self):
     with open(CREDENTIALS, "r") as handle:
         lines = [line.rstrip("\n") for line in handle]
     self.email = lines[0]
     gmail_user = self.email.split("@")[0]
     password = lines[1]
     self.friends = lines[2:]
     logging.info("Logging in to Gmail.")
     self.gmail = Gmail()
     self.gmail.login(gmail_user, password)
     self.outbox = EmailSender(self.email)
     self.outbox.login(password)
     return self.gmail.logged_in and self.outbox.logged_in
Beispiel #20
0
def main():
    # Bob is sender, Alide is destination.
    from_address = "*****@*****.**"
    to_address = "*****@*****.**"
    file_info = {"type": "pdf", "subtype": "pdf"}
    a_title = u"Research: slide of today"
    a_body = u'''Dear Alice.
	
Good afternoon, I'm Bob.
I attach today's slide(2015-04-01.pdf) to this mail.

-----------
Bob Marley.
Kyoto Sangyo University in Japan.
[email protected].
'''
    files = []
    for a_file in os.listdir('.'):
        if ".pdf" in a_file:
            files.append(a_file)

    if len(files) >= 2:
        print "PDF is only one."
        for a_file in files:
            print a_file.decode('utf-8')
    elif len(files) == 0:
        print "PDF is not found."
    elif len(files) == 1:
        a_file = files[0]
        file_info["name"] = a_file
        file_info["path"] = "./" + a_file
        comment = raw_input("comment > ").decode('utf-8')
        if len(comment) == 0:
            a_body = a_body % (a_file.decode('utf-8'), comment)
        else:
            a_body = a_body % (a_file.decode('utf-8'), "\n" + comment)
        print "\n"
        print a_title
        print "*" * 50
        print a_body
        print "*" * 50

        if raw_input("Is This OK? ") == 'y':
            a_gmail = Gmail()
            a_message = a_gmail.create_message(from_address, to_address,
                                               a_title, file_info, a_body)
            a_gmail.send(from_address, to_address, a_message)
            print u"Sent!"
        else:
            print u"Sending miss."
Beispiel #21
0
def lambda_handler(event={}, context={}):
    """
    Lambda handler.

    Parameters
    ----------
    event : dict
    context : dict

    Returns
    -------
    response : dict
        Return code and response body.
    """
    gmail = Gmail()
    yamato = Yamato()
    publisher = LineBotPublisher()
    newer_than = os.environ['NEWER_THAN']

    # Get message bodies
    messages = gmail.get_messages(
        maxResults=MAX_RESULTS,
        query=yamato.SEARCH_QUERY,
        newerThan=newer_than,
    )
    if not messages:
        return {
            'statusCode': 200,
            'body':
            json.dumps('Not found yamato email in {0}'.format(newer_than)),
        }

    # Extract parcel and date from message body
    for message in messages:
        parcel_info = yamato.get_parcel_and_date(message=message)
        if not parcel_info['parcel'] and not parcel_info['date']:
            print('Cannot obtain from messages!: {0}'.format(message))
            continue

        # Post to line
        publisher.post_text(
            os.environ['LINE_BOT_TO_ID'],
            generate_parcel_message(parcel_info),
        )

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!'),
    }
Beispiel #22
0
def scheduled_job():
    with open('config.json') as file:
        config = json.load(file)

    emailserver = Gmail(config.get('senderAddress'))

    REDO_ATTEMPTS = 0
    MAX_ATTEMPTS = 3
    firefox_options = Options()
    firefox_options.add_argument("--headless")
    driver = webdriver.Firefox(options=firefox_options)
    while (condos := get_condos_data(
            driver,
            URL=config.get('URL'))) == -1 and REDO_ATTEMPTS < MAX_ATTEMPTS:
        condos = get_condos_data(driver, URL=config.get('URL'))
        REDO_ATTEMPTS += 1
def acceptEmailTerms(listing):
    gmail = Gmail()
    gmail.login(gmailUser,gmailPass)
    today = date.today()
    year = today.year
    month = today.month
    day = today.day
    
    print("Receiving email confirmation...")
    time.sleep(60)
    print ("Checking email")
    emails = gmail.inbox().mail(sender="*****@*****.**",unread=True,after=datetime.date(year, month, day-1))
    termsUrl = getCraigslistEmailUrl(listing,emails)
    acceptTermsAndConditions(listing,termsUrl)

    gmail.logout()
    print ("Confirmed")
Beispiel #24
0
def send_confirmation(user_email=None):
    print 'sending email confirmation'
    if user_email is None:
        print 'Email not provided for send_confirmation()'
        Response("Email address not provided", 200)

    token = generate_confirmation_token(user_email)
    url = "http://0.0.0.0:5000/confirm?confirm_token=%s&user_email=%s" % (
        token, user_email)
    gmail = Gmail(gmail_user="******",
                  gmail_password="******")
    gmail.mail_from_name = "Crypto Bot"
    gmail.mail_from = "***********@gmail.com"
    gmail.mail_subject = "Please confirm your account"
    gmail.mail_to = user_email
    gmail.mail_body = "<strong>Thank you for signing up with **************</strong><br>Click the URL below to activate your account <a href='%s'>%s</a>" % (
        url, url)
    gmail.send()
    def monitorEmail(self):
        if not self.isSafetySwitchOff():
            self.sendMonitorErrorEmail(
                "Monitor Email still broken: safety switch turned on")
            return

        g = Gmail()
        g.login(SECRETS_DICT['EMAIL_USERNAME'], SECRETS_DICT['EMAIL_PASSWORD'])
        # play with your gmail...
        messages = g.inbox().mail(unread=True,
                                  sender="*****@*****.**")
        for x in messages:
            x.fetch()
            try:
                self.handleEmail(x)
            except Exception as e:
                x.add_label("Monitor Email Job Error")

        g.logout()
Beispiel #26
0
def main():
    sender, password = get_email_credentials()
    receivers = get_receivers()

    gmail = Gmail(sender, password)

    for locationName, emails in receivers.items():
        location = Location(locationName)

        if location.get_local_time().hour == SEND_EMAIL_HOUR:
            forecast = Forecast(location)

            if forecast.rain_today():
                message = forecast.get_forecast_message()

                for email in emails:
                    send_forecast_message(gmail, email, message)

    print('INFO: Done.')
Beispiel #27
0
def acceptEmailTerms(listing):
    gmail = Gmail()
    gmail.login(gmailUser, gmailPass)

    today = date.today()
    year = today.year
    month = today.month
    day = today.day

    time.sleep(120)
    print "Checking email"
    emails = gmail.inbox().mail(sender="*****@*****.**",
                                unread=True,
                                after=datetime.date(year, month, day - 1))
    termsUrl = getFirstCraigslistEmailUrl(listing, emails)
    acceptTermsAndConditions(listing, termsUrl)

    gmail.logout()
    print "Done Checking Email"
Beispiel #28
0
    def __init__(self, **kwargs):
        super(Gmail_checker, self).__init__(**kwargs)

        # check if parameters have been provided
        username = kwargs.get('username', None)
        password = kwargs.get('password', None)

        if username is None:
            raise MissingParameterException("Username parameter required")

        if password is None:
            raise MissingParameterException("Password parameter required")

        # prepare a returned dict
        returned_dict = dict()

        g = Gmail()
        g.login(username, password)

        # check if login succeed
        logging.debug("Gmail loggin ok: %s" % g.logged_in)  # Should be True, AuthenticationError if login fails

        # get unread mail
        unread = g.inbox().mail(unread=True)

        returned_dict["unread"] = len(unread)

        if len(unread) > 0:
            # add a list of subject
            subject_list = list()
            for email in unread:
                email.fetch()
                encoded_subject = email.subject
                subject = self._parse_subject(encoded_subject)
                subject_list.append(subject)

            returned_dict["subjects"] = subject_list

        logger.debug("gmail neuron returned dict: %s" % str(returned_dict))
        # logout of gmail
        g.logout()
        self.say(returned_dict)
Beispiel #29
0
def in_(destdir, instream):
    input = json.load(instream)

    username = input['source']['username']
    password = input['source']['password']
    version = input.get('version')
    uid = version.get('uid', "") if version is not None else ""

    common.msg("logging into gmail as '{0}'".format(username))
    g = Gmail()

    # login, fail if unable to authenticate
    try:
        g.login(username, password)
    except:
        common.msg("unable to log in")
        exit(1)

    # fetch this particular email
    common.msg("fetching email with uid '{0}'".format(uid))
    msg = g.fetch_multiple_messages({uid: Message(g.inbox(), uid)})[uid]

    # if we haven't found the required email message, then exit
    if msg is None or msg.message is None:
        common.msg("unable to find email with uid '{0}'".format(uid))
        exit(1)

    # put it on a file system
    common.msg("writing email '{0}' to {1}".format(msg.subject, destdir))
    with safe_open(os.path.join(destdir, "email"), 'w') as f:
        f.write(json.dumps(toJSON(msg)))

    # log out and swallow the error
    try:
        g.logout()
    except:
        pass

    metadata = [{'name': 'uid', "value": msg.uid}, {'name': 'subject', "value": msg.subject}]
    return {'version': {'uid': msg.uid}, 'metadata': metadata}
Beispiel #30
0
def mdp_oublie():
    if request.method == 'GET':
        return render_template('forgot-password.html')
    else:
        email = request.form['email']
        if not re.match(r'^[\w\.]+@\w+\.[\w\.]+$', email):
            return render_template('forgot-password.html',
                                   msg="L'adresse "
                                   "courriel n'est pas valide.")
        if len(email) == 0:
            return render_template('forgot-password.html',
                                   msg="Le champ "
                                   "'email' est vide!")
        if get_database().get_user_by_email(email) is not None:
            jeton = uuid.uuid4().hex
            get_database().save_token(email, jeton)
            url = "http://localhost:5000/nouveau-mdp/%s" % jeton
            entete = "Nouveau mot de passe"
            msg = """Bonjour,\n
Veuillez appuyer sur le lien suivant afin de créer un nouveau mot de passe.\n
%s """ % url
            mail = Gmail()
            mail.envoyer_mail(email, entete, msg)
        return redirect('/admin')