当前位置: 首页>>代码示例>>Python>>正文


Python gmail.Gmail类代码示例

本文整理汇总了Python中gmail.Gmail的典型用法代码示例。如果您正苦于以下问题:Python Gmail类的具体用法?Python Gmail怎么用?Python Gmail使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Gmail类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

 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
开发者ID:Mondego,项目名称:pyreco,代码行数:25,代码来源:allPythonContent.py

示例2: Mail

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: ').strip()
        password = getpass.getpass('Password: ').strip()
            
        #login
        try:
            self.g.login(username, password)
        except:
            print '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)
开发者ID:mattpie,项目名称:gduino,代码行数:33,代码来源:mail.py

示例3: get

    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})
开发者ID:psbanka,项目名称:yamzam,代码行数:33,代码来源:ImportEmail.py

示例4: send_email

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
开发者ID:npinto,项目名称:craigslistParser,代码行数:26,代码来源:updater.py

示例5: main

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)
开发者ID:LeJit,项目名称:EveryoneHacksCHI,代码行数:26,代码来源:Tokenize.py

示例6: run

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
开发者ID:schwallie2,项目名称:gmail_stats,代码行数:10,代码来源:inbox_stats.py

示例7: __init__

    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')
开发者ID:ThomasCabrol,项目名称:strata_bootcamp,代码行数:12,代码来源:email_classify.py

示例8: __init__

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:
开发者ID:matteocam,项目名称:you-are-the-emails-you-write,代码行数:13,代码来源:download.py

示例9: __init__

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="[email protected]", 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()
开发者ID:Pseudonymous-coders,项目名称:Python_Libs,代码行数:51,代码来源:gmail_check.py

示例10: test_remove_bcc_from_header

    def test_remove_bcc_from_header(self):
        """
        Test if Bcc is removed from message header before send it
        """
        my_sender = 'Me <[email protected]>'
        to = 'Leo Iannacone <[email protected]>'
        Cc = 'Leo2 Iannacone <[email protected]>, Leo3 Iannacone <[email protected]>'
        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())
开发者ID:LeoIannacone,项目名称:goopg,代码行数:27,代码来源:gmail.tests.py

示例11: __init__

 def __init__(self):
     # user info
     self.username = None
     self.password = None
     
     # object using the gmail library
     self.g = Gmail()
开发者ID:mattpie,项目名称:gduino,代码行数:7,代码来源:mail.py

示例12: yesItShould

    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()
开发者ID:daniman,项目名称:dibs,代码行数:60,代码来源:reuse_parser.py

示例13: _get_an_email

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
开发者ID:psbanka,项目名称:yamzam,代码行数:17,代码来源:parse_cc.py

示例14: init

 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}
开发者ID:jubayerarefin,项目名称:goopg,代码行数:8,代码来源:commandhandler.py

示例15: UtIntfGmail

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
开发者ID:jamesgmorgan,项目名称:temp-v3ndr01d-common,代码行数:19,代码来源:utIntfGmail.py


注:本文中的gmail.Gmail类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。