elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  ¿Cómo enviar más de 255 letras?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: ¿Cómo enviar más de 255 letras?  (Leído 2,123 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
¿Cómo enviar más de 255 letras?
« en: 26 Diciembre 2021, 02:39 am »

Buenas:

Quiero enviar un email en modo consola que supere los 255 caracteres tal como se hace en cualquier navegador.

¿Es posible hacerlo?

Aquí dejo un ejemplo con  Ggail.
Código:
// Activar / desactivar Acceso de aplicaciones poco seguras en Google.
// https://myaccount.google.com/lesssecureapps

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace Enviar_email_Consola_07
{
    internal class Program
    {
        static void Main(string[] args)
        {
            #region Configuración ventana.
            // Título de la ventana.
            Console.Title = "Gestor correo electrónico";

            // Tamaño de la ventana, x, y.
            Console.SetWindowSize(80, 25);

            // Color de fondo.
            Console.BackgroundColor = ConsoleColor.Black;

            // Color de las letras.
            Console.ForegroundColor = ConsoleColor.Gray;

            // Limpiar pantalla y dejarlo todo en color de fondo.
            Console.Clear();

            // Visible el cursor.
            Console.CursorVisible = true;
            #endregion

            // Variables.
            string usuario, contraseña, destinatario, asunto, mensaje;

            // Título del programa.
            Console.WriteLine("\t\t----------------------------------------");
            Console.WriteLine("\t\t\tEnviar Correo Electrónico");
            Console.WriteLine("\t\t----------------------------------------");

            try
            {
                Console.WriteLine("\n");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\t\tTu correo electrónico: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                usuario = Console.ReadLine();
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\t\tIntroducir contraseña: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                contraseña = LeerPassword();
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\t\tDestinatario: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                destinatario = Console.ReadLine();
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\t\tAsunto: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                asunto = Console.ReadLine();
                Console.WriteLine();

                //----------------------------------------------
                byte[] bytes = new byte[2000]; // Nuevo tamanho máximo.
                Stream inputStream = Console.OpenStandardInput(bytes.Length);
                Console.SetIn(new StreamReader(inputStream));
                //----------------------------------------------

                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\t\tMensaje: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                mensaje = Console.ReadLine();
                Console.WriteLine();

                MailMessage correo = new MailMessage(usuario, destinatario, asunto, mensaje);

                SmtpClient servidor = new SmtpClient("smtp.gmail.com")
                {
                    Port = 587
                };
                NetworkCredential credenciales = new NetworkCredential(usuario, contraseña);
                servidor.Credentials = credenciales;
                servidor.EnableSsl = true;

                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\t\tEnviando correo...");
                servidor.Send(correo);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("\t\tCorreo enviado satisfactoriamente.");
                correo.Dispose();
                Console.CursorVisible = false;
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("ERROR: \n");
                Console.WriteLine("\t\t" + ex.Message);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\t\tNo se ha enviado el correo.");
                Console.ReadKey();
            }

        }

        // A la hora de introducir la contraseña, se sustituye por asterístos (*) en pantalla.
        public static string LeerPassword()
        {
            ConsoleKeyInfo cki;
            StringBuilder sb = new StringBuilder();
            int contador = 0;

            do
            {
                cki = Console.ReadKey(true);
                if (cki.Key != ConsoleKey.Enter)
                {

                    sb.Append(cki.KeyChar);
                    if (contador < 4)
                    {
                        Console.Write("*");
                    }
                    contador++;
                }

                else
                {
                    break;
                }

            } while (true);
            Console.WriteLine();
            return sb.ToString();
        }
    }
}

Felices fiestas camaradas.


En línea

Mohicano

Desconectado Desconectado

Mensajes: 46



Ver Perfil
Re: ¿Cómo enviar más de 255 letras?
« Respuesta #1 en: 27 Diciembre 2021, 00:04 am »

La función Console.ReadLine() tiene implícito ese límite de 256 caracteres (254 sin CarriageReturn + LineFeed). Ese es el límite del tamaño del búfer del que hace uso al adquirir el flujo de entrada estándar o std-in especificado en la función Console.OpenStandardInput.

Puedes incrementar dicho límite a 32.767(-2) caracteres de la siguiente manera:
Código
  1. Console.SetIn(new StreamReader(Console.OpenStandardInput(Int16.MaxValue), Console.InputEncoding, false, Int16.MaxValue));

O a 65.535(-2) caracteres si lo prefieres:
Código
  1. Console.SetIn(new StreamReader(Console.OpenStandardInput(UInt16.MaxValue), Console.InputEncoding, false, UInt16.MaxValue));

El límite máximo teórico es Int32.MaxValue ( Maximum length of byte[]? + <gcAllowVeryLargeObjects> element ), pero llegar a esos extremos para este tipo de escenario lo veo totalmente innecesario.

La llamada al método Console.SetIn() puedes acomodarlo de forma reutilizable como en el siguiente ejemplo de clase, y simplemente llamar al método SetInBufferSize() cuando sea necesario:

Código
  1. Public NotInheritable Class ConsoleUtil
  2.  
  3. #Region " Constructors "
  4.  
  5.    ''' ----------------------------------------------------------------------------------------------------
  6.    ''' <summary>
  7.    ''' Prevents a default instance of the <see cref="ConsoleUtil"/> class from being created.
  8.    ''' </summary>
  9.    ''' ----------------------------------------------------------------------------------------------------
  10.    <DebuggerNonUserCode>
  11.    Private Sub New()
  12.    End Sub
  13.  
  14. #End Region
  15.  
  16. #Region " Private Members "
  17.  
  18.    ''' <summary>
  19.    ''' The underlying standard input stream (stdin) used for <see cref="ConsoleUtil.SetInBufferSize"/> method.
  20.    ''' </summary>
  21.    Private Shared stdIn As StreamReader
  22.  
  23. #End Region
  24.  
  25. #Region " Public Methods "
  26.  
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    ''' <summary>
  29.    ''' Sets the buffer size of the standard input stream (std-in)
  30.    ''' acquired from the <see cref="System.Console.OpenStandardInput"/> function.
  31.    ''' <para></para>
  32.    ''' So the <see cref="Console.ReadLine()"/> function can benefit from a larger buffer size.
  33.    ''' <para></para>
  34.    ''' Default buffer size is 256.
  35.    ''' </summary>
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <param name="bufferSize">
  38.    ''' Minimum value is: 256.
  39.    ''' <para></para>
  40.    ''' Note that the last two characters in the buffer are reserved for
  41.    ''' <see cref="ControlChars.Cr"/> + <see cref="ControlChars.Lf"/>.
  42.    ''' </param>
  43.    ''' ----------------------------------------------------------------------------------------------------
  44.    <DebuggerStepThrough>
  45.    Public Shared Sub SetInBufferSize(bufferSize As Integer)
  46.        If bufferSize < 256 Then
  47.            Throw New ArgumentException(NameOf(bufferSize), message:="Value must be equal or greater than 256.")
  48.        End If
  49.  
  50.        ConsoleUtil.stdIn?.Close()
  51.        ConsoleUtil.stdIn = New StreamReader(Console.OpenStandardInput(bufferSize), Console.InputEncoding, False, bufferSize)
  52.        Console.SetIn(ConsoleUtil.stdIn)
  53.    End Sub
  54.  
  55. #End Region
  56.  
  57. End Class
  58.  
  59. #End Region

Traducción a C#:
Código
  1. public sealed class ConsoleUtil {
  2.  
  3. #region  Constructors
  4.  
  5. /// ----------------------------------------------------------------------------------------------------
  6. /// <summary>
  7. /// Prevents a default instance of the <see cref="ConsoleUtil"/> class from being created.
  8. /// </summary>
  9. /// ----------------------------------------------------------------------------------------------------
  10. [DebuggerNonUserCode]
  11. private ConsoleUtil() { }
  12.  
  13. #endregion
  14.  
  15. #region  Private Members
  16.  
  17. /// <summary>
  18. /// The underlying standard input stream (stdin) used for <see cref="ConsoleUtil.SetInputBufferSize"/> method.
  19. /// </summary>
  20. private static StreamReader stdIn;
  21.  
  22. #endregion
  23.  
  24. #region  Public Methods
  25.  
  26. /// ----------------------------------------------------------------------------------------------------
  27. /// <summary>
  28. /// Sets the buffer size of the standard input stream (std-in)
  29. /// acquired from the <see cref="System.Console.OpenStandardInput"/> function.
  30. /// <para></para>
  31. /// So the <see cref="Console.ReadLine()"/> function can benefit from a larger buffer size.
  32. /// <para></para>
  33. /// Default buffer size is 256.
  34. /// </summary>
  35. /// ----------------------------------------------------------------------------------------------------
  36. /// <param name="bufferSize">
  37. /// Minimum value is: 256.
  38. /// <para></para>
  39. /// Note that the last two characters in the buffer are reserved for
  40. /// <see cref="ControlChars.Cr"/> + <see cref="ControlChars.Lf"/>.
  41. /// </param>
  42. /// ----------------------------------------------------------------------------------------------------
  43. [DebuggerStepThrough]
  44. public static void SetInBufferSize(int bufferSize) {
  45. if (bufferSize < 256) {
  46. throw new ArgumentException(nameof(bufferSize), message:"Value must be equal or greater than 256.");
  47. }
  48.  
  49. ConsoleUtil.stdIn?.Close();
  50. ConsoleUtil.stdIn = new StreamReader(Console.OpenStandardInput(bufferSize), Console.InputEncoding, false, bufferSize);
  51. Console.SetIn(ConsoleUtil.stdIn);
  52. }
  53.  
  54. #endregion
  55.  
  56. }
  57.  
  58. #endregion
  59.  

----------------------

Como alternativa a lo de arriba, en caso de que prefieras no reemplazar el flujo de entrada estándar, puedes definir una función como esta de aquí abajo, que puedes añadir a la clase de arriba, para que sirva como reemplazo de la función Console.ReadLine().

VB.NET:
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Reads the next line of characters from the standard input stream.
  4. ''' <para></para>
  5. ''' This function attempts to be a improved replacement for <see cref="System.Console.ReadLine()"/> function.
  6. ''' </summary>
  7. ''' ----------------------------------------------------------------------------------------------------
  8. ''' <param name="bufferSize">
  9. ''' The character limit to read in the next line of characters from the standard input stream.
  10. ''' <para></para>
  11. ''' Minimum value is: 256.
  12. ''' <para></para>
  13. ''' Default value is: <see cref="Short.MaxValue"/> (32767).
  14. ''' <para></para>
  15. ''' Note that the last two characters in the buffer are reserved for
  16. ''' <see cref="ControlChars.Cr"/> + <see cref="ControlChars.Lf"/>.
  17. ''' </param>
  18. ''' ----------------------------------------------------------------------------------------------------
  19. ''' <returns>
  20. ''' The next line of characters from the input stream,
  21. ''' or <see langword="Nothing"/> if no more lines are available.
  22. ''' </returns>
  23. ''' ----------------------------------------------------------------------------------------------------
  24. <DebuggerStepThrough>
  25. Public Shared Function ReadLine(Optional bufferSize As Integer = Short.MaxValue) As String
  26.    If bufferSize < 256 Then
  27.        Throw New ArgumentException(NameOf(bufferSize), message:="Value must be equal or greater than 256.")
  28.    End If
  29.  
  30.    Dim inputStream As Stream = Console.OpenStandardInput(bufferSize)
  31.    Dim bytes(bufferSize - 1) As Byte
  32.    Dim outputLength As Integer = inputStream.Read(bytes, 0, bufferSize)
  33.    Dim chars As Char() = Console.InputEncoding.GetChars(bytes, 0, outputLength)
  34.  
  35.    Return New String(chars).TrimEnd({ControlChars.Cr, ControlChars.Lf})
  36. End Function

Traducción a C#
Código
  1. /// ----------------------------------------------------------------------------------------------------
  2. /// <summary>
  3. /// Reads the next line of characters from the standard input stream.
  4. /// <para></para>
  5. /// This function attempts to be a improved replacement for <see cref="System.Console.ReadLine()"/> function.
  6. /// </summary>
  7. /// ----------------------------------------------------------------------------------------------------
  8. /// <param name="bufferSize">
  9. /// The character limit to read in the next line of characters from the standard input stream.
  10. /// <para></para>
  11. /// Minimum value is: 256.
  12. /// <para></para>
  13. /// Default value is: <see cref="Short.MaxValue"/> (32767).
  14. /// <para></para>
  15. /// Note that the last two characters in the buffer are reserved for
  16. /// <see cref="ControlChars.Cr"/> + <see cref="ControlChars.Lf"/>.
  17. /// </param>
  18. /// ----------------------------------------------------------------------------------------------------
  19. /// <returns>
  20. /// The next line of characters from the input stream,
  21. /// or <see langword="Nothing"/> if no more lines are available.
  22. /// </returns>
  23. /// ----------------------------------------------------------------------------------------------------
  24. [DebuggerStepThrough]
  25. public static string ReadLine(int bufferSize = short.MaxValue) {
  26. if (bufferSize < 256) {
  27. throw new ArgumentException(nameof(bufferSize), message:"Value must be equal or greater than 256.");
  28. }
  29.  
  30. Stream inputStream = Console.OpenStandardInput(bufferSize);
  31. byte[] bytes = new byte[bufferSize];
  32. int outputLength = inputStream.Read(bytes, 0, bufferSize);
  33. char[] chars = Console.InputEncoding.GetChars(bytes, 0, outputLength);
  34.  
  35. return (new string(chars)).TrimEnd(new[] {'\r', '\n'});
  36. }

Modo de empleo en C#:
Código
  1. // Copy very long string to clipboard.
  2. string longString = new string('0', short.MaxValue);
  3. Clipboard.SetText(longString);
  4.  
  5. // Manually paste the string here...
  6. string line = ConsoleUtil.ReadLine(bufferSize:ushort.MaxValue);
  7.  
  8. Console.WriteLine();
  9. Console.WriteLine($"String Length: {line.Length}");
  10.  
  11. Console.WriteLine("Press any key to exit...");
  12. Console.ReadKey();
  13.  
  14. Environment.Exit(0);


« Última modificación: 27 Diciembre 2021, 02:54 am por Mohicano » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: ¿Cómo enviar más de 255 letras?
« Respuesta #2 en: 28 Diciembre 2021, 23:41 pm »

Muy buen planteamiento. Muchísimas gracias, ya me sirvió.

Dejo el código completo por si alguien lo necesita.

Funciona todo al 100 %, con tildes incluidos.
Código
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Mail;
  5. using System.Text;
  6.  
  7. namespace Enviar_email_Consola_07
  8. {
  9.    internal class Program
  10.    {
  11.        static void Main(string[] args)
  12.        {
  13.  
  14.  
  15.            // Variables.
  16.            string usuario, contraseña, destinatario, asunto, mensaje;
  17.            const int MAXIMA_LONGITUD = 2048;
  18.  
  19.            #region Configuración ventana.
  20.            // Título de la ventana.
  21.            Console.Title = "Gestor correo electrónico";
  22.  
  23.            // Tamaño de la ventana, x, y.
  24.            Console.SetWindowSize(80, 25);
  25.  
  26.            // Color de fondo.
  27.            Console.BackgroundColor = ConsoleColor.Black;
  28.  
  29.            // Color de las letras.
  30.            Console.ForegroundColor = ConsoleColor.Gray;
  31.  
  32.            // Limpiar pantalla y dejarlo todo en color de fondo.
  33.            Console.Clear();
  34.  
  35.            // Visible el cursor.
  36.            Console.CursorVisible = true;
  37.            #endregion
  38.  
  39.            // Título del programa.
  40.            Console.WriteLine("\t\t----------------------------------------");
  41.            Console.WriteLine("\t\t\tEnviar Correo Electrónico");
  42.            Console.WriteLine("\t\t----------------------------------------");
  43.  
  44.            try
  45.            {
  46.  
  47.                Console.WriteLine("\n");
  48.                Console.ForegroundColor = ConsoleColor.Cyan;
  49.                Console.Write("\t\tTu correo electrónico: ");
  50.                Console.ForegroundColor = ConsoleColor.Gray;
  51.                usuario = Console.ReadLine();
  52.                Console.WriteLine();
  53.                Console.ForegroundColor = ConsoleColor.Cyan;
  54.                Console.Write("\t\tIntroducir contraseña: ");
  55.                Console.ForegroundColor = ConsoleColor.Gray;
  56.                contraseña = LeerPassword();
  57.                Console.WriteLine();
  58.                Console.ForegroundColor = ConsoleColor.Cyan;
  59.                Console.Write("\t\tDestinatario: ");
  60.                Console.ForegroundColor = ConsoleColor.Gray;
  61.                destinatario = Console.ReadLine();
  62.                Console.WriteLine();
  63.                Console.ForegroundColor = ConsoleColor.Cyan;
  64.                Console.Write("\t\tAsunto: ");
  65.                Console.ForegroundColor = ConsoleColor.Gray;
  66.                asunto = Console.ReadLine();
  67.                Console.WriteLine();
  68.                Console.ForegroundColor = ConsoleColor.Cyan;
  69.                Console.Write("\t\tMensaje: ");
  70.                Console.ForegroundColor = ConsoleColor.Gray;
  71.                //mensaje = Console.ReadLine();
  72.  
  73.                #region Enviar más de 255 caracteres.
  74.                // Enviar mensaje de más de 255 caracteres. ################################
  75.                Stream inputStream = Console.OpenStandardInput();
  76.                byte[] buffer = new byte[MAXIMA_LONGITUD];
  77.                int numerosBytesLeidos = inputStream.Read(buffer, 0, MAXIMA_LONGITUD);
  78.                char[] chars = Console.InputEncoding.GetChars(buffer, 0, numerosBytesLeidos);
  79.                mensaje = new string(chars);
  80.                // #########################################################################
  81.                #endregion
  82.                Console.WriteLine();
  83.                Console.ForegroundColor = ConsoleColor.DarkCyan;
  84.                Console.Write("\t\tCantidad de texto introducido: ");
  85.                Console.ForegroundColor = ConsoleColor.Gray;
  86.                Console.WriteLine(mensaje.Length);                
  87.  
  88.                MailMessage correo = new MailMessage(usuario, destinatario, asunto, mensaje);
  89.  
  90.                SmtpClient servidor = new SmtpClient("smtp.gmail.com")
  91.                {
  92.                    Port = 587
  93.                };
  94.                NetworkCredential credenciales = new NetworkCredential(usuario, contraseña);
  95.                servidor.Credentials = credenciales;
  96.                servidor.EnableSsl = true;
  97.  
  98.                Console.WriteLine();
  99.                Console.ForegroundColor = ConsoleColor.Yellow;
  100.                Console.WriteLine("\t\tEnviando correo...");
  101.                servidor.Send(correo);
  102.                Console.WriteLine();
  103.                Console.ForegroundColor = ConsoleColor.Green;
  104.                Console.WriteLine("\t\tCorreo enviado satisfactoriamente.");
  105.                correo.Dispose();
  106.                Console.CursorVisible = false;
  107.                Console.ReadKey();
  108.            }
  109.            catch (Exception ex)
  110.            {
  111.                Console.ForegroundColor = ConsoleColor.Red;
  112.                Console.WriteLine("ERROR: \n");
  113.                Console.WriteLine("\t\t" + ex.Message);
  114.                Console.WriteLine();
  115.                Console.ForegroundColor = ConsoleColor.Yellow;
  116.                Console.WriteLine("\t\tNo se ha enviado el correo.");
  117.                Console.ReadKey();
  118.            }
  119.  
  120.        }
  121.  
  122.        // A la hora de introducir la contraseña, se sustituye por asterístos (*) en pantalla.
  123.        public static string LeerPassword()
  124.        {
  125.            ConsoleKeyInfo cki;
  126.            StringBuilder sb = new StringBuilder();
  127.            int contador = 0;
  128.  
  129.            do
  130.            {
  131.                cki = Console.ReadKey(true);
  132.                if (cki.Key != ConsoleKey.Enter)
  133.                {
  134.  
  135.                    sb.Append(cki.KeyChar);
  136.                    if (contador < 1)
  137.                    {
  138.                        Console.Write("*");
  139.                    }
  140.                    contador++;
  141.                }
  142.  
  143.                else
  144.                {
  145.                    break;
  146.                }
  147.  
  148.            } while (true);
  149.            Console.WriteLine();
  150.            return sb.ToString();
  151.        }
  152.    }
  153. }

Que tengan buen fin de lo que queda de año.  ;-) ;-) ;-) ;-)
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
encontrar letras diferentes, como BARBARIC
Diseño Gráfico
Erick_666 4 1,959 Último mensaje 13 Mayo 2005, 21:02 pm
por korgzak
Como pasar de letras a numeros
Programación Visual Basic
kakinets 2 2,590 Último mensaje 2 Julio 2005, 21:05 pm
por maxnet
como poner letras a un video
Multimedia
kichan 1 10,650 Último mensaje 14 Agosto 2007, 19:00 pm
por Songoku
Como hacer letras 3D???
Diseño Gráfico
peib0l 9 34,572 Último mensaje 3 Marzo 2008, 14:33 pm
por H4RR13R
Transposición de letras. ¿Como se resuelve?
Criptografía
NaDraK 7 10,529 Último mensaje 17 Noviembre 2010, 16:43 pm
por APOKLIPTICO
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines