本文整理汇总了Python中gmail.Gmail.logout方法的典型用法代码示例。如果您正苦于以下问题:Python Gmail.logout方法的具体用法?Python Gmail.logout怎么用?Python Gmail.logout使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gmail.Gmail
的用法示例。
在下文中一共展示了Gmail.logout方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_codes
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
def fetch_codes():
client = Gmail()
client.login(sys.argv[1], email_password)
mails = client.inbox().mail(unread=True, sender="[email protected]")
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()
示例2: Mail
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
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)
示例3: __init__
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
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()
示例4: monitorEmail
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
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="[email protected]")
for x in messages:
x.fetch()
try:
self.handleEmail(x)
except Exception as e:
x.add_label("Monitor Email Job Error")
g.logout()
示例5: acceptEmailTerms
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
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="[email protected]",unread=True,after=datetime.date(year, month, day-1))
termsUrl = getFirstCraigslistEmailUrl(listing,emails)
acceptTermsAndConditions(listing,termsUrl)
gmail.logout()
print "Done Checking Email"
示例6: EmailHandler
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
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"
示例7: this_html
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
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:
mes.fetch()
mes.read() # mark letter as read
print mes.fr #from whom
print mes.body # main text (body) of e-mail
print "--------------------------------"
# new (unread) letters marked as Normal
if sys.argv[2]=='new':
new_messages=g.label("Normal").mail(unread=True)
for new_mes in new_messages:
new_mes.fetch()
new_mes.read()
print new_mes.fr
print new_mes.body
print "--------------------------------"
g.logout()
示例8: doScrape
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
def doScrape(Con, q):
try:
g = Gmail()
################ LOGIN #####################################
q.put(('Logging In', 5),)
logger.info("Logging In")
try:
g.login(Con.Username, Con.Password)
except AuthenticationError:
logger.exception(sys.exc_info())
q.put(('Login Failed', 100),)
return "AUTH_ERROR"
############################################################
################ GET LABEL MAILBOX #########################
mailbox = None
q.put(('Getting Mailbox', 10),)
logger.info("Getting Mailbox")
try:
if Con.Label.lower() == 'inbox':
mailbox = g.inbox()
else:
mailbox = g.mailbox(Con.Label)
except:
logger.exception(sys.exc_info())
q.put(('Problem in fetching Gmail Label', 100),)
return "LABEL_FETCH_ERROR"
if not mailbox:
q.put(('Gmail Label Not Found', 100),)
return "LABEL_NOT_FOUND"
############################################################
################ GET EMAILS ################################
mails = None
q.put(('Searching For Emails', 15),)
logger.info("Searching Emails")
try:
afterDate = Con.FromDate - timedelta(days=1)
beforeDate = Con.ToDate + timedelta(days=1)
mails = mailbox.mail(subject='Fiverr: Congrats! You have a new order',
after=afterDate, before=beforeDate)
mails.extend(mailbox.mail(subject='just ordered an Extra',
after=afterDate, before=beforeDate))
# mails = mailbox.mail(after=Con.FromDate, before=Con.ToDate)
except:
logger.exception(sys.exc_info())
q.put(('Problem in searching for emails', 100),)
return "EMAILS_FETCH_ERROR"
if len(mails) == 0:
q.put(('No Emails Found with search criteria', 100),)
return "NO_EMAIL_FOUND"
############################################################
################ FETCH EMAILS ##############################
q.put(('Fetching Emails', 20),)
logger.info("Scraping Order Data From Emails")
Con.Orders = []
logger.info("Num of Emails found: " + str(len(mails)))
try:
for mail in mails:
msg = "Fetching Email " + str(mails.index(mail)+1) + ' of ' + str(len(mails))
per = 20 + int((float(mails.index(mail)+1) * 100.0 * 0.6 / float(len(mails))))
q.put((msg, per),)
#logger.info(msg)
mail.fetch()
gmailEvents.extract_orders_from_email(mail, Con)
except:
logger.exception(sys.exc_info())
q.put(('Problem in fetching emails', 100),)
return "EMAIL_FETCH_ERROR"
############################################################
# return 'SUCCESS'
################ CALCULATE TOTAL AMOUNT ####################
q.put(('Calculating Total and Revenue', 85),)
logger.info("Calculating Total Amount")
gmailEvents.calculate_total_amount(Con)
############################################################
################ GENERATE XLS ##############################
q.put(('Generating XLS', 90),)
logger.info("Generating XLS")
gmailEvents.generate_xls(Con)
############################################################
q.put(('Logging Out of Gmail', 95),)
g.logout()
q.put(('SUCCESS', 100),)
return 'SUCCESS'
except:
if g:
g.logout()
logger.exception(sys.exc_info())
q.put(('Error Occurred', 100),)
return "ERROR"
示例9: findPayments
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
def findPayments(username, password):
# Main Part, use Gmail to find venmo balances
file = open('recent.txt', 'r')
most_recent = file.read()
file.close()
IDs = [0,most_recent]
charges = {}
#can use this if we only want to check most recent emails
#then = datetime.datetime.now().replace(hour=8, minute=0, second=0, microsecond=0)
'''
Make benefits_on true to provide benefits to DKEggertor founders
'''
benefits_on = False
g = Gmail()
g.login(username, password)
newMail = g.inbox().mail(fr="[email protected]")
print "got mail"
#Filter venmo emails that are payments emails from venmo
payments = filterPayments(newMail)
print "filtered"
#Can use this part to implement only most recent email checking, Note: use email.sent_at to get the emails timestamp.
#for i in pay:
#if i.sent_at >= then:
#payments.append(i)
#Iterate through payment emails to find balances
i = 0
while i < len(payments):
#Check if the ID number of the email has already been checked
#as this prevents checking emails twice and incorrectly calculating balances
if payments[i].uid not in IDs:
print "Test 1"
#Check if email is a payment to DKE Keg
if isKegEmail(payments[i]) and int(payments[i].uid) >= int(most_recent)+1:
print "Test 2"
#Seperate out the subject of the email to find Name and Amount that was paid
IDs.append(payments[i].uid)
payments[i].fetch()
print "Fetched"
message = payments[i].subject
print "subject"
name = message.split(" p")[0]
if len(message.split("$")[1]) >= 10:
amount = float(message.split("$")[1].split(" ")[0])
else:
amount = float(message.split("$")[1])
#Update amount if name is already in the database
if name in charges:
amount = charges[name] + amount
#This check is only for when I (Mike DeLaus) pay from the my venmo account as it is the same email we use for DKE Keg
if name != "You":
charges[name] = amount
#Provides benefits for the founding members of DKEggerator
founders = ["Michael DeLaus", "Ryan Kelly", "Mitch Maisel"]
for name in founders:
if benefits_on == True:
charges[name] = 999999999999
file = open('recent.txt', 'w')
most_recent = payments[i].uid
file.write(str(most_recent))
file.close()
i+=1
return charges
#Sleep the program so we don't constantly check, can probably find better way to do this
#time.sleep(60)
#Logout of email so next check uses a refreshed inbox
g.logout()
示例10: ReuseParser
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import logout [as 别名]
#.........这里部分代码省略.........
self.appendToLog("could not find location _%s_ in lookup dict" % guess.generalLocation)
theReuseItem.guess_found=False
return theReuseItem
def batchSaveList(self, listOfParseObjects):
if len(listOfParseObjects)==0:
return;
print 'batch saving objects'
self.appendToLog('batch saving %d objects' % len(listOfParseObjects))
#batch save a list of parseobjects. the batch limit is 50!
batcher = ParseBatcher()
batchLimit = 50
while len(listOfParseObjects)> 0:
#save the first @batchLimit amount of objects
batcher.batch_save(listOfParseObjects[0:batchLimit])
#clear the list of those saved objects
listOfParseObjects = listOfParseObjects[batchLimit:]
def handleReplyEmail(self, replyList):
batchItemList = []
for email in replyList:
#find the old post and set the claimed field!
existingItems= ReuseItem.Query.all().filter(email_id = email.thread_id).limit(1) #get only 1 post
for item in existingItems:
#update the claimed field
item.claimed = True
batchItemList.append(item)
logPost = "set post _%s_ to claimed based on post _%s_" % (item.email_subject[0:32], email.body[0:32])
self.appendToLog( logPost )
if self.isDebugMode: print logPost
#batch save those objects now!
self.batchSaveList(batchItemList)
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()