GestorCorreo/modelo.py

111 lines
3.8 KiB
Python

import poplib
import email
import pymongo
from email.utils import parsedate_to_datetime
class CorreoModelo:
POP3_SERVER = "192.168.120.103"
POP3_PORT = 110
EMAIL_USER = "kevin@psp.ieslamar.org"
EMAIL_PASS = "1234"
MONGO_CLIENT = "mongodb://localhost:27017/"
DB_NAME = "correo_db"
COLLECTION_NAME = "correos"
def __init__(self):
self.client = pymongo.MongoClient(self.MONGO_CLIENT)
self.db = self.client[self.DB_NAME]
self.collection = self.db[self.COLLECTION_NAME]
def correo_existe(self, remitente, asunto, fecha):
return self.collection.find_one({"remitente": remitente, "asunto": asunto, "fecha": fecha}) is not None
def guardar_correo(self, remitente, asunto, fecha, cuerpo):
if self.correo_existe(remitente, asunto, fecha):
return
correo = {"remitente": remitente, "asunto": asunto, "fecha": fecha, "cuerpo": cuerpo}
self.collection.insert_one(correo)
def descargar_correos(self):
try:
mail = poplib.POP3(self.POP3_SERVER, self.POP3_PORT)
mail.user(self.EMAIL_USER)
mail.pass_(self.EMAIL_PASS)
num_mensajes = len(mail.list()[1])
mensajes_nuevos = False
for i in range(1, num_mensajes + 1):
response, lines, octets = mail.retr(i)
raw_email = b"\n".join(lines)
msg = email.message_from_bytes(raw_email)
remitente = msg["From"]
asunto = msg["Subject"]
fecha = msg["Date"]
if fecha:
try:
fecha = parsedate_to_datetime(fecha).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
pass
cuerpo = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
cuerpo = part.get_payload(decode=True).decode(errors="ignore")
break
else:
cuerpo = msg.get_payload(decode=True).decode(errors="ignore")
if not self.correo_existe(remitente, asunto, fecha):
self.guardar_correo(remitente, asunto, fecha, cuerpo.strip())
mensajes_nuevos = True
mail.quit()
return True
except Exception as e:
return str(e)
def obtener_correos(self):
return list(self.collection.find())
def hay_mensajes_nuevos(self):
"""
Verifica si hay correos nuevos en el servidor POP3 que no estén en la base de datos.
"""
try:
mail = poplib.POP3(self.POP3_SERVER, self.POP3_PORT)
mail.user(self.EMAIL_USER)
mail.pass_(self.EMAIL_PASS)
num_mensajes = len(mail.list()[1])
for i in range(1, num_mensajes + 1):
response, lines, octets = mail.retr(i)
raw_email = b"\n".join(lines)
msg = email.message_from_bytes(raw_email)
remitente = msg["From"]
asunto = msg["Subject"]
fecha = msg["Date"]
if fecha:
try:
fecha = parsedate_to_datetime(fecha).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
pass
if not self.correo_existe(remitente, asunto, fecha):
mail.quit()
return True # Hay al menos un mensaje nuevo
mail.quit()
return False # No hay mensajes nuevos
except Exception as e:
return False # En caso de error, asumimos que no hay nuevos mensajes