Retrieving emails with SSL

POP3_SSL() is the secure version of POP3(). This class takes additional parameters, such as keyfile and certfile, which are used for supplying the SSL certificate files, namely the private key and certificate chain file. Writing for a POP3 client is also very straightforward. To do this, instantiate a mailbox object by initializing the POP3() or POP3_SSL() classes. Then, invoke the user() and pass_() methods to login to the server by using the following command:

mailbox = poplib.POP3_SSL("POP3_SERVER", "SERVER_PORT")
mailbox.user('username')
mailbox.pass_('password')
You can see the basic POP3 example from the documentation: http://docs.python.org/library/poplib.html#pop3-example.
We can retrieve all of the messages from an email account with the retr method. The following link provides documentation about this method: https://docs.python.org/3/library/poplib.html#poplib.POP3.retr.

Here is a minimal example that opens a mailbox and retrieves all of its messages. First, we create a POP3_SSL object (Gmail works with SSL) and enter our username and password. From here, we can manage our emails with the functions that are provided by the poplib library. In this example, we obtain the list of messages with the list() method. The last message is chosen from the response and the server is requested through retr(msgid).

You can find the following code in the mailbox_basic.py file:

#!/usr/bin/env python3

import poplib

mailbox = poplib.POP3_SSL("pop.gmail.com",995)
mailbox.user("user")
mailbox.pass_("password")

print(mailbox.getwelcome())

messages = len(mailbox.list()[1])

for index in range(messages):
for message in mailbox.retr(index+1)[1]:
print(message)

mailbox.quit()

In this example, we have the same functionality from the previous script—the only difference is how we get the params server, port, user, and password from the command line.

You can find the following code in the mailbox_basic_params.py file:

#!/usr/bin/env python3

import poplib
import argparse

def main(hostname,port,user,password):

mailbox = poplib.POP3_SSL(hostname,port)

try:
mailbox.user(user)
mailbox.pass_(password)
response, listings, octet_count = mailbox.list()
for listing in listings:
number, size = listing.decode('ascii').split()
print("Message %s has %s bytes" % (number, size))

except poplib.error_proto as exception:
print("Login failed:", exception)

finally:
mailbox.quit()

In the previous code block we have defined our function that accepts as parameters the hostname,port,user and password and establish the connection with this configuration.In the next code block we use the argparse module for setting the parameters used by the main() method.

if __name__ == '__main__':
parser = argparse.ArgumentParser(description='MailBox basic params')
parser.add_argument('--hostname', action="store", dest="hostname")
parser.add_argument('--port', action="store", dest="port")
parser.add_argument('--user', action="store", dest="user")
given_args = parser.parse_args()
hostname = given_args.hostname
port = given_args.port
user = given_args.user
import getpass
password = getpass.getpass(prompt='Enter your password:')
main(hostname,port,user,password)

Let's see how we can read out the email messages by accessing Google's secure POP3 email server. By default, the POP3 server listens on port 995 securely. The following is an example of fetching an email by using POP3.

Get the total number of messages:

(messagesNumber, size) = mailbox.stat()

Get a specific message by using your mailbox number:

response, headerLines, bytes = mailbox.retr(i+1)

You can find the following code in the poplib_gmail.py file:

#!/usr/bin/env python3

import poplib
import getpass

mailbox = poplib.POP3_SSL ('pop.gmail.com', 995)
username = input('Enter your username:')
password = getpass.getpass(prompt='Enter your password:')

mailbox.user(username)
mailbox.pass_(password)

EmailInformation = mailbox.stat()
print("Number of new emails: %s ", EmailInformation)
numberOfMails = EmailInformation[0]

num_messages = len(mailbox.list()[1])

In the previous code block we initialize the connection with pop3 server mail and store information about connection in mailbox object, later we get information about stats and the messages number. In the next code block we use the mailbox object to retrieve information about each message contained in the mailbox.

for i in range (num_messages):
print(" Message number "+str(i+1))
print("--------------------")
# read message
response, headerLines, bytes = mailbox.retr(i+1)
#for header in headerLines:
#print(str(header))
print('Message ID', headerLines[1])
print('Date', headerLines[2])
print('Reply To', headerLines[4])
print('To', headerLines[5])
print('Subject', headerLines[6])
print('MIME', headerLines[7])
print('Content Type', headerLines[8])

mailbox.quit()

In this example we have extracted mails from our mailbox server using the list() method.For each message we can print all information available in headerLines array .Also we can get information in that array accessing specific index like headerLines[1] for get Message ID or headerLines[5] for get mail destination.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset