Beispiel #1
0
class Mail():
    def __init__(self):
        # user info
        self.username = None
        self.password = None
        
        # object using the gmail library
        self.g = Gmail()
    
    
    def login(self):
        # get user info    
        username = raw_input('Username: '******'Password: '******'Unable to login'
  
  
    def logout(self):
        # logout
        self.g.logout()
                  
       
    def getNumUnread(self):
        # get number of unread email  
        try:
            return len(self.g.inbox().mail(unread=True))
        except Exception as err:
            print str(err)
Beispiel #2
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 #3
0
    def get(self, request, limit=10):
        """
        Log in to gmail using credentials from our config file and retrieve
        email to store into our db
        """
        profile = request.user.get_profile()
        username = profile.gmail_username
        password = profile.gmail_password
        source = profile.gmail_source

        g = Gmail()
        g.login(username, password)
        msgs = g.inbox().mail(sender=source)

        imported = 0
        for msg in msgs[:int(limit)]:
            try:
                email_summary = EmailSummary.objects.get(
                    message_id=msg.message_id)
                continue
            except EmailSummary.DoesNotExist:
                pass
            msg.fetch()
            email_summary = EmailSummary.objects.create(
                user=request.user,
                message_id=msg.message_id,
                subject=msg.subject, date=msg.sent_at, source_addr=source,
                imported_to_wordpress=False
            )
            email_summary.save()
            imported += 1

        return Response({"response": "imported %s messages" % imported})
Beispiel #4
0
class Steem_node():
    def __init__(self):
        self.stm = Steem()
        self.blockchain = Blockchain(steem_instance=self.stm, mode="head")
        self.mailserver = Gmail(60)

    def run(self):
        # Fetch full blocks, then inspect each operation.
        for block in self.blockchain.blocks():
            block_num = block.block_num
            created_at = block.time()
            print(f'Block: {block_num}')

            for op in block.operations:
                # Extract op data
                if op['type'] == 'transfer_operation':
                    type = 'transfer'
                    subject = 'New transfer'
                    to = op['value']['to']
                    FROM = op['value']['from']
                    amount = op['value']['amount']
                    memo = op['value']['memo']

                    # Check if account matches, sent mail on True
                    if to == 'steempytutorials':
                        print('Incoming transfer')
                        message = (
                            f'{created_at}\nBlock: {block_num}\nFrom: {FROM}' +
                            f'\nTo: {to}\nAmount: {amount}\nMemo: {memo}\n')
                        try:
                            self.mailserver.send_email(subject, message, type)
                            print('Mail sent')
                        except Exception as e:
                            print('Failed to sent mail', e)
Beispiel #5
0
    def __init__(self):
        # user info
        self.username = None
        self.password = None

        # object using the gmail library
        self.g = Gmail()
Beispiel #6
0
class Mail():
    def __init__(self):
        # user info
        self.username = None
        self.password = None

        # object using the gmail library
        self.g = Gmail()

    def login(self):
        # get user info
        username = raw_input('Username: '******'Password: '******'Unable to login'

    def logout(self):
        # logout
        self.g.logout()

    def getNumUnread(self):
        # get number of unread email
        try:
            return len(self.g.inbox().mail(unread=True))
        except Exception as err:
            print str(err)
Beispiel #7
0
def main(useDefault):
	text = "There is a flood on 1444 N Bosworth Avenue. My name is Deckard Cain."
	time = None
	email = Gmail()
	messages = email.readEmails(True)
	if not useDefault:
		text,time = messages[-1].split("|")
	entities = findEntities(text)
	if not time == None:
		entities[time] = "Time"
	s = parsetree(text)

	for sentence in s:
		chunks = sentence.chunks
		for chunk in chunks:
			tag, myString = chunk.tag, chunk.string
			if tag == "NP":
				no_adjective_string = removeAdjective(chunk)
				no_adjective_string = formatString(no_adjective_string)
				if len(no_adjective_string) > 0:
					if not entities.has_key(no_adjective_string):
						entities[no_adjective_string] = determineType(no_adjective_string,sentence) 

	for i,textfile in enumerate(textfile_names):
		value = textfile_mappings[i]
		writeOutput(textfile,entities,value)
Beispiel #8
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 #9
0
def send_email( sender, recipients, msg ):
    """Send the email. Don't forget to add the relevant information into conf.py
    """

    from gmail import Gmail
    gm = Gmail(conf.SMTP_USER, conf.SMTP_PASS)
    print recipients
    gm.mail(recipients[0], 'alert palo alto', msg[:100])
    gm.mail(recipients[1], 'alert palo alto', msg)
    return

    session = smtplib.SMTP(conf.SMTP_SERVER)
    session.starttls()
    session.login(conf.SMTP_USER, conf.SMTP_PASS)
    smtpresult = session.sendmail(sender, recipients, msg)

    if smtpresult:
        errstr = ""
        for recip in smtpresult.keys():
            errstr = """Could not delivery mail to: %s

  Server said: %s
  %s

  %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
        raise smtplib.SMTPException, errstr
Beispiel #10
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 #11
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 #12
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 #13
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 #14
0
    def receive(self, from_address=None):
        """
        receive gmail
        """
        gmail = Gmail(self.gsetting)
        date, message = gmail.receive(from_address)

        return date, message
Beispiel #15
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 #16
0
def run():
    g = Gmail()
    # Store your Username/Pwd in secret.py, and don't include secret.py in your github
    success = login_to_gmail(g)
    if not success:
        return  # TODO: Add error handling
    # Return list of gmail message objects
    to_me = g.inbox().mail()
    received = parse_emails(to_me, store={})
    return received
Beispiel #17
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 #18
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 #19
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 #20
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 #21
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')
    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 #23
0
class YoutubeCheck:
    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)

    @staticmethod
    def delete_email(emaillist):
        for email in emaillist:
            email.delete()

    def set_args(self, **kwargs):
        print "Attempting to start gmail (args)...",
        self.arguments = kwargs
        print "Done"

    def get_emails(self):
        return self.gmail.inbox().mail(self.arguments)

    def check_videos(self):
        self.login()
        sleep(1)
        print "Trying to check if new emails have been sent...",
        self.emails = []
        emailss = (self.get_emails())
        if len(emailss) == 0:
            return [0]
        print "Done"
        for email in emailss:
            subject = email.subject
            if '"' in subject:
                if '"' in subject[subject.index("\"") + 1:]:
                    print "Found copyrighted video...",
                    videoname = str(subject[subject.index("\"") +
                                            1:][:subject.index("\"")]).replace(
                                                "\"", "")
                    self.emails.append(videoname)
                    print "Done"
        self.delete_email(emailss)
        return self.emails

    def login(self):
        self.gmail.login(self.user, self.password)

    def logout(self):
        self.gmail.logout()
Beispiel #24
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 #25
0
class MailAnalytics:
  def __init__(self, loginFile = 'credentials.txt'):
    self.g = Gmail()
    self.loginFromCredentialsFile(loginFile)

  def loginFromCredentialsFile(self, loginFile = None):
    # XXX: currently file is not used
    try:
        # NOTE: your username andpassword here
        userName = None
        pwd = None 
      self.g.login(userName, pwd )
    except:
class YoutubeCheck:
    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)

    @staticmethod
    def delete_email(emaillist):
        for email in emaillist:
            email.delete()

    def set_args(self, **kwargs):
        print "Attempting to start gmail (args)...",
        self.arguments = kwargs
        print "Done"

    def get_emails(self):
        return self.gmail.inbox().mail(self.arguments)

    def check_videos(self):
        self.login()
        sleep(1)
        print "Trying to check if new emails have been sent...",
        self.emails = []
        emailss = (self.get_emails())
        if len(emailss) == 0:
            return [0]
        print "Done"
        for email in emailss:
            subject = email.subject
            if '"' in subject:
                if '"' in subject[subject.index("\"")+1:]:
                    print "Found copyrighted video...",
                    videoname = str(subject[subject.index("\"")+1:][:subject.index("\"")]).replace("\"", "")
                    self.emails.append(videoname)
                    print "Done"
        self.delete_email(emailss)
        return self.emails

    def login(self):
        self.gmail.login(self.user, self.password)

    def logout(self):
        self.gmail.logout()
Beispiel #27
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 #28
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 #29
0
    def yesItShould(self):
        #runs the whole shebang
        self.appendToLog(" ")
        self.appendToLog("running the whole shebang")
         
        # #the gmail object, maybe
        # g = Gmail()
        self.g = Gmail()
        self.g.login("radixdeveloper", "whereisstrauss")

        # #the location object
        # loc = Locator()

        emails = self.g.label("reuse").mail(unread=True)
        
        #batcher lists for parse
        parseObjectBatchList = []
        # claimedEmailsBatchList = []
        
        for email in emails:
            if self.isDebugMode: 
                print "="*8
                print " "
                
            email.fetch()

            #don't read if testing
            if not self.isDebugMode: email.read()

            #if it is a reply email, ignore it
            if isReplyEmail(email):
                if self.isDebugMode: print "skipping: "+email.subject #+ " "+email.body
                
                # if (util.isClaimedEmail(email)):
                    # claimedEmailsBatchList.append(email)
                continue

            #print the first snippet of the email
            print(email.subject[0:self.logSnippetLength])   
            # print(email.body)   
            self.appendToLog(email.subject[0:self.logSnippetLength])      

            #make the guess
            locationGuess = self.loc.makeGuessByEmail(email)
            self.appendToLog("guess location = %s" % locationGuess.__str__())     
            if self.isDebugMode: print("guess location = %s" % locationGuess.__str__()) 
            
            #create the item and save for later batch saving
            theReuseItem = self.createReuseItem(email,locationGuess)
            parseObjectBatchList.append(theReuseItem)
        
        #batch save the objects we created above 
        self.batchSaveList(parseObjectBatchList)
          
        # #deal with the reply emails AFTER saving the existing ones above
        # self.handleReplyEmail(claimedEmailsBatchList)

        print 'done'
        self.appendToLog("done with run, logging out of gmail.")
        self.g.logout()
Beispiel #30
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 #31
0
 def __init__(self):
     # user info
     self.username = None
     self.password = None
     
     # object using the gmail library
     self.g = Gmail()
Beispiel #32
0
    def test_remove_bcc_from_header(self):
        """
        Test if Bcc is removed from message header before send it
        """
        my_sender = 'Me <*****@*****.**>'
        to = 'Leo Iannacone <*****@*****.**>'
        Cc = 'Leo2 Iannacone <*****@*****.**>, Leo3 Iannacone <*****@*****.**>'
        Bcc = ['Leo{0} Nnc <leo{0}@tests.com>'.format(i) for i in range(4, 30)]
        Bcc = ', '.join(Bcc)
        payload = 'This is the payload of test_remove_bcc_from_header'
        m = MIMEText(payload)
        m['To'] = to
        m['Cc'] = Cc
        m['Bcc'] = Bcc
        m['From'] = my_sender

        new_message = Gmail._remove_bcc_from_header(m)

        # message must be a correct email (parsable)
        new_message = email.message_from_string(new_message)
        self.assertIsInstance(new_message, Message)

        # must not have 'Bcc'
        self.assertFalse('Bcc' in new_message)

        # and must have the same payload
        self.assertEqual(payload, new_message.get_payload())
Beispiel #33
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 #34
0
def _get_an_email(gmail_configs, index):
    """
    Log in to gmail using credentials from our config file and retrieve
    an email from our sender with a given index-number.
    """
    g = Gmail()
    g.login(gmail_configs['username'], gmail_configs['password'])
    msg = g.inbox().mail(sender=gmail_configs['source_address'])[index]
    msg.fetch()
    raw_message = msg.message
    html_body = ''
    if raw_message.get_content_maintype() == "multipart":
        for content in raw_message.walk():
            print content.get_content_type()
            if content.get_content_type() == "text/html":
                html_body = content.get_payload(decode=True)
    return html_body
Beispiel #35
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 #36
0
class GmailHandler(object):
    def __init__(self):
        """Initialise Gmail object"""
        self.obj = Gmail()
        self.obj.login(GMAIL_CONFIG['username'], GMAIL_CONFIG['password'])
        self.unread = self.obj.inbox().mail(unread=True)

    def get_unread(self, recent=False):
        if recent:
            self.unread = self.obj.inbox().mail(unread=True, on=date.today())
        else:
            self.unread = self.obj.inbox().mail(unread=True)
        return self._format_msg_count(len(self.unread))

    def search_unread(self, term):
        """Search sender or subject for a given term.

        Args:
            term (str): term to search.

        Returns:
            subject (str): subject of email with term/from sender

        """
        self.unread = self.obj.inbox().mail(unread=True)
        term = term.lower()
        result = []
        for mail in self.unread:
            mail.fetch()
            subject = mail.subject
            sender = mail.fr
            if term in subject.lower() or term in sender:
                result.append(mail.subject)

        return self._format_search_results(result)

    """Formatting methods."""

    def _format_msg_count(self, msg_count):
        if msg_count:
            msg = 'You have {msg_count} new emails.'
            msg = msg.format(msg_count=msg_count)
        else:
            msg = 'You have no new emails.'
        return msg

    def _format_search_results(self, results):
        msg = self._format_msg_count(len(results))
        results.insert(0, msg)
        msg = '\n'.join(results)
        return msg

    def __del__(self):
        """Destructor"""
        self.obj.logout()
class UtIntfGmail(object):
    def __init__(self, dictCreds):
        self.init(dictCreds)
        pass
    
    def init(self, dictCreds):
        self.__api_Gmail = Gmail()
        self.__api_Gmail.login(dictCreds['username'], dictCreds['password'])
        pass
    
    def getEmails(self, user):
        bRet = True
        bodyList = []
        mailList = self.__api_Gmail.inbox().mail(unread=True, sender=user)
        for m in mailList:
            m.fetch()
            bodyList.append(m.body)
        
        return bRet, bodyList
Beispiel #38
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'])
class ProxyZipDownloader:

    def __init__(self, username, password, abs_path_zips):
        self.username = username
        self.password = password
        self.abs_path_zips = abs_path_zips
        self.g = Gmail()
        self.g.login(username, password)
    
    def __remove_all_zips__(self):
        for file_name in os.listdir(self.abs_path_zips):
            if file_name.endswith(".zip"):
                file_to_remove = self.abs_path_zips + file_name
                print "Removing %s" % file_to_remove
                os.remove(file_to_remove)


    def __is_zip_file_old__(self, file_name):
        # proxylist-10-26-13.zip
        date_zip_file = datetime.datetime.strptime(file_name, \
                                                           'proxylist-%m-%d-%y.zip')
        date_today = datetime.datetime.now()
        return (date_today - date_zip_file).days >= 2

    def fetch_files(self):
        self.__remove_all_zips__()
        for email in self.g.inbox().mail(sender="*****@*****.**", after=datetime.datetime.now() - datetime.timedelta(days=3)):
            message = email.fetch()

            m1 = message.get_payload()[0]
            m2 = message.get_payload()[1]

            zip_file_name = m2.get_filename()
            if self.__is_zip_file_old__(zip_file_name):
                continue

            zip_file_contents = m2.get_payload(decode=True)
                    
            print "Saving %s" % zip_file_name
            f = open(self.abs_path_zips + zip_file_name, 'w')
            f.write(zip_file_contents)
            f.close()
    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 #41
0
    def setup(self, config_file):
        self.running_switch = True
        self.config_file = config_file
        config = configparser.ConfigParser()
        config.read(config_file)
        gmail_user = config['mail']['gmail_user']
        gmail_password = config['mail']['gmail_password']

        self.hours_between_every_mail = int(
            config['mail']['hours_between_every_mail'])
        self.minutes_between_every_mail = int(
            config['mail']['minutes_between_every_mail'])
        self.last_mail = datetime.now() - timedelta(
            hours=self.hours_between_every_mail,
            minutes=self.minutes_between_every_mail)
        self.DATABASE = config['flask']['sqlite_db_name']
        Gmail.__init__(self, gmail_user, gmail_password)
        self.start_stop = True
        Thread.__init__(self)
        if int(self.enabled):
            self.start()
def send_email(blog_id, post_id):
    post = (blogger_service().posts().get(
        blogId=blog_id,
        postId=post_id
    ).execute())
    form = forms.Form()
    recipients = Recipient.query.filter_by(blog_id=blog_id).all()
    addresses = [r.email for r in recipients]

    if form.validate_on_submit():
        html = flask.render_template(
            'email.html',
            title=post['title'],
            content=flask.Markup(post['content']))
        text = 'A new blog post is available at ' + post['url']
        gmail = Gmail(gmail_service())
        gmail.send(addresses, post['title'], text, html)
        flask.flash(u"Email sent - {title}".format(**post), "success")
        return flask.redirect(flask.url_for('.blog', blog_id=blog_id))

    return flask.render_template('send_email.html', post=post, form=form, addresses=addresses)
Beispiel #43
0
	def __init__(self, name_customer, name_lawyer, email,contract,template_success,template_warning):
		self.numbers = {'een':1,'Een':1,'één':1,'Eén':1,'twee':2,'Twee':2,'Drie':3,'drie':3,None:0,1:1}
		self.gm = Gmail('*****@*****.**', 'hackathonmasters')
		self.name_customer = name_customer
		self.name_lawyer = name_lawyer
		self.email = email
		self.contract = contract
		self.subject = 'Betreffende uw contract'
		with open(template_success) as f:
			self.template_success = f.read()
		with open(template_warning) as f:
			self.template_warning = f.read()
class Server:

    def __init__(self, credentials, address='0.0.0.0', port=0, forward=False):
        self.forward = forward
        self.gmail = Gmail()
        self.ftp_server = FTPServer(credentials, (address, port), FTPSession)
        self.address, self.port = self.ftp_server.socket.getsockname()

    @property
    def images(self):
        return self.ftp_server.images

    def forward_received_images_on_smtp(self):
        while self.forward:
            sleep(60)

            batch = []
            while not self.images.empty():
                batch.append(self.images.get())
            
            if batch:
                message = Message(Configuration.email_subject, batch)
                self.gmail.connect()
                self.gmail.send(message)
                self.gmail.disconnect()

    def listen(self):
        Thread(target=self.ftp_server.serve_forever).start()
        Thread(target=self.forward_received_images_on_smtp).start()

    def quit(self):
        self.forward = False
        self.ftp_server.shutdown()
def main():
    path = "C:\\Users\\L.SeonHo\\Desktop\\result\\"
    gmaps = list()  # for location
    gmap_path = str()   # for full path
    g = Gmail()
    g.login('bob5leesh', 'rlayuna#0905')
    if not os.path.isdir(path):
        os.mkdir(path)
    set_sqlite(path)

    for i in range(16, 30):
        mailday = date(2016, 7, i)
        daypath =  "C:\\Users\\L.SeonHo\\Desktop\\result\\" + str(mailday) +"\\"    # for create day folder
        daygmap = list()    # create day gmap
        if not os.path.isdir(daypath):
            os.mkdir(daypath)   # create folder
        emails = g.inbox().mail(on = mailday, sender = '*****@*****.**')

        for email in emails:
            flock = fl0ckfl0ck(email) # one mail routine
            flock.path = daypath
            flock.GetGmail()
            gmap_path = flock.path
            if flock.ShortToFull() != 0: # in : success get full url / out : fail get full url
                flock.GetImage()
                flock.GetHash()
                flock.GetGPS()
                # check exist gps info from file
                if str(flock.gps_lat) == 'None' or str(flock.gps_lon) == 'None':
                    pass
                elif str(flock.gps_lat) == 'N/A' or str(flock.gps_lon) == 'N/A':
                    pass
                else:
                    gmaps.append(flock.MakeGmap())       # setting day gmap
                    daygmap.append(flock.MakeGmap())     # setting full gmap
            flock.OutCSV()  # create CSV file
            flock.OutSQLite(path)   # create SQLite database
        if len(daygmap) != 0:
            get_googlemap(daygmap, gmap_path)   # get day gmap
        get_googlemap(gmaps, path)  # get full gmap
Beispiel #46
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 #47
0
def fetch_codes():
    client = Gmail()
    client.login(sys.argv[1], email_password)
    mails = client.inbox().mail(unread=True, sender="*****@*****.**")

    for entry in mails:
        entry.fetch()

        if 'need to complete the process:' not in entry.body:
            continue

        entry.read()
        
        # First, find the username this went too
        username = re.findall("Dear (.*),", entry.body)[0]

        # Label this as a proper steam-guard code
        entry.add_label("Codes")

        # Grab the actual steam-guard code
        _, data = entry.body.split("need to complete the process:")
        code = data.strip().split("\n", 1)[0].strip()

        store_code(entry.to, username, code)

    client.logout()
Beispiel #48
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()
Beispiel #49
0
 def test_do_not_duplicate_senders(self):
     """
     Test if email is sent twice to the same receiver
     """
     my_sender = 'Me <*****@*****.**>'
     to = '"Leo2, Ianna" <*****@*****.**>, "Leo, Iannacone" <*****@*****.**>'
     payload = 'This is the payload of test_remove_bcc_from_header'
     m = MIMEText(payload)
     m['To'] = to
     m['From'] = my_sender
     addr = Gmail._get_receivers(m)
     self.assertEqual(1, len(addr))
     self.assertIn("*****@*****.**", addr)
Beispiel #50
0
 def test_allow_comma_in_receiver_issue_14(self):
     """
     Test if email is sent to the correct contact, containing comma in name
     """
     my_sender = 'Me <*****@*****.**>'
     to = '"Leo2, Ianna" <*****@*****.**>, "Leo, Iannacone" <*****@*****.**>'
     payload = 'This is the payload of test_remove_bcc_from_header'
     m = MIMEText(payload)
     m['To'] = to
     m['From'] = my_sender
     addr = Gmail._get_receivers(m)
     self.assertIn("*****@*****.**", addr)
     self.assertIn("*****@*****.**", addr)
Beispiel #51
0
class EmailHandler():

    def __init__(self, username, password ):
        self.g = Gmail()
        self.g.login(username, password)

    def logout(self):
        self.g.logout()

    def get_sent_mail(self):
        return self.g.sent_mail()


    def store_emails(self, start_date , store_at):
        '''
            Download the emails and store them in a plain text file separated by "===" string

        '''
        all_emails = []
        for message in self.get_sent_mail().mail(after=start_date):
            message.fetch()
            for line in message.body.split('\r\n'):
                #do some cleaning before storing the emails
                if "-------- Original Message --------" in line:
                    break
                if "---------- Forwarded message ----------" in line:
                    break
                line = re.sub("\d+", "", line)
                line = re.sub('<[^>]*>', '', line)
                if line and line[0] != '>' and line[0] != '<' : #ignore quoting previous email or http links
                    all_emails.append(line)
            all_emails.append("="*30)
        #save the emails
        f = open(store_at,"wr+")
        f.write('\n'.join(all_emails))
        f.close()
        print "Done getting and storing emails"
    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()
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 #54
0
    def test_sends_to_everyone(self):
        """
        Tests if message is going to be sent to:
          To:
          CC:
          Bcc:
        """
        my_sender = 'Me <*****@*****.**>'
        to = 'Leo Iannacone <*****@*****.**>'
        Cc = 'Leo2 Iannacone <*****@*****.**>, Leo3 Iannacone <*****@*****.**>'
        Bcc = 'Leo4 Iannacone <*****@*****.**>, Leo5 Iannacone <*****@*****.**>'
        m = Message()
        m['To'] = to
        m['Cc'] = Cc
        m['Bcc'] = Bcc
        m['From'] = my_sender

        my_receivers = ', '.join([to, Cc, Bcc]).split(',')
        my_addresses = email.utils.getaddresses(my_receivers)

        addresses = Gmail._get_receivers(m)
        for name, addr in my_addresses:
            self.assertIn(addr, addresses)
import getpass
from gmail import Gmail

# Leemos los datos mediante la consola de entrada
my_gmail = input("Escribe tu Gmail: ")
my_gmail_password = getpass.getpass("Password: "******"Introduce una lista con los emails de los destinatarios: ")
asunto = input("Asunto del email: ")
msg = input("Mensaje a enviar: ")

my_gmail = Gmail( my_gmail, my_gmail_password )
for dest_email in list_dest_email.split(',') :
    dest_email_cleaned = dest_email.strip()
    try :
        my_gmail.send_message( dest_email_cleaned, msg, asunto )
        print("Email enviado a %s" % dest_email_cleaned )
    except Exception as err :
        print("Error enviado el email a %s. " % dest_email_cleaned + str( err ) )
my_gmail.quit()

Beispiel #56
0
if sys.argv[1]=='send':
    number = sys.argv[2]

    message=''
    for word in sys.argv[3:]:
        message+=" "
        message+=word
    message=message.strip()

    client = SinchSMS("app_public_key","app_secret_key")
    print("Sending '%s' to %s" % (message, number))
    client.send_message(number, message)
#------------------------------------------------------
if sys.argv[1]=='recive':
    g = Gmail()
    g.login('gmail_login', 'gmail_pass')

# mark the letters without html markup as Normal
    messages = g.inbox().mail()
    for message in messages:
        message.fetch()
        message_body=message.body.split()
        message_body=("".join(message_body)).strip()
        if this_html(message_body)==False:
            message.add_label("Normal")

# all letters marked as Normal
    if sys.argv[2]=='all':
        all_messages=g.label("Normal").mail()
        for mes in all_messages:
 def __init__(self, username, password, abs_path_zips):
     self.username = username
     self.password = password
     self.abs_path_zips = abs_path_zips
     self.g = Gmail()
     self.g.login(username, password)