// Activar / desactivar Acceso de aplicaciones poco seguras en Google.
// https://myaccount.google.com/lesssecureapps
using System;
using System.Collections.Generic;
using OpenPop.Pop3;
using OpenPop.Mime;
using System.Text.RegularExpressions;
using System.IO.Ports;
using System.Text;
using System.Timers;
namespace Recibir_email_enviar_arduino_01
{
class Program
{
// Disparador de eventos del timer. Dispara cada cierto tiempo por el timer.
public static void DisparadorEventosTimer(object source, ElapsedEventArgs e)
{
//ConsoleKey tecla;
string comando = "";
ConnectPop3 oC
= new ConnectPop3
();
List<OpenPop.Mime.Message> lstMessages = oC.GetMessages();
if (lstMessages != null)
{
foreach (var oMessage in lstMessages)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("EMAIL DE: ");
Console.ForegroundColor = ConsoleColor.Gray;
string emailDesde = oMessage.Headers.From.ToString();
// Expresión regular detectar dirección email.
Regex rx
= new Regex
(@"<(.*?)>"); //Regex rx = new Regex(@"^([da-z_.-]+)@([da-z.-]+).([a-z.]{2,6})$");
// Guarda la dirección email en la variable "emailCompleto".
string emailCompleto = rx.Match(emailDesde).Groups[1].Value;
// Muestra solo la dirección del email.
Console.WriteLine(emailCompleto);
// ¿Son email filtrados? Sí, ejecuta las intrucciones necesarios para leer asunto y mensajes.
if ((emailCompleto == "metaconta@gmail.com") || (emailCompleto == "celltium@gmail.com"))
{
Console.WriteLine("{0} a pasado el filtro: ", emailCompleto);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine();
Console.WriteLine("ASUNTO: ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(oMessage.Headers.Subject + "\n"); // Asunto.
comando = oMessage.Headers.Subject; // Guarda el asunto en la variable "comando".
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine();
Console.WriteLine("MENSAJE: ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine();
// ¿Es texto sin formato? Sí.
// if (oMessage.MessagePart.IsText == true)
if (oMessage.MessagePart.IsText)
{
Console.WriteLine("Texto sin formato.");
Console.WriteLine(oMessage.MessagePart.GetBodyAsText());
Console.WriteLine("-------------------------------------------");
}
// No. Texto con formato.
else
{
Console.WriteLine("Texto con formato.");
// Encuentra el primer texto sin formato.
MessagePart plainTextPart = oMessage.FindFirstPlainTextVersion();
if (plainTextPart != null)
{
// El mensaje tenía una versión de texto sin formato.
Console.WriteLine(plainTextPart.GetBodyAsText());
}
else
{
// Trate de encontrar un cuerpo para mostrar en algunas de las otras versiones de texto.
List<MessagePart> textVersions = oMessage.FindAllTextVersions();
if (textVersions.Count >= 1)
{
Console.WriteLine(textVersions[0].GetBodyAsText());
}
else
{
Console.WriteLine("<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>");
}
}
}
}
// No. Entonces,ignorará los email no filtrados.
else
{
Console.WriteLine("No ha pasado el filtro y no se leerá ningún email.");
}
}
}
Console.ForegroundColor = ConsoleColor.Yellow; // Letras amarillas.
Console.WriteLine();
Console.WriteLine("FIN DEL PROGRAMA.");
//Console.ReadKey(); // Pulse cualquier tecla para salir.
Console.ForegroundColor = ConsoleColor.Gray;
// Cree un nuevo objeto SerialPort con la configuración predeterminada.
SerialPort Puerto_serie
= new SerialPort
("COM4") {
BaudRate = 115200,
Parity = Parity.None,
StopBits = StopBits.One,
DataBits = 8,
Handshake = Handshake.None,
RtsEnable = true,
// Establecer los tiempos de espera de lectura / escritura.
ReadTimeout = 500, // Milisegundos.
WriteTimeout = 500
};
// Detecta cualquier dato recibido.
Puerto_serie
.DataReceived += new SerialDataReceivedEventHandler
(DataReceivedHandler
);
Puerto_serie.Open(); // Abrir puerto.
// ConsoleKey tecla;
Console.WriteLine("Pulse tecla 1 para encender y 2 para apagar:");
do
{
switch (comando)
{
case "Luz_ON":
EncenderLuz();
break;
case "Luz_OFF":
ApagarLuz();
break;
case "Salir":
Environment.Exit(1); // Salir de la consola.
break;
default:
Console.WriteLine("Esperando comandos válidos");
break;
}
//tecla = Console.ReadKey(true).Key; // Espera pulsación de teclas.
//switch (tecla)
//{
// case ConsoleKey.D1: // Tecla 1 del teclado estandar.
// case ConsoleKey.NumPad1: // Tecla 1 del número del pad.
// EncenderLuz();
// break;
// case ConsoleKey.D2:
// case ConsoleKey.NumPad2:
// ApagarLuz();
// break;
// default:
// Console.WriteLine("Tecla el 1, el 2 y Escape para salir.");
// break;
//}
Puerto_serie.Close(); // Cerrar puerto.
} while (comando == "salir"); // while (tecla != ConsoleKey.Escape); // Pulsa Escape para salir del menú.
void EncenderLuz()
{
byte[] miBuffer1 = Encoding.ASCII.GetBytes("Luz_ON"); // Codificación ASCII y guarda en la variable array tipo byte.
Puerto_serie.Write(miBuffer1, 0, miBuffer1.Length); // Envía los datos del buffer todo su contenido.
Console.WriteLine("Comando \"Luz_ON\" enviado."); // Muestra en pantalla comandos enviado.
}
void ApagarLuz()
{
byte[] miBuffer2 = Encoding.ASCII.GetBytes("Luz_OFF");
Puerto_serie.Write(miBuffer2, 0, miBuffer2.Length);
Console.WriteLine("Comando \"Luz_OFF\" enviado.");
}
Console.WriteLine("Presione cualquier tecla para terminar...");
Console.WriteLine();
Console.ReadKey(); // Espera pulsar una tecla cualquiera.
Puerto_serie.Close(); // Cierra el puerto serie.
}
static void Main(string[] args)
{
// Título de la ventana.
Console.Title = "Recibir e-mail con Consola C# y enviar al LCD de Arduino";
// Tamaño ventana consola.
Console.WindowWidth = 80; // X. Ancho.
Console.WindowHeight = 40; // Y. Alto.
// Cursor invisible.
Console.CursorVisible = false;
// Título del programa.
Console.WriteLine("\t-----------------------------------------------------");
Console.WriteLine("\tRecibir Correo Electrónico y enviar al LCD de Arduino");
Console.WriteLine("\t-----------------------------------------------------");
Console.WriteLine();
try
{
Timer miTimer
= new Timer
{
Enabled = true
};
miTimer
.Elapsed += new ElapsedEventHandler
(DisparadorEventosTimer
); miTimer.Interval = 5000; // Escaneo cada 5 segundos.
miTimer.Start(); // Activa el temporizador.
Console.ReadKey(); // Pulse cualquier tecla para salir.
}
// Cualquier error mostrado en mensaje y de color rojo.
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine(ex);
Console.ReadKey();
}
}
// Detecta cualquier dato entrante.
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string entradaDatos = sp.ReadExisting(); // Almacena los datos recibidos en la variable tipo string.
Console.WriteLine("Dato recibido desde Arduino: " + entradaDatos); // Muestra en pantalla los datos recibidos.
}
}
public class ConnectPop3
{
public string email = "celltium@gmail.com";
public string contraseña = "g0923490xgh0945g450Xj4025g"; // Ficticio.
public int puerto = 995;
public bool usarSLL = true;
public string Hostame = "pop.gmail.com";
public List<OpenPop.Mime.Message> GetMessages()
{
using (Pop3Client oClient
= new Pop3Client
()) {
oClient.Connect(Hostame, puerto, usarSLL);
oClient.Authenticate(email, contraseña);
int messageCount = oClient.GetMessageCount();
List
<OpenPop
.Mime.Message> lstMessages
= new List
<OpenPop
.Mime.Message>(messageCount
);
for (int i = messageCount; i > 0; i--)
{
lstMessages.Add(oClient.GetMessage(i));
}
return lstMessages;
}
}
}
}