You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
InterfazEmail/test2_proyecto_app_correo.py

219 lines
9.1 KiB

import tkinter as tk
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import imaplib
import email
# Ventana principal
ventana_principal = None
# Funciones para la interfaz gráfica
def abrir_ventana_enviar_correo():
# Ventana para enviar correo
ventana_enviar = tk.Toplevel(ventana_principal)
ventana_enviar.title("Enviar Correo")
# Configurar el tamaño y la posición de la ventana
ancho_ventana = 600
alto_ventana = 400
x_ventana = ventana_principal.winfo_screenwidth() // 2 - ancho_ventana // 2
y_ventana = ventana_principal.winfo_screenheight() // 2 - alto_ventana // 2
ventana_enviar.geometry(f"{ancho_ventana}x{alto_ventana}+{x_ventana}+{y_ventana}")
# Campos para ingresar información
etiqueta_destinatario = tk.Label(ventana_enviar, text="Destinatario:")
etiqueta_destinatario.pack()
entrada_destinatario = tk.Entry(ventana_enviar)
entrada_destinatario.pack()
etiqueta_asunto = tk.Label(ventana_enviar, text="Asunto:")
etiqueta_asunto.pack()
entrada_asunto = tk.Entry(ventana_enviar)
entrada_asunto.pack()
etiqueta_mensaje = tk.Label(ventana_enviar, text="Mensaje:")
etiqueta_mensaje.pack()
entrada_mensaje = tk.Text(ventana_enviar, height=8, width=60)
entrada_mensaje.pack()
# Función para enviar correo
def enviar():
destinatario = entrada_destinatario.get()
asunto = entrada_asunto.get()
mensaje = entrada_mensaje.get("1.0", tk.END)
body = mensaje
enviado_por = 'test@psp.fp'
password = 'Abcd#1234#'
msg = MIMEMultipart()
msg['From'] = enviado_por
msg['To'] = destinatario
msg['Subject'] = asunto
msg.attach(MIMEText(body, 'plain'))
try:
session = smtplib.SMTP('localhost', 25)
session.starttls()
session.login(enviado_por, password)
text = msg.as_string()
session.sendmail(enviado_por, destinatario, text)
session.quit()
messagebox.showinfo("Éxito", "Correo enviado correctamente")
ventana_enviar.destroy()
except Exception as e:
messagebox.showerror("Error", f"Error al enviar el correo: {str(e)}")
# Botón para enviar correo
boton_enviar = tk.Button(ventana_enviar, text="Enviar", command=enviar)
boton_enviar.pack()
def abrir_ventana_consultar_bandeja():
# Ventana para mostrar la bandeja de entrada
ventana_bandeja = tk.Toplevel(ventana_principal)
ventana_bandeja.title("Bandeja de Entrada")
# Configuramos el tamaño y la posición de la ventana
ancho_ventana = 800
alto_ventana = 600
x_ventana = ventana_principal.winfo_screenwidth() // 2 - ancho_ventana // 2
y_ventana = ventana_principal.winfo_screenheight() // 2 - alto_ventana // 2
ventana_bandeja.geometry(f"{ancho_ventana}x{alto_ventana}+{x_ventana}+{y_ventana}")
# Título para la bandeja de entrada
label_titulo = tk.Label(ventana_bandeja, text="Mi Bandeja de Entrada", font=("Courier New", 14, "bold"))
label_titulo.pack(pady=15)
# Este código nos servirá para consultar la bandeja de entrada de un correo de usuario concreto
user = 'jn@psp.fp'
password = 'Abcd#1234#'
imap_url = 'localhost'
#Aquí obtenemos la bandeja de entrada de un remitente concreto
def search(key, value, con):
result, data = con.search(None, key, '"{}"'.format(value))
return data
def get_emails(result_bytes):
msgs = []
for num in result_bytes[0].split():
typ, data = con.fetch(num, '(RFC822)')
msgs.append(data)
return msgs
con = imaplib.IMAP4_SSL(imap_url)
con.login(user, password)
con.select('Inbox') # Seleccionamos la bandeja de entrada para leer los correos recibidos
msgs = get_emails(search('FROM', 'test@psp.fp', con)) #Aquí obtenemos la bandeja de entrada de un remitente concreto
# Mostramos los correos en una lista
lista_correos = tk.Listbox(ventana_bandeja, selectmode=tk.SINGLE, height=20, width=70)
for msg in msgs[::-1]:
for sent in msg:
if type(sent) is tuple:
content = str(sent[1], 'utf-8')
data = str(content)
try:
indexstart = data.find("ltr")
data2 = data[indexstart + 5: len(data)]
indexend = data2.find("</div>")
# En la lista que se muestra nos quedaremos solo con el remitente, el asunto y el cuerpo/contenido del mensaje
remitente = email.message_from_string(content).get("From", "Desconocido")
asunto = email.message_from_string(content).get("Subject", "Sin asunto")
cuerpo = ""
if email.message_from_string(content).is_multipart():
for parte in email.message_from_string(content).walk():
if parte.get_content_type() == "text/plain":
cuerpo = parte.get_payload(decode=True).decode("utf-8")
break
else:
cuerpo = email.message_from_string(content).get_payload(decode=True).decode("utf-8")
# Agregamos el mensaje a la lista de correos
lista_correos.insert(tk.END, f"Remitente: {remitente} | \n\nAsunto: {asunto} | \n\nMensaje: {cuerpo}")
lista_correos.insert(tk.END, "")
except UnicodeEncodeError as e:
pass
lista_correos.pack(pady=10)
# Función para mostrar el correo seleccionado
def mostrar_correo_seleccionado():
seleccion = lista_correos.curselection()
if seleccion:
# Creamos una nueva ventana para mostrar el detalle del mensaje seleccionado de la lista
ventana_detalle = tk.Toplevel(ventana_bandeja)
ventana_detalle.title("Detalles del Correo")
# Etiqueta para el remitente
etiqueta_remitente = tk.Label(ventana_detalle, text="Remitente:", font=("Courier New", 12, "bold"))
etiqueta_remitente.pack(pady=10)
# Etiqueta para el asunto
etiqueta_asunto = tk.Label(ventana_detalle, text="Asunto:", font=("Courier New", 12, "bold"))
etiqueta_asunto.pack(pady=10)
# Campo de texto para el cuerpo del mensaje
etiqueta_mensaje = tk.Label(ventana_detalle, text="Mensaje:", font=("Courier New", 12, "bold"))
etiqueta_mensaje.pack(pady=10)
# Aquí creamos espacios en blanco para inseratr los datos del remitente, asunto y mensaje
tk.Label(ventana_detalle, text="", font=("Courier New", 12)).pack()
tk.Label(ventana_detalle, text="", font=("Courier New", 12)).pack()
tk.Label(ventana_detalle, text="", font=("Courier New", 12)).pack()
# Configuramos el tamaño y la posición de la ventana del detalle del correo
ancho_ventana = 600
alto_ventana = 400
x_ventana = ventana_principal.winfo_screenwidth() // 2 - ancho_ventana // 2
y_ventana = ventana_principal.winfo_screenheight() // 2 - alto_ventana // 2
ventana_detalle.geometry(f"{ancho_ventana}x{alto_ventana}+{x_ventana}+{y_ventana}")
# Botón para mostrar el detalle del correo seleccionado
boton_mostrar_detalle = tk.Button(ventana_bandeja, text="Mostrar Detalles", command=mostrar_correo_seleccionado)
boton_mostrar_detalle.pack()
def mostrar_menu_principal():
global ventana_principal
# Configuramos la ventana principal de la interfaz para enviar o mostrar correos
ventana_principal = tk.Tk()
ventana_principal.title("Aplicación de Correo")
# Obtenemos el tamaño de la pantalla del usuario/a para centrar la ventana
ancho_pantalla = ventana_principal.winfo_screenwidth()
alto_pantalla = ventana_principal.winfo_screenheight()
# Calculamos la posición para centrar la ventana en la pantalla
x = (ancho_pantalla - ventana_principal.winfo_reqwidth()) // 2 - 120
y = (alto_pantalla - ventana_principal.winfo_reqheight()) // 2 - 120
# Establecemos la posición de la ventana en la pantalla
ventana_principal.geometry(f"500x400+{x}+{y}")
# Añadimos un título antes del menú de opciones
label_titulo = tk.Label(ventana_principal, text="Menú consultar/enviar emails", font=("Courier New", 14, "bold"))
label_titulo.pack(pady=15)
# Botones del menú principal
boton_enviar_correo = tk.Button(ventana_principal, text="Enviar Correo", command=abrir_ventana_enviar_correo)
boton_enviar_correo.pack(pady=10)
boton_consultar_bandeja = tk.Button(ventana_principal, text="Consultar Bandeja de Entrada", command=abrir_ventana_consultar_bandeja)
boton_consultar_bandeja.pack(pady=10)
# Ejecutamos la aplicación para que se muestre la ventana
ventana_principal.mainloop()
# Ejecutanos la aplicación para que se muestre el menú de la aplicación
mostrar_menu_principal()

Powered by INFORMATICA.FP.EDU.ES.