/ Published in: Python
The following code snippet shows a basic POP3 class, which can get the total message count and message details.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import socket; class POP3(): def __init__(self, host, port): self.log = "" ip = socket.gethostbyname(host) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = self.sock.connect_ex((ip, port)) if result == 0: self.log += "GREETING: " +self.read_line() def credentials(self, username, password): self.send_cmd("USER " + username + "\n") self.log += "USER: " + self.read_line() self.send_cmd("PASS " + password + "\n") self.log += "PASS: " + self.read_line() def msg_count(self): self.send_cmd("STAT\n") response = self.read_line() parts = response.split(" ") return parts[1] def get_message(self, msg_index): message = POP3Message() self.send_cmd("RETR " + str(msg_index) + "\n") parts = self.read_line().split(" ") if parts[0] == "+OK": size = int(parts[1]) data = "" while len(data) < size: data += self.sock.recv(1024).decode("utf-8") lines = data.split("\n") headers = {} is_header = True body = "" for line in lines: if line.strip() != "" and is_header == True: key_value_header = line.strip().split(":", 1) if len(key_value_header) == 2: headers[key_value_header[0].strip()] = key_value_header[1].strip() else: is_header = False if is_header == False: body += line message.set_from(headers["From"]) message.set_to(headers["To"]) message.set_subject(headers["Subject"]) message.set_date(headers["Date"]) message.set_body(body) return message def get_log(self): return self.log def send_cmd(self, cmd): self.sock.sendall(bytes(cmd, "UTF-8")) def read_line(self): return self.sock.recv(1024).decode("utf-8") class POP3Message(): def set_from(self, fromAddr): self.fromAddr = fromAddr def get_from(self): return self.fromAddr def set_to(self, to): self.to = to def get_to(self): return self.to def set_subject(self, subject): self.subject = subject def get_subject(self): return self.subject def set_date(self, date): self.date = date def get_date(self): return self.date def set_body(self, body): self.body = body def get_body(self): return self.body pop_client = POP3("pop.host.com", 110) pop_client.credentials("username", "password") print("Message count:" + pop_client.msg_count()) message = pop_client.get_message(1) print("From: " + message.get_from()) print("To: " + message.get_to()) print("Subject: " + message.get_subject()) print("Date: " + message.get_date()) print("Body: " + message.get_body()) print(pop_client.get_log())
URL: http://www.hostprojects.net/snippets/python/147/simple-pop3-class