Read Email, pop3

[toc]In this tutorial you will learn how to receive email using the poplib module. The mail server needs to support pop3, but most mail servers do this.  The Post Office Protocol (POP3) is for receiving mail only, for sending you will need the SMTP protocol.

pop3-email-server
Simplified Mail Server

Related course:
Python Programming Bootcamp: Go from zero to hero

Meta Data

Every email will contain many variables, but these are the most important ones:

Feature Description
message-id unique identifier
from where did the email come from?
to where was the email sent to?
date date
subject Email subject.

Reading Email Example

You can request messages directly from a mail server using the Post Office Protocol (protocol). You do not have to worry about the internal protocol because you can use the poplib module.
Connect and authenticate with the server using:

# connect to server
server = poplib.POP3(SERVER)
 
# login
server.user(USER)
server.pass_(PASSWORD)

The program below gets 10 emails from the server including mail header

import poplib
import string, random
import StringIO, rfc822
 
def readMail():
SERVER = "YOUR MAIL SERVER"
USER = "YOUR USERNAME [email protected]"
PASSWORD = "YOUR PASSWORD"
 
# connect to server
server = poplib.POP3(SERVER)
 
# login
server.user(USER)
server.pass_(PASSWORD)
 
# list items on server
resp, items, octets = server.list()
 
for i in range(0,10):
id, size = string.split(items[i])
resp, text, octets = server.retr(id)
 
text = string.join(text, "\n")
file = StringIO.StringIO(text)
 
message = rfc822.Message(file)
 
for k, v in message.items():
print k, "=", v
 
readMail()

Building an IRC (ro)bot

There are tons of (ro)bots out there for IRC (Internet Relay Chat). So how do you start and build one in Python, just for fun?

You will need a program that connects with an IRC server and acts like a traditional IRC client.  IRC servers never ask for any type of complicated human verification such as solving captchas, which is why we can simply connect with a script. The script itself will use network sockets,  a library that is often used to provide network interactions in many programming languages including Python and C/C++.

Related course
Python Scripting for Network Engineers: Realizing Network Automation for Reliable Networks

IRC and Python
To communicate with an IRC server, you need to use the IRC protocol.  The IRC protocol has distinct messages such as PRIVMSG, USER, NICK and JOIN. If you are curious, you could read the entire protocol. But following this tutorial may be a lot simpler 😉 Authentication is achieved using only a few steps:

The IRC protocol is a layer on top of the IP protocol.   To create a socket we use the command:

 irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

socket.AF_INET tells the library to use the network protocol IPv4.   The second argument tells the library to use stream sockets, which are traditionally implemented on the TCP protocol. (IRC works over TCP/IP). We then must use the commands to authenticate with the server:

USER botname botname botname: phrase
NICK botname
JOIN #channel

Sometimes the IDENT command is neccesary too. Summing up, we get this class (save it as irc.py):

import socket
import sys
 
 
class IRC:
 
    irc = socket.socket()
  
    def __init__(self):  
        self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
    def send(self, chan, msg):
        self.irc.send("PRIVMSG " + chan + " " + msg + "n")
 
    def connect(self, server, channel, botnick):
        #defines the socket
        print "connecting to:"+server
        self.irc.connect((server, 6667))                                                         #connects to the server
        self.irc.send("USER " + botnick + " " + botnick +" " + botnick + " :This is a fun bot!n") #user authentication
        self.irc.send("NICK " + botnick + "n")               
        self.irc.send("JOIN " + channel + "n")        #join the chan
 
    def get_text(self):
        text=self.irc.recv(2040)  #receive the text
 
        if text.find('PING') != -1:                      
            self.irc.send('PONG ' + text.split() [1] + 'rn') 
 
        return text

Now that we have the network connectivity class, we can use it as an instance.  We will keep our (ro)bot simple for explanatory purposes. The bot will reply “Hello!” if it gets the message “hello” in the channel it resides.

from irc import *
import os
import random
 
channel = "#testit"
server = "irc.freenode.net"
nickname = "reddity"
 
irc = IRC()
irc.connect(server, channel, nickname)
 
 
while 1:
    text = irc.get_text()
    print text
 
    if "PRIVMSG" in text and channel in text and "hello" in text:
        irc.send(channel, "Hello!")

Save it as bot.py and run with python bot.py. Connect with a traditional irc client (mirc,hexchat,irsii) to the the channel and observe the experiment has worked! You can now extend it with any cool features you can imagine.

Posts navigation

1 2