Properly formatted example for Python iMAP email access?

tldr: Can someone show me how to properly format this Python iMAP example so it works?

from https://docs.python.org/2.4/lib/imap4-example.html

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

Assuming my email is "email@gmail.com" and the password is "password," how should this look? I tried M.login(getpass.getuser(email@gmail.com), getpass.getpass(password)) and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).


Asked by: Marcus746 | Posted: 06-10-2021






Answer 1

Here is a script I used to use to grab logwatch info from my mailbox. Presented at LFNW 2008 -

#!/usr/bin/env python

''' Utility to scan my mailbox for new mesages from Logwatch on systems and then
    grab useful info from the message and output a summary page.

    by Brian C. Lane <bcl@brianlane.com>
'''
import os, sys, imaplib, rfc822, re, StringIO

server  ='mail.brianlane.com'
username='yourusername'
password='yourpassword'

M = imaplib.IMAP4_SSL(server)
M.login(username, password)
M.select()
typ, data = M.search(None, '(UNSEEN SUBJECT "Logwatch")')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
#   print 'Message %s\n%s\n' % (num, data[0][1])

    match = re.search(  "^(Users logging in.*?)^\w",
                        data[0][1],
                        re.MULTILINE|re.DOTALL )
    if match:
        file = StringIO.StringIO(data[0][1])
        message = rfc822.Message(file)
        print message['from']
        print match.group(1).strip()
        print '----'

M.close()
M.logout()

Answered by: Wilson206 | Posted: 07-11-2021



Answer 2

import imaplib

# you want to connect to a server; specify which server
server= imaplib.IMAP4_SSL('imap.googlemail.com')
# after connecting, tell the server who you are
server.login('email@gmail.com', 'password')
# this will show you a list of available folders
# possibly your Inbox is called INBOX, but check the list of mailboxes
code, mailboxen= server.list()
print mailboxen
# if it's called INBOX, then…
server.select("INBOX")

The rest of your code seems correct.

Answered by: Roman902 | Posted: 07-11-2021



Answer 3

Did you forget to specify the IMAP host and port? Use something to the effect of:

M = imaplib.IMAP4_SSL( 'imap.gmail.com' )

or,

M = imaplib.IMAP4_SSL()
M.open( 'imap.gmail.com' )

Answered by: Aston724 | Posted: 07-11-2021



Answer 4

Instead of M.login(getpass.getuser(email@gmail.com), getpass.getpass(password)) you need to use M.login('email@gmail.com', 'password'), i.e. plain strings (or better, variables containing them). Your attempt actually shouldn't have worked at all, since getpass's getuser doesn't take arguments but merely returns the user login name. And email@gmail.com isn't even a valid variable name (you didn't put it into quotes)...

Answered by: Thomas203 | Posted: 07-11-2021



Similar questions

python - CSV formatted data off website not being properly parsed

My Python script opens a file through urllib2; the data looks like this: "Charitable Donation: Contribution","012","","","","","","","","","","","","","","","","","","","","" The Python script: reader = csv.reader(data, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: print row The output is this: ['Charitable Don...


Python syntax error in seeming properly formatted code

Closed. This question is not reproducible or was caused...


python - Passing properly formatted windows pathname to SQL server via PYODBC

I need python to issue a query via pyodbc to insert a .PNG file into a table as a blob. The problem seems to have something to do with how the path to the file is represented. Here's some code: OutFilePath = 'd:\\DilerBW_images\\' OutFileName = SubjID+'_'+str(UserID)+'_'+DateTime+'.png' print OutFilePath+OutFileName qstring = ('insert into [wpic-smir].[Diler_BW].[Beckwith].[PlotI...


python - How to read wrongly formatted string in csv properly?

In csv, for a column there is ambiguity in string. Because of that, I'm getting 6 values in list instead of 5 values as output. Code: import csv csv_data = csv.reader(file('test.csv')) for row in csv_data: print row I tried to replace " with space to get atleast as normal string with out any quotes, as shown b...


python - Web scrape a website not formatted properly

I am working on scraping a web site link is &quot;https://homeshopping.pk/search.php?q=samsung%20phones&quot;. Iam finding difficulty in accessing to one of the div class. I think its is not formatted properly. Reason for asking this question is to confirm that is it not formatted properly or I am doing something wrong. Screenshot is:


python - Tables from panda is not properly formatted

I am trying to convert a dictionary item into tables using pandas, but the problem is that I am not getting the desired results. here is my code below value = new_stock(data) dict_stocks = {i: value[i] for i in range (0, len(value))} df = pd.DataFrame(list(dict_stocks.items()), columns =['Company Name', 'Price per share', Total valuation]) print(df) I want the output to be like


python - How to fix broken CSV file where column values are not formatted properly?

I have a dataframe that has a weird format that I am having difficulty formatting it to a desired format. I just need the columns first_name, last_name, domain, Email, Verification and status but am not sure how to remove it when it is in this format. ,first_name,last_name,domain,Email,Score,Verification status,Source 1,Source 2,So...


python - How to plot a graph from a txt file that is not properly formatted?

I need to plot a graph from data in a given text file, but the text file is not really properly formatted for easy extraction of data. Is there some way to automate the extraction of the data I need into proper lists or dataframe in something like Jupyter notebook with python to plot a graph easily? Here's how the file currently looks like: ########### Average Hybridsort CPU time, ar...


python - How to make my code formatted properly in columns

I want my code to come out looking like the image below. My code is below that nums = list(range(1,101)) chunks = [] for i in range(1, len(nums)+1): if i % 10 == 0: print(i, end = &quot; &quot;) print() else: print(i, end = &quot; &quot;)


python - Parsing json that doesn't seem to be properly formatted

I'm trying to do some work with real estate data and after failing on my own managed to borrow a code that pulled some of the data. Unfortunately I have no idea how to parse the rest, as the json formatting is very confusing to me. This is not my area of expertise so if anyone has ideas on how to approach this I would greatly appreciate it. If needed I can post the entire json but it's very long. im...


How can I unpack binary hex formatted data in Python?

Using the PHP pack() function, I have converted a string into a binary hex representation: $string = md5(time); // 32 character length $packed = pack('H*', $string); The H* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the unpack(...


python - Passing Formatted Text Through XSLT

I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform without losing the original formatting? I have access to the transformation script and the python script but not the transform invocation itself.


How are booleans formatted in Strings in Python?

I see I can't do: "%b %b" % (True, False) in Python. I guessed %b for b(oolean). Is there something like this?


Is there a way for me to get detailed formatted information on a Python class?

So, I know I can use dir() to get information about class members etc. What I'm looking for is a way to get a nicely formatted report on everything related to a class (the members, docstrings, inheritance hierarchy, etc.). I want to be able to run this on the command-line so I can explore code and debug better.


python - how to extract formatted text content from PDF

How can I extract the text content (not images) from a PDF while (roughly) maintaining the style and layout like Google Docs can?


datetime - Python: date formatted with %x (locale) is not as expected

I have a datetime object, for which I want to create a date string according to the OS locale settings (as specified e.g. in Windows'7 region and language settings). Following Python's datetime formatting documentation, I used the %x format code which is supposed to output "Locale’s a...


python - Removing broken tags and poorly formatted html from some text

i have a huge database of scraped forum posts that i am inserting into a website. however alot of people try to use html in their forum posts and often times do it wrong. because of this, there are always stray &lt;strike&gt; &lt;b&gt; &lt;/strike&gt; &lt;/div&gt; &lt;/b&gt; tags in the posts which will end up messing up the webpage format when i add say 15 forum posts. for now i have just been append...


Python convert formatted string to list

I have a string "[u'foo']" (Yes, it includes the square brackets and the u''). I have to convert that to a list which looks like [u'foo']. list("[u'foo']") won't work. Any suggestions?


Getting formatted datetime in Python like in PHP

How to get formatted date time in Python the same way as in PHP date('M d Y', $timestamp);?


python - Create an html formatted report

I have a Python 2.6 app running on Linux that creates a CSV file. From the app, I need to create an HTML report, as a single HTML file, that presents the data from the CSV (probably as a table) and also highlights fields where the values meet certain criteria. Charting type functionality would be a nice to have. What's the best way to do this? No GPL stuff please.






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top