本文整理汇总了Python中gmail.Gmail.inbox方法的典型用法代码示例。如果您正苦于以下问题:Python Gmail.inbox方法的具体用法?Python Gmail.inbox怎么用?Python Gmail.inbox使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gmail.Gmail
的用法示例。
在下文中一共展示了Gmail.inbox方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_codes
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [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 inbox [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: get
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
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})
示例4: run
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
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
示例5: __init__
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [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()
示例6: monitorEmail
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [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()
示例7: _get_an_email
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
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
示例8: acceptEmailTerms
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [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"
示例9: UtIntfGmail
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
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
示例10: __init__
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
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="[email protected]", 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()
示例11: main
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
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 = '[email protected]')
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
示例12: Gmail
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
from account import Account
from gmail import Gmail
gmail = Gmail()
while True:
choice = input('1. Sign up\n2. Login\n')
if choice == '1':
new_account = Account()
elif choice == '2':
user_account = Account.login()
if user_account != None:
while True:
choice2 = input('1. Inbox\n2.Send Email\n')
if choice2 == '1':
inbx = gmail.inbox(user_account)
print(inbx)
choice3 = input('Enter the index of message to view (max {}) / -1 to go back: '.format(len(inbx)-1))
if int(choice3) == -1:
pass
else:
print(gmail.view_message(int(choice3),inbx))
elif choice2 == '2':
#to_email, msg, subject, user
t = input('To: ')
s = input('Subject: ')
m = input('Message: ')
gmail.send_email(t, m, s, user_account)
示例13: doScrape
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [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"
示例14: Gmail
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
import serial
import time
from datetime import datetime
from gmail import Gmail
# Don't forget to replace the email and password in config.py!
g = Gmail()
g.login(config.email, config.password)
# Runs every 10 seconds
while True:
# Connect to the Bean via virtual serial port. Wait 250ms at most.
# Set up the Bean you want to use as a virtual serial device in the
# Bean Loader App for OS X.
ser = serial.Serial('/tmp/tty.LightBlue-Bean', 9600, timeout=0.25)
twitter_emails = g.inbox().mail(sender='[email protected]')
facebook_emails = g.inbox().mail(sender='facebookmail.com')
all_emails = g.inbox().mail(unread=True)
# Display how many emails were found in the inbox
print datetime.now()
print 'Twitter notifications:', len(twitter_emails)
print 'Facebook notifications:', len(facebook_emails)
print 'All unread emails:', len(all_emails)
print
# Mark all emails as read so we don't trigger on the same email each time
for email in twitter_emails:
email.read()
for email in facebook_emails:
email.read()
示例15: calculate_email_stats
# 需要导入模块: from gmail import Gmail [as 别名]
# 或者: from gmail.Gmail import inbox [as 别名]
#.........这里部分代码省略.........
else:
last_responder_was_counterparty.append(conversation)
if all([email_in_aliases(email.fr, ALIASES) for email in conversation.thread]):
only_sender_was_me.append(conversation)
inbound_emails = [email for email in emails \
if (email_in_aliases(email.to, ALIASES) and \
not email_in_aliases(email.fr, ALIASES))]
outbound_emails = [email for email in emails \
if (email_in_aliases(email.fr, ALIASES) and \
not email_in_aliases(email.to, ALIASES))]
selfie_emails = [email for email in emails \
if (email_in_aliases(email.fr, ALIASES) and \
email_in_aliases(email.to, ALIASES))]
other_emails = [email for email in emails \
if (not email_in_aliases(email.fr, ALIASES) and \
not email_in_aliases(email.to, ALIASES))]
email_days = set(email.sent_at.date() for email in emails)
emails_received_by_day = [(email_day, len([email for email in inbound_emails if email.sent_at.date() == email_day])) for email_day in email_days]
emails_sent_by_day = [(email_day, len([email for email in outbound_emails if email.sent_at.date() == email_day])) for email_day in email_days]
emails_received_by_day.sort(cmp=lambda x,y: cmp(x,y))
emails_sent_by_day.sort(cmp=lambda x,y: cmp(x,y))
emails_received_by_day = [{"date": "{} {}".format(day_of_week(date.weekday()), date.day), "count": count} for (date, count) in emails_received_by_day]
emails_sent_by_day = [{"date": "{} {}".format(day_of_week(date.weekday()), date.day), "count": count} for (date, count) in emails_sent_by_day]
write("Sorted emails")
write("* " * 25)
inbox_total = g.inbox().count()
inbox_unread = g.inbox().count(unread=True)
total_email_count = total_email_count
ignored_for_email = ignored_for_email
ignored_for_subject = ignored_for_subject
ignored_for_body = ignored_for_body
num_remaining_emails = len(emails)
num_threads = len(threads)
num_inbound_emails = len(inbound_emails)
num_outbound_emails = len(outbound_emails)
num_selfie_emails = len(selfie_emails)
num_other_emails = len(other_emails)
num_last_responder_was_me = len(last_responder_was_me)
num_last_responder_was_counterparty = len(last_responder_was_counterparty)
response_times = []
for thread in (last_responder_was_counterparty + last_responder_was_me):
response_times.extend(thread.get_response_times())
senders = {}
for response_time in response_times:
if not response_time.get("fr"):
continue
sender = response_time.get("fr").lower()
name, email_address = parseaddr(sender)
if not email_address in senders.keys():
senders[email_address] = {'response_times':[]}
senders[email_address]['response_times'].append(response_time.get("response_time"))
emails_sent_per_person = [(sender, len(senders[sender].get("response_times"))) for sender in senders.keys()]
emails_sent_per_person.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True)