Once you are familiar with managing a POP3 mailbox with poplib and getting login information with getpass, you can use the two together to access (or "pop") any mailbox on-the-fly. First things first, import the relevant modules:
Then get the username. Using Python's built-in input() function here will consistently result in errors. input() treats all strings as variable names - even email logins. Therefore, you need to use raw_input() to ensure the string is not misunderstood.
import getpass, poplib
This gives the user a prompt of "Username:" and places the ensuing input into a variable user.
user = raw_input('Username:')
We then should the same thing with the server, protocol, and port number. If you use this code for only one server, you can hardwire the values into the program, otherwise, you need to go back to the user:
We then need to follow this with an if loop to set the value for the mailbox object:
server = raw_input('Server Address:') type = raw_input('Encrypted with SSL (Y/N):') port = raw_input('Port:')
This bit of code obviously expects the user to know the port number involved. With another if loop, however, one can allow for custom ports and defaults. POP3 defaults to port 110. POP3 over SSL (POP3_SSL) defaults to port 995.
if type=="Y": Mailbox = poplib.POP3_SSL(server, port) else: Mailbox = poplib.POP3(server, port)
With the mailbox object created, we then login with login user.
Note that method user is used to specify a username for logging into the server. If the username is left off, the default is to use the name associated with the calling process or user - whether the local user or a suid user. Therefore, you should fail softly here (even though here we don't for the sake of brevity). For tips on managing exceptions and errors, see Python's built-in exceptions and warnings. For help on how to use them, see "Exceptions, Errors, and Warnings."
Before we can initiate the login process, however, we need to get the password.
To get the password for the account, we use the getpass() function from the getpass module.
This allows entry of the password in a secured manner. Having logged in successfully, we just need to download the messages.
Then we simply set up a loop that counts the messages and retrieves each message in sequence until the end of the box is reached.
messageCount = len(Mailbox.list())
This merely prints the messages to the screen. Naturally, if you have more than a couple messages on the server, you will not get to see them all in one go. It is best, therefore, to either pipe the output to a text file or rewrite the code to write it to a file, perhaps named after the server address input by the user.
for i in range(messageCount): for j in Mailbox.retr(i+1): print j