correo enviar y recibir v.1
This commit is contained in:
commit
848043007f
|
@ -0,0 +1,46 @@
|
||||||
|
import smtplib
|
||||||
|
from email.mime.multipart import MIMEMultipart
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# Configuración del servidor SMTP (Sin SSL)
|
||||||
|
SMTP_SERVER = "192.168.120.103"
|
||||||
|
SMTP_PORT = 25 # También puedes probar 587 si 25 no funciona
|
||||||
|
EMAIL_USER = "pruebas@psp.ieslamar.org"
|
||||||
|
EMAIL_PASS = "1234"
|
||||||
|
|
||||||
|
def enviar_correo(destinatario, asunto, mensaje):
|
||||||
|
try:
|
||||||
|
# Obtener la fecha y hora actual
|
||||||
|
fecha_envio = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
# Crear mensaje con la fecha incluida
|
||||||
|
msg = MIMEMultipart()
|
||||||
|
msg["From"] = EMAIL_USER
|
||||||
|
msg["To"] = destinatario
|
||||||
|
msg["Subject"] = asunto
|
||||||
|
msg["Date"] = fecha_envio # Agregar la fecha en la cabecera del correo
|
||||||
|
|
||||||
|
# Formato del mensaje con la fecha en el cuerpo
|
||||||
|
mensaje_completo = f"""
|
||||||
|
asdasdsad
|
||||||
|
|
||||||
|
{mensaje}
|
||||||
|
"""
|
||||||
|
|
||||||
|
msg.attach(MIMEText(mensaje_completo, "plain")) # Mensaje en texto plano
|
||||||
|
|
||||||
|
# Conectar al servidor SMTP SIN SSL
|
||||||
|
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
|
||||||
|
server.ehlo()
|
||||||
|
server.login(EMAIL_USER, EMAIL_PASS) # Iniciar sesión
|
||||||
|
server.sendmail(EMAIL_USER, destinatario, msg.as_string())
|
||||||
|
server.quit()
|
||||||
|
|
||||||
|
print(f"Correo enviado a {destinatario} el {fecha_envio}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error enviando correo: {e}")
|
||||||
|
|
||||||
|
# Uso del script
|
||||||
|
enviar_correo("kevin@psp.ieslamar.org", "Prueba de Correo", "Este es un mensaje de prueba sin SSL.")
|
|
@ -0,0 +1,107 @@
|
||||||
|
import poplib
|
||||||
|
import email
|
||||||
|
import pymongo
|
||||||
|
import threading
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
|
# Configuración del servidor POP3 (Sin SSL)
|
||||||
|
POP3_SERVER = "192.168.120.103"
|
||||||
|
POP3_PORT = 110 # Puerto POP3 estándar sin SSL
|
||||||
|
EMAIL_USER = "kevin@psp.ieslamar.org"
|
||||||
|
EMAIL_PASS = "1234"
|
||||||
|
|
||||||
|
# Configuración de la base de datos MongoDB
|
||||||
|
MONGO_CLIENT = "mongodb://localhost:27017/"
|
||||||
|
DB_NAME = "correo_db"
|
||||||
|
COLLECTION_NAME = "correos"
|
||||||
|
|
||||||
|
# Conectar a MongoDB
|
||||||
|
client = pymongo.MongoClient(MONGO_CLIENT)
|
||||||
|
db = client[DB_NAME]
|
||||||
|
collection = db[COLLECTION_NAME]
|
||||||
|
|
||||||
|
def guardar_correo(remitente, asunto, fecha, cuerpo):
|
||||||
|
""" Guarda un correo en la base de datos si no existe. """
|
||||||
|
if collection.find_one({"remitente": remitente, "asunto": asunto, "fecha": fecha}):
|
||||||
|
print("⚠️ Correo ya guardado, se omite.")
|
||||||
|
return
|
||||||
|
|
||||||
|
correo = {
|
||||||
|
"remitente": remitente,
|
||||||
|
"asunto": asunto,
|
||||||
|
"fecha": fecha,
|
||||||
|
"cuerpo": cuerpo
|
||||||
|
}
|
||||||
|
collection.insert_one(correo)
|
||||||
|
print("✅ Correo guardado en la base de datos.")
|
||||||
|
|
||||||
|
def descargar_correos():
|
||||||
|
""" Descarga correos en un hilo separado y los guarda en MongoDB. """
|
||||||
|
try:
|
||||||
|
print("📡 Conectando al servidor POP3 para descargar correos...\n")
|
||||||
|
mail = poplib.POP3(POP3_SERVER, POP3_PORT)
|
||||||
|
mail.user(EMAIL_USER)
|
||||||
|
mail.pass_(EMAIL_PASS)
|
||||||
|
|
||||||
|
num_mensajes = len(mail.list())
|
||||||
|
print(f"📩 Se encontraron {num_mensajes} correos en la bandeja de entrada.\n")
|
||||||
|
|
||||||
|
for i in range(max(1, num_mensajes - 4), 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")
|
||||||
|
|
||||||
|
guardar_correo(remitente, asunto, fecha, cuerpo.strip())
|
||||||
|
|
||||||
|
mail.quit()
|
||||||
|
print("✅ Descarga de correos completada.\n")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error al descargar correos: {e}")
|
||||||
|
|
||||||
|
def consultar_correos():
|
||||||
|
""" Consulta los correos almacenados en MongoDB y los muestra en otro hilo. """
|
||||||
|
print("📂 Consultando correos en la base de datos...\n")
|
||||||
|
correos = collection.find()
|
||||||
|
|
||||||
|
for correo in correos:
|
||||||
|
print(f"📅 Fecha: {correo['fecha']}")
|
||||||
|
print(f"🔹 Remitente: {correo['remitente']}")
|
||||||
|
print(f"📌 Asunto: {correo['asunto']}")
|
||||||
|
print(f"📝 Mensaje:\n{correo['cuerpo']}")
|
||||||
|
print("-" * 40)
|
||||||
|
|
||||||
|
def ejecutar_en_hilos():
|
||||||
|
""" Ejecuta la descarga y consulta de correos en hilos separados para mayor eficiencia. """
|
||||||
|
hilo_descarga = threading.Thread(target=descargar_correos)
|
||||||
|
hilo_consulta = threading.Thread(target=consultar_correos)
|
||||||
|
|
||||||
|
# Iniciar hilos
|
||||||
|
hilo_descarga.start()
|
||||||
|
hilo_consulta.start()
|
||||||
|
|
||||||
|
# Esperar a que terminen
|
||||||
|
hilo_descarga.join()
|
||||||
|
hilo_consulta.join()
|
||||||
|
|
||||||
|
# Ejecutar el programa con hilos
|
||||||
|
ejecutar_en_hilos()
|
Loading…
Reference in New Issue