{"id":602,"date":"2024-06-25T18:43:16","date_gmt":"2024-06-25T18:43:16","guid":{"rendered":"https:\/\/rodamoya.com\/?p=602"},"modified":"2024-06-25T19:56:41","modified_gmt":"2024-06-25T19:56:41","slug":"email-summarizer","status":"publish","type":"post","link":"https:\/\/rodamoya.com\/index.php\/2024\/06\/25\/email-summarizer\/","title":{"rendered":"Email Summarizer:"},"content":{"rendered":"\n<p>The following code is highly useful and a time-saver for those who receive numerous lengthy emails daily. It integrates the Python Gmail reader library &#8217;email&#8217; with the well-known ChatGPT model. By providing a Gmail account username and password, the code reads a specified number of emails you input and summarizes them into structured points. Originally designed for inbox emails, it can also handle emails from a designated folder, allowing you to select which ones to summarize. After defining the emails to process, the program sends them to ChatGPT for summarization. Once all emails are summarized, the code compiles a single email containing a structured summary of all processed emails, along with individual summaries in case you prefer to review the original content.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Steps:<\/h2>\n\n\n\n<ol>\n<li>Define the number of mails to read.<\/li>\n\n\n\n<li>The code will read the mails one by one following the next steps:\n<ol>\n<li>Obtain the subject and the &#8220;from&#8221; of the mail.<\/li>\n\n\n\n<li>Extracts the HTML body of the email.<\/li>\n\n\n\n<li>Converts the HTML body to plain text format.<\/li>\n\n\n\n<li>Include the email body in the prompt for ChatGPT to process<\/li>\n\n\n\n<li>Receive the structured and summarized email from ChatGPT.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li>Combines all the summarized emails.<\/li>\n\n\n\n<li>Compile and send all the summarized emails in a single mail message.<\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-video\"><video controls src=\"https:\/\/rodamoya.com\/wp-content\/uploads\/2024\/06\/Mail_sum.mp4\"><\/video><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code># Librerias Correo:\nfrom email.message import EmailMessage\nimport ssl\nimport smtplib\nimport imghdr\nimport imaplib\nimport email\nfrom email.header import decode_header\n\n# Librerias Chat GPT:\nimport openai\nimport os\n\n# Librerias leer txt HTML:\nfrom IPython.display import display, HTML\nfrom bs4 import BeautifulSoup\n\n#Hora actual para mandar correo:\nfrom datetime import datetime\n\n# Inputs:\n\n#Emisor el correo del cual se van a leer los correos\nemail_emisor = \"xxxxx@gmail.com\"\n#Contrase\u00f1a del correo del cual se van a leer los correos\ncontra_emisor = \"xwiqgqjvoydpnjhj\"\n\n#Receptor otro mail por si quieres recibir el correo resumido en otro correo:\nemail_receptor = \"xxxxx@gmail.com\"\n\n# Carga la API Key de OPEN AI:\nopenai.api_key = \"\"\n\n# Cuantos mails quieres resumir?\nnum_mails = 4\n\n# API OPEN AI:\n\n# Funci\u00f3n para interactuar con la API de OpenAI\ndef interact_with_gpt(prompt):\n    try:\n        response = openai.ChatCompletion.create(\n            model=\"gpt-3.5-turbo\",  # Modelo actualizado\n            messages=&#91;\n                {\"role\": \"user\", \"content\": prompt}\n            ],\n            max_tokens=150\n        )\n        return response.choices&#91;0].message&#91;'content'].strip()\n    except openai.error.OpenAIError as e:\n        return f\"Error al interactuar con la API de OpenAI: {e}\"\n\n\n# Enviar Mail:\n\ndef send_email(asunto, cuerpo, email_emisor, contra_emisor, email_receptor):\n    #__________________________________MENSAJE_____________________________\n    em = EmailMessage()\n    \n    # Emisor\n    em&#91;\"From\"] = email_emisor\n\n    #receeptor:\n    em&#91;\"To\"] = email_receptor\n\n    # Asunto\n    em&#91;\"Subject\"] = asunto\n    \n    #Definir correo\n    em.set_content(cuerpo)\n    contexto = ssl.create_default_context()\n    \n\n    \n    with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context = contexto) as smtp:\n        smtp.login(email_emisor, contra_emisor)\n        smtp.sendmail(email_emisor, email_receptor, em.as_string())\n\n# Read Mail:\n\n#_______________________________________________Correo_______________________________________________\ndic_correos = {}\nnum_mails = num_mails +1\n# Crear un contexto SSL\ncontext = ssl.create_default_context()\n# Conectarse al servidor\nmail = imaplib.IMAP4_SSL(\"imap.gmail.com\", port=993, ssl_context=context)\n# Iniciar sesi\u00f3n en tu cuenta\nmail.login(email_emisor, contra_emisor)\n# Seleccionar el buz\u00f3n de correo que deseas leer\nmail.select(\"inbox\")\n\n# Buscar todos los correos electr\u00f3nicos en la bandeja de entrada\nstatus, messages = mail.search(None, \"ALL\")\n\n# Convertir los mensajes a una lista de IDs de correos electr\u00f3nicos\nemail_ids = messages&#91;0].split()\n\nfor contador in range(1,num_mails):\n    # Obtener el \u00faltimo correo electr\u00f3nico\n    latest_email_id = email_ids&#91;-contador]\n\n    # Obtener el correo electr\u00f3nico por ID\n    status, msg_data = mail.fetch(latest_email_id, \"(RFC822)\")\n\n    # Obtener el contenido del correo electr\u00f3nico\n    for response_part in msg_data:\n        if isinstance(response_part, tuple):\n            msg = email.message_from_bytes(response_part&#91;1])\n            # Decodificar el asunto del correo electr\u00f3nico\n            subject, encoding = decode_header(msg&#91;\"Subject\"])&#91;0]\n            if isinstance(subject, bytes):\n                subject = subject.decode(encoding if encoding else \"utf-8\")\n            # Decodificar el remitente del correo electr\u00f3nico\n            from_ = msg.get(\"From\")\n            #print(\"Asunto:\", subject)\n            #print(\"De:\", from_)\n\n            # Si el mensaje del correo electr\u00f3nico es multipart\n            if msg.is_multipart():\n                # Iterar sobre las partes del correo electr\u00f3nico\n                for part in msg.walk():\n                    # Extraer el tipo de contenido del correo electr\u00f3nico\n                    content_type = part.get_content_type()\n                    content_disposition = str(part.get(\"Content-Disposition\"))\n\n                    try:\n                        # Obtener el cuerpo del correo electr\u00f3nico\n                        body = part.get_payload(decode=True).decode()\n                        #print(\"Cuerpo:\", body)\n                    except Exception as e:\n                        pass\n            else:\n                # Extraer el tipo de contenido del correo electr\u00f3nico\n                content_type = msg.get_content_type()\n\n                # Obtener el cuerpo del correo electr\u00f3nico\n                body = msg.get_payload(decode=True).decode()\n                #print(\"Cuerpo:\", body)\n                \n    #Leer el body en html\n    soup = BeautifulSoup(body, \"html.parser\")\n\n    # Obtener el conteido del correo a texto \n    text_content = soup.get_text()\n    \n    # Dar formato al correo para pasarlo a la API de Chat GPT:\n    Correo = \"Correo de \" + from_ + \"Asunto:\" + subject + \"Con contenido:\" + str(text_content)\n    \n    #_______________________________________________CHAT GPT_______________________________________________\n    #Promp CHAT GPT\n    promp_corre = \"Pon como titulo en mayusculas el asunto, a\u00f1adade tambien quien ha enviado el correo y con el contenido: Resume el correo usando puntos sobre los temas mas importantes: \\n\"+ '\"\"\"' + Correo + '\"\"\"' \n\n    #Preguntar CHAT GPT:\n    respuesta = interact_with_gpt(promp_corre)\n    print(respuesta)\n    dic_correos&#91;subject] = respuesta\n    \n    print(\"________________________________________________\")\n    \n    \n                \n            \n\n# Cerrar la conexi\u00f3n y cerrar sesi\u00f3n\nmail.close()\nmail.logout()\n\n# Generar el correo a enviar:\ncorreo_enviar = \"\"\nfor i in dic_correos.keys():\n    correo_enviar = correo_enviar + dic_correos&#91;i] + \"\\n\" + \"____________________________________________\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\" \n    \n# Hora actual para poner en el asunto:\nnow = datetime.now()\nhora_actual = now.strftime(\"%Y-%m-%d %H:%M\")    \n\n## Enviar el correo:\nsend_email(\"Correos resumidos por CHAT GPT \"+ hora_actual, correo_enviar, email_emisor, contra_emisor, email_receptor)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>The following code is highly useful and a time-saver for those who receive numerous lengthy emails daily. It integrates the Python Gmail reader library &#8217;email&#8217; with the well-known ChatGPT model. By providing a Gmail account username and password, the code reads a specified number of emails you input and summarizes them into structured points. Originally &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/rodamoya.com\/index.php\/2024\/06\/25\/email-summarizer\/\" class=\"more-link\">Read more<span class=\"screen-reader-text\"> &#8220;Email Summarizer:&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/posts\/602"}],"collection":[{"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/comments?post=602"}],"version-history":[{"count":4,"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/posts\/602\/revisions"}],"predecessor-version":[{"id":612,"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/posts\/602\/revisions\/612"}],"wp:attachment":[{"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/media?parent=602"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/categories?post=602"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/rodamoya.com\/index.php\/wp-json\/wp\/v2\/tags?post=602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}