diff --git a/Funciones.cs b/Funciones.cs new file mode 100644 index 0000000..bdfec82 --- /dev/null +++ b/Funciones.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Mail; +using System.Net.Mime; +using tsCorreos; +using TsCorreos; + +namespace TsCorreos +{ + + public class Funciones + { + + public static async void EnviaCorreo(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, List AttachMents = null, List AlternateViews = null, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "", bool CredencialesConDominio = false, SecurityProtocolType ProtocoloSeguridad = SecurityProtocolType.Tls, string NombreRemitente = "") + { + try + { + if (ServidorSMTP == "smtp.gmail.com") + { + var tkgm = await TokenGmail.ObtieneTokenAsync(Remitente); + await GmailOAuthSender.EnviarCorreoAsync(tkgm.Config, tkgm.Token, Destinatario, Asunto, Cuerpo, CuerpoenHTML, CC, BCC, ResponderA, AttachMents); + } + else + { + FuncionesInternas.EnviaCorreo(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, AttachMents, AlternateViews, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, CuerpoenHTML, ResponderA, CredencialesConDominio, ProtocoloSeguridad, NombreRemitente); + } + } + catch (Exception ex) + { + throw new Exception(ex.Message, ex); + } + } + public static async void EnviaCorreoAL(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, ArrayList FicherosAdjuntos = null, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, string NombreRemitente = "") + { + try + { + if (ServidorSMTP == "smtp.gmail.com") + { + var tkgm = await TokenGmail.ObtieneTokenAsync(Remitente); + await GmailOAuthSender.EnviarCorreoALAsync(tkgm.Config, tkgm.Token, Destinatario, Asunto, Cuerpo, false, CC, BCC, adjuntos: FicherosAdjuntos); + } + else + { + FuncionesInternas.EnviaCorreoAL(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, FicherosAdjuntos, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, NombreRemitente); + } + } + catch (Exception ex) + { + throw new Exception(ex.Message, ex); + } + + } + public static void EnviaCorreoCompruebaHTML(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, MemoryStream[] FicherosAdjuntos, string[] NombreFicherosAdjuntos, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "", string NombreRemitente = "") + { + try + { + if (FicherosAdjuntos.Count() == 1 && NombreFicherosAdjuntos[0].EndsWith(".html.zip")) + { + string sDirectorioTMP = tsCorreos.Utilidades.ObtieneDirectorioAleatorio(); + tsZip.Zip.ExtraeTodoDeZip(FicherosAdjuntos[0], sDirectorioTMP); + // tsZIP.zip.ExtraeTodoDeZip("f:\temp\csc.html.zip", sDirectorioTMP) + string sFichCuerpo = Directory.GetFiles(sDirectorioTMP, "*.html")[0]; + string sCuerpo = System.Text.Encoding.UTF8.GetString(File.ReadAllBytes(sFichCuerpo)); + var avHtml = AlternateView.CreateAlternateViewFromString(sCuerpo, null, MediaTypeNames.Text.Html); + string diradj = Directory.GetDirectories(sDirectorioTMP)[0]; + string[] ficadj = Directory.GetFiles(diradj); + foreach (var f in ficadj) + { + var ms = new MemoryStream(File.ReadAllBytes(f)); + var inline = new LinkedResource(ms, "image/" + Path.GetExtension(f).Trim('.')); + inline.ContentId = Path.GetFileNameWithoutExtension(f); + avHtml.LinkedResources.Add(inline); + } + var avs = new List(); + avs.Add(avHtml); + FuncionesInternas.EnviaCorreoHtml(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, null, avs, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, true, ResponderA, NombreRemitente); + Directory.Delete(sDirectorioTMP, true); + } + else + { + EnviaCorreoMS(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, FicherosAdjuntos, NombreFicherosAdjuntos, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, CuerpoenHTML, ResponderA, NombreRemitente); + } + } + catch (Exception ex) + { + throw new Exception(ex.Message, ex); + } + + } + + public static async void EnviaCorreoMS(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, MemoryStream[] FicherosAdjuntos, string[] NombreFicherosAdjuntos, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "", string NombreRemitente = "") + { + + + try + { + if (ServidorSMTP == "smtp.gmail.com") + { + var tkgm = await TokenGmail.ObtieneTokenAsync(Remitente); + await GmailOAuthSender.EnviarCorreoMSAsync(tkgm.Config, tkgm.Token, Destinatario, Asunto, Cuerpo, false, CC, BCC, FicherosAdjuntos: FicherosAdjuntos); + } + else + { + FuncionesInternas.EnviaCorreoMS(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, FicherosAdjuntos, NombreFicherosAdjuntos, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, CuerpoenHTML,ResponderA, NombreRemitente); + } + } + catch (Exception ex) + { + throw new Exception(ex.Message, ex); + } + + + } + } +} \ No newline at end of file diff --git a/FuncionesInternas.cs b/FuncionesInternas.cs new file mode 100644 index 0000000..7e9b0e1 --- /dev/null +++ b/FuncionesInternas.cs @@ -0,0 +1,821 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Mail; +using System.Net.Mime; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; + +namespace TsCorreos +{ + + internal class FuncionesInternas + { + internal static void EnviaCorreoCompruebaHTML(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, MemoryStream[] FicherosAdjuntos, string[] NombreFicherosAdjuntos, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "") + { + if (FicherosAdjuntos.Count() == 1 && NombreFicherosAdjuntos[0].EndsWith(".html.zip")) + { + string sDirectorioTMP = tsCorreos.Utilidades.ObtieneDirectorioAleatorio(); + tsZip.Zip.ExtraeTodoDeZip(FicherosAdjuntos[0], sDirectorioTMP); + // tsZIP.zip.ExtraeTodoDeZip("f:\temp\csc.html.zip", sDirectorioTMP) + string sFichCuerpo = Directory.GetFiles(sDirectorioTMP, "*.html")[0]; + string sCuerpo = System.Text.Encoding.UTF8.GetString(File.ReadAllBytes(sFichCuerpo)); + var avHtml = AlternateView.CreateAlternateViewFromString(sCuerpo, null, MediaTypeNames.Text.Html); + string diradj = Directory.GetDirectories(sDirectorioTMP)[0]; + string[] ficadj = Directory.GetFiles(diradj); + foreach (var f in ficadj) + { + var ms = new MemoryStream(File.ReadAllBytes(f)); + var inline = new LinkedResource(ms, "image/" + Path.GetExtension(f).Trim('.')); + inline.ContentId = Path.GetFileNameWithoutExtension(f); + avHtml.LinkedResources.Add(inline); + } + var avs = new List(); + avs.Add(avHtml); + EnviaCorreoHtml(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, null, avs, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, true, ResponderA); + Directory.Delete(sDirectorioTMP, true); + } + else + { + EnviaCorreoMS(ServidorSMTP, Remitente, Destinatario, Asunto, Cuerpo, FicherosAdjuntos, NombreFicherosAdjuntos, CC, BCC, CuentaCorreo, ContraseñaCorreo, Puerto, UsarSSL, CuerpoenHTML, ResponderA); + } + } + + + + internal static void EnviaCorreoHtml(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, List AttachMents, List AlternateViews, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "",string NombreRemitente="") + { + try + { + if (NombreRemitente==null) NombreRemitente=Remitente; + SmtpClient SmtpMail; + MailMessage myMessage; + + + // Si es alguna de las máquinas de desarrollo de danmun, el correo se envía solamente a danmun. Son pruebas. + if (Environment.MachineName == "WIN81PDDANMUN" || (Environment.MachineName.ToUpper() ?? "") == ("INTI81".ToUpper() ?? "") || (Environment.MachineName.ToUpper() ?? "") == ("INTI10".ToUpper() ?? "")) + { + Destinatario = "danmun@tecnosis.eu"; + } + + Asunto = Asunto.Replace(Environment.NewLine, " "); + // myMessage = New MailMessage(Remitente, Destinatario, Asunto, Cuerpo) + myMessage = new MailMessage(); + myMessage.Body = Cuerpo; + myMessage.Subject = Asunto; + string[] destinatarios = Destinatario.Split(';'); + foreach (var currentDestinatario in destinatarios) + { + Destinatario = currentDestinatario; + myMessage.To.Add(new MailAddress(Destinatario.Trim(), Destinatario.Trim())); + } + myMessage.BodyEncoding = System.Text.Encoding.Default; + if (ResponderA is null || string.IsNullOrWhiteSpace(ResponderA)) + { + myMessage.ReplyToList.Add(new MailAddress(Remitente, NombreRemitente)); + } + else + { + myMessage.ReplyToList.Add(new MailAddress(ResponderA, ResponderA)); + myMessage.ReplyToList.Add(new MailAddress(Remitente, NombreRemitente)); + } + myMessage.Sender = new MailAddress(Remitente, NombreRemitente); + myMessage.From = new MailAddress(Remitente, NombreRemitente); + myMessage.IsBodyHtml = CuerpoenHTML; + if (!string.IsNullOrEmpty(CC)) + { + foreach (var scc in CC.Split(';')) + myMessage.CC.Add(scc); + } + if (!string.IsNullOrEmpty(BCC)) + { + foreach (var sbcc in BCC.Split(';')) + myMessage.Bcc.Add(sbcc); + } + if (AttachMents != null) + { + foreach (var att in AttachMents) + myMessage.Attachments.Add(att); + } + if (AlternateViews != null) + { + foreach (var av in AlternateViews) + myMessage.AlternateViews.Add(av); + } + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(ServidorSMTP)) + SmtpMail.Host = ServidorSMTP; + SmtpMail.Port = Puerto; + if (!string.IsNullOrEmpty(CuentaCorreo)) + { + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo); + } + SmtpMail.EnableSsl = UsarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + SmtpMail.Send(myMessage); + } + + + catch (Exception myexp) + { + throw new Exception(myexp.Message, myexp); + } + } + + internal static void EnviaCorreo(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, List AttachMents, List AlternateViews, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "", bool CredencialesConDominio = false, SecurityProtocolType ProtocoloSeguridad = SecurityProtocolType.Tls, string NombreRemitente ="") + { + try + { + + SmtpClient SmtpMail; + MailMessage myMessage; + + if (string.IsNullOrEmpty(NombreRemitente)) NombreRemitente=Remitente; + if (string.IsNullOrEmpty(Destinatario) & !string.IsNullOrEmpty(CC)) + { + Destinatario = CC; + CC = ""; + } + Asunto = Asunto.Replace(Environment.NewLine, " "); + // myMessage = New MailMessage(Remitente, Destinatario, Asunto, Cuerpo) + myMessage = new MailMessage(); + myMessage.Subject = Asunto; + myMessage.Body = Cuerpo; + myMessage.From = new MailAddress(Remitente); + string[] sDestinatarios = null; + sDestinatarios = Destinatario.Split(';'); + foreach (var dest in sDestinatarios) + { + if (!string.IsNullOrEmpty(dest.Trim())) + { + myMessage.To.Add(dest.Trim()); + } + } + + myMessage.BodyEncoding = System.Text.Encoding.Default; + if (ResponderA is null || string.IsNullOrWhiteSpace(ResponderA)) + { + myMessage.ReplyToList.Add(new MailAddress(Remitente, NombreRemitente)); + } + else + { + myMessage.ReplyToList.Add(new MailAddress(ResponderA, ResponderA)); + myMessage.ReplyToList.Add(new MailAddress(Remitente, NombreRemitente)); + } + myMessage.Sender = new MailAddress(Remitente, NombreRemitente); + myMessage.From = new MailAddress(Remitente, NombreRemitente); + myMessage.IsBodyHtml = CuerpoenHTML; + + if (!string.IsNullOrEmpty(CC)) + { + string[] scc = CC.Split(';'); + foreach (var c in scc) + { + if (!string.IsNullOrEmpty(c)) + myMessage.CC.Add(c); + } + } + if (!string.IsNullOrEmpty(BCC)) + { + string[] sbcc = BCC.Split(';'); + foreach (var b in sbcc) + { + if (!string.IsNullOrEmpty(b)) + myMessage.Bcc.Add(b); + } + } + if (AttachMents != null) + { + foreach (var att in AttachMents) + myMessage.Attachments.Add(att); + } + if (AlternateViews != null) + { + foreach (var av in AlternateViews) + myMessage.AlternateViews.Add(av); + } + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(ServidorSMTP)) + SmtpMail.Host = ServidorSMTP; + SmtpMail.Port = Puerto; + if (!string.IsNullOrEmpty(CuentaCorreo)) + { + if (CredencialesConDominio) + { + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo, CuentaCorreo.Split('@')[1]); + } + else + { + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo); + } + } + SmtpMail.EnableSsl = UsarSSL; + // SmtpMail.TargetName = "STARTTLS/smtp.office365.com" + // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls OrElse SecurityProtocolType.Tls11 OrElse SecurityProtocolType.Tls12 OrElse SecurityProtocolType.Tls13 + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + // ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + ServicePointManager.ServerCertificateValidationCallback = + (sender, certificate, chain, sslPolicyErrors) => true; + SmtpMail.Send(myMessage); + } + + + catch (Exception myexp) + { + throw new Exception(myexp.Message, myexp); + } + } + + internal static void EnviaCorreoMS(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, MemoryStream[] FicherosAdjuntos, string[] NombreFicherosAdjuntos, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "", string NombreRemitente ="") + { + try + { + if (NombreRemitente == "") NombreRemitente = Remitente; + Attachment myAttch; + SmtpClient SmtpMail; + MailMessage myMessage; + int i, iCnt; + + // Si es alguna de las máquinas de desarrollo de danmun, el correo se envía solamente a danmun. Son pruebas. + if (Environment.MachineName == "WIN81PDDANMUN" || (Environment.MachineName.ToUpper() ?? "") == ("INTI81".ToUpper() ?? "") || (Environment.MachineName.ToUpper() ?? "") == ("INTI10".ToUpper() ?? "")) + { + Destinatario = "danmun@tecnosis.eu"; + } + + Asunto = Asunto.Replace(Environment.NewLine, " "); + myMessage = new MailMessage(); + + + myMessage = new MailMessage(); + myMessage.Body = Cuerpo; + myMessage.Subject = Asunto; + string[] destinatarios = Destinatario.Split(';'); + foreach (var currentDestinatario in destinatarios) + { + Destinatario = currentDestinatario; + myMessage.To.Add(new MailAddress(Destinatario.Trim(), Destinatario.Trim())); + } + + + + myMessage.BodyEncoding = System.Text.Encoding.Default; + if (ResponderA is null || string.IsNullOrWhiteSpace(ResponderA)) + { + myMessage.ReplyToList.Add(new MailAddress(Remitente, NombreRemitente)); + } + else + { + myMessage.ReplyToList.Add(new MailAddress(ResponderA, ResponderA)); + myMessage.ReplyToList.Add(new MailAddress(Remitente, NombreRemitente)); + } + myMessage.Sender = new MailAddress(Remitente, NombreRemitente); + myMessage.From = new MailAddress(Remitente, NombreRemitente); + myMessage.IsBodyHtml = CuerpoenHTML; + + if (!string.IsNullOrEmpty(CC)) + { + foreach (var scc in CC.Split(';')) + myMessage.CC.Add(scc); + } + if (!string.IsNullOrEmpty(BCC)) + { + foreach (var sbcc in BCC.Split(';')) + myMessage.Bcc.Add(sbcc); + } + if (FicherosAdjuntos != null) + { + iCnt = FicherosAdjuntos.Count() - 1; + var loopTo = iCnt; + for (i = 0; i <= loopTo; i++) + { + myAttch = new Attachment(FicherosAdjuntos[i], NombreFicherosAdjuntos[i]); + myMessage.Attachments.Add(myAttch); + } + } + + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(ServidorSMTP)) + SmtpMail.Host = ServidorSMTP; + SmtpMail.Port = Puerto; + if (!string.IsNullOrEmpty(CuentaCorreo)) + { + SmtpMail.UseDefaultCredentials = false; + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo); + } + SmtpMail.EnableSsl = UsarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + // ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + ServicePointManager.ServerCertificateValidationCallback = + (sender, certificate, chain, sslPolicyErrors) => true; + SmtpMail.Send(myMessage); + } + + + catch (Exception myexp) + { + throw new Exception(myexp.Message, myexp); + } + } + internal static void EnviaCorreo(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, List FicherosAdjuntos, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, bool CuerpoenHTML = false, string ResponderA = "") + { + try + { + Attachment myAttch; + SmtpClient SmtpMail; + MailMessage myMessage; + int i, iCnt; + + // Si es alguna de kas máquinas de desarrollo de danmun, el correo se envía solamente a danmun. Son pruebas. + // If Environment.MachineName = "WIN81PDDANMUN" OrElse Environment.MachineName.ToUpper = "INTI81".ToUpper OrElse Environment.MachineName.ToUpper = "INTI10".ToUpper Then + // Destinatario = "danmun@tecnosis.eu" + // End If + + Asunto = Asunto.Replace(Environment.NewLine, " "); + myMessage = new MailMessage(Remitente, Destinatario, Asunto, Cuerpo); + myMessage.BodyEncoding = System.Text.Encoding.Default; + if (ResponderA is null || string.IsNullOrWhiteSpace(ResponderA)) + { + myMessage.ReplyToList.Add(new MailAddress(Remitente, Remitente)); + } + else + { + myMessage.ReplyToList.Add(new MailAddress(ResponderA, ResponderA)); + myMessage.ReplyToList.Add(new MailAddress(Remitente, Remitente)); + } + myMessage.Sender = new MailAddress(Remitente, Remitente); + myMessage.From = new MailAddress(Remitente, Remitente); + + + if (!string.IsNullOrEmpty(CC)) + { + myMessage.CC.Add(CC); + } + if (!string.IsNullOrEmpty(BCC)) + { + myMessage.Bcc.Add(BCC); + } + if (FicherosAdjuntos != null) + { + iCnt = FicherosAdjuntos.Count - 1; + var loopTo = iCnt; + for (i = 0; i <= loopTo; i++) + { + if (File.Exists(FicherosAdjuntos[i])) + { + myAttch = new Attachment(FicherosAdjuntos[i]); + myMessage.Attachments.Add(myAttch); + // myAttch.Dispose() + } + } + } + + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(ServidorSMTP)) + SmtpMail.Host = ServidorSMTP; + SmtpMail.Port = Puerto; + if (!string.IsNullOrEmpty(CuentaCorreo)) + { + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo); + } + SmtpMail.EnableSsl = UsarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + SmtpMail.Send(myMessage); + } + catch (Exception e) + { + throw new Exception(e.Message, e); + } + } + + internal static void EnviaCorreo(string servidorSMTP, string remitente, List destinatarios, string asunto, string cuerpo, List ficherosAdjuntos, string cc = "", string bcc = "", string cuentaCorreo = "", string contraseñaCorreo = "", int puerto = 25, bool usarSSL = false, bool cuerpoEsHTML = false, string responderA = "") + { + try + { + Attachment myAttch; + SmtpClient SmtpMail; + MailMessage myMessage; + int i, iCnt; + + // Si es alguna de kas máquinas de desarrollo de danmun, el correo se envía solamente a danmun. Son pruebas. + // If Environment.MachineName = "WIN81PDDANMUN" OrElse Environment.MachineName.ToUpper = "INTI81".ToUpper OrElse Environment.MachineName.ToUpper = "INTI10".ToUpper Then + // Destinatario = "danmun@tecnosis.eu" + // End If + + asunto = asunto.Replace(Environment.NewLine, " "); + myMessage = new MailMessage(); + myMessage.Body = cuerpo; + myMessage.Subject = asunto; + foreach (var destinatario in destinatarios) + myMessage.To.Add(new MailAddress(destinatario, destinatario)); + + myMessage.BodyEncoding = System.Text.Encoding.Default; + if (responderA is null || string.IsNullOrWhiteSpace(responderA)) + { + myMessage.ReplyToList.Add(new MailAddress(remitente, remitente)); + } + else + { + myMessage.ReplyToList.Add(new MailAddress(responderA, responderA)); + myMessage.ReplyToList.Add(new MailAddress(remitente, remitente)); + } + myMessage.Sender = new MailAddress(remitente, remitente); + myMessage.From = new MailAddress(remitente, remitente); + + + if (!string.IsNullOrEmpty(cc)) + { + foreach (var scc in cc.Split(';')) + myMessage.CC.Add(scc); + } + if (!string.IsNullOrEmpty(bcc)) + { + foreach (var sbcc in bcc.Split(';')) + myMessage.Bcc.Add(sbcc); + } + if (ficherosAdjuntos != null) + { + iCnt = ficherosAdjuntos.Count - 1; + var loopTo = iCnt; + for (i = 0; i <= loopTo; i++) + { + if (File.Exists(ficherosAdjuntos[i])) + { + myAttch = new Attachment(ficherosAdjuntos[i]); + myMessage.Attachments.Add(myAttch); + // myAttch.Dispose() + } + } + } + + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(servidorSMTP)) + SmtpMail.Host = servidorSMTP; + SmtpMail.Port = puerto; + if (!string.IsNullOrEmpty(cuentaCorreo)) + { + SmtpMail.Credentials = new NetworkCredential(cuentaCorreo, contraseñaCorreo); + } + SmtpMail.EnableSsl = usarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + SmtpMail.Send(myMessage); + } + catch (Exception e) + { + throw new Exception(e.Message, e); + } + } + + internal static void EnviaCorreoAL(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, ArrayList FicherosAdjuntos = null, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false, string NombreRemitente="" ) + { + try + { + if (NombreRemitente == "") NombreRemitente=Remitente; + Attachment myAttch; + SmtpClient SmtpMail; + MailMessage myMessage; + int i, iCnt; + + // myMessage = New MailMessage(Remitente, Destinatario, Asunto, Cuerpo) + myMessage = new MailMessage(); + myMessage.Body = Cuerpo; + myMessage.Subject = Asunto; + string[] destinatarios = Destinatario.Split(';'); + foreach (var currentDestinatario in destinatarios) + { + Destinatario = currentDestinatario; + myMessage.To.Add(new MailAddress(Destinatario.Trim(), Destinatario.Trim())); + } + + + myMessage.BodyEncoding = System.Text.Encoding.Default; + myMessage.ReplyTo = new MailAddress(Remitente, NombreRemitente); + myMessage.Sender = new MailAddress(Remitente, NombreRemitente); + myMessage.From = new MailAddress(Remitente, NombreRemitente); + + + if (!string.IsNullOrEmpty(CC)) + { + string[] scc = CC.Split(';'); + foreach (var c in scc) + { + if (!string.IsNullOrEmpty(c)) + myMessage.CC.Add(c); + } + } + if (!string.IsNullOrEmpty(BCC)) + { + string[] sbcc = BCC.Split(';'); + foreach (var b in sbcc) + { + if (!string.IsNullOrEmpty(b)) + myMessage.Bcc.Add(b); + } + } + if (FicherosAdjuntos != null) + { + iCnt = FicherosAdjuntos.Count - 1; + var loopTo = iCnt; + for (i = 0; i <= loopTo; i++) + { + if (File.Exists(FicherosAdjuntos[i].ToString())) + { + myAttch = new Attachment(FicherosAdjuntos[i].ToString()); + myMessage.Attachments.Add(myAttch); + // myAttch.Dispose() + } + } + } + + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(ServidorSMTP)) + SmtpMail.Host = ServidorSMTP; + SmtpMail.Port = Puerto; + if (!string.IsNullOrEmpty(CuentaCorreo)) + { + // SmtpMail.UseDefaultCredentials = True + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo); + } + SmtpMail.EnableSsl = UsarSSL; + + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.ServerCertificateValidationCallback = + (sender, certificate, chain, sslPolicyErrors) => true; + + + SmtpMail.Send(myMessage); + } + catch (Exception myexp) + { + throw myexp; + } + } + + internal static void EnviaCorreoVariosAdjuntos(string ServidorSMTP, string Remitente, string Destinatario, string Asunto, string Cuerpo, List FicherosAdjuntos = null, string CC = "", string BCC = "", string CuentaCorreo = "", string ContraseñaCorreo = "", int Puerto = 25, bool UsarSSL = false) + { + try + { + Attachment myAttch; + SmtpClient SmtpMail; + MailMessage myMessage; + int i, iCnt; + + myMessage = new MailMessage(Remitente, Destinatario, Asunto, Cuerpo); + myMessage.BodyEncoding = System.Text.Encoding.Default; + myMessage.ReplyTo = new MailAddress(Remitente, Remitente); + myMessage.Sender = new MailAddress(Remitente, Remitente); + myMessage.From = new MailAddress(Remitente, Remitente); + + + if (!string.IsNullOrEmpty(CC)) + { + myMessage.CC.Add(CC); + } + if (!string.IsNullOrEmpty(BCC)) + { + myMessage.Bcc.Add(BCC); + } + ContentDisposition cd; + if (FicherosAdjuntos !=null) + { + iCnt = FicherosAdjuntos.Count - 1; + var loopTo = iCnt; + for (i = 0; i <= loopTo; i++) + { + if (!string.IsNullOrEmpty(FicherosAdjuntos[i].Ruta)) + { + if (File.Exists(FicherosAdjuntos[i].Ruta)) + { + myAttch = new Attachment(FicherosAdjuntos[i].Ruta); + cd = myAttch.ContentDisposition; + cd.FileName = FicherosAdjuntos[i].NombreFichero; + myMessage.Attachments.Add(myAttch); + } + } + else if (FicherosAdjuntos[i].Fichero != null && FicherosAdjuntos[i].Fichero.Length > 0) + { + myAttch = new Attachment(new MemoryStream(FicherosAdjuntos[i].Fichero), FicherosAdjuntos[i].NombreFichero); + cd = myAttch.ContentDisposition; + cd.FileName = FicherosAdjuntos[i].NombreFichero; + myMessage.Attachments.Add(myAttch); + + } + } + } + + SmtpMail = new SmtpClient(); + + if (!string.IsNullOrEmpty(ServidorSMTP)) + SmtpMail.Host = ServidorSMTP; + SmtpMail.Port = Puerto; + if (!string.IsNullOrEmpty(CuentaCorreo)) + { + SmtpMail.Credentials = new NetworkCredential(CuentaCorreo, ContraseñaCorreo); + } + SmtpMail.EnableSsl = UsarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + + SmtpMail.Send(myMessage); + } + catch (Exception myexp) + { + throw myexp; + } + } + + /// + /// Envía un correo electrónico. Puede recibir adjuntos mediante un Dictionary(Of String, Stream). + /// + /// + /// + /// + /// + /// + /// Un Dictionary(Of String, Stream). La clave es el nombre del archivo adjunto, el valor es el contenido del archivo adjunto en forma de Stream. + /// + /// + /// + /// + /// + /// + /// + internal static void EnviarCorreoElectrónico(string servidorSMTP, string remitente, string destinatario, string asunto, string cuerpo, Dictionary adjuntos = null, string cc = "", string bcc = "", string cuentaCorreo = "", string contraseñaCorreo = "", int puerto = 25, bool usarSSL = false, string ResponderA = "") + { + try + { + SmtpClient clienteSMTP; + MailMessage mensaje; + + // Si es alguna de las máquinas de desarrollo de danmun, el correo se envía solamente a danmun. Son pruebas. + // If Environment.MachineName = "WIN81PDDANMUN" OrElse Environment.MachineName.ToUpper = "INTI81".ToUpper OrElse Environment.MachineName.ToUpper = "INTI10".ToUpper Then + // destinatario = "danmun@tecnosis.eu" + // End If + + asunto = asunto.Replace(Environment.NewLine, " "); + mensaje = new MailMessage(remitente, destinatario, asunto, cuerpo); + mensaje.BodyEncoding = System.Text.Encoding.Default; + if (ResponderA is null || string.IsNullOrWhiteSpace(ResponderA)) + { + mensaje.ReplyToList.Add(new MailAddress(remitente, remitente)); + } + else + { + mensaje.ReplyToList.Add(new MailAddress(ResponderA, ResponderA)); + mensaje.ReplyToList.Add(new MailAddress(remitente, remitente)); + } + mensaje.Sender = new MailAddress(remitente, remitente); + mensaje.From = new MailAddress(remitente, remitente); + + + if (!string.IsNullOrEmpty(cc)) + { + mensaje.CC.Add(cc); + } + if (!string.IsNullOrEmpty(bcc)) + { + mensaje.Bcc.Add(bcc); + } + if (adjuntos != null) + { + if (adjuntos.Count > 0) + { + foreach (var adjunto in adjuntos) + mensaje.Attachments.Add(new Attachment(adjunto.Value, adjunto.Key)); + } + } + + clienteSMTP = new SmtpClient(); + + if (!string.IsNullOrEmpty(servidorSMTP)) + clienteSMTP.Host = servidorSMTP; + clienteSMTP.Port = puerto; + if (!string.IsNullOrEmpty(cuentaCorreo)) + { + clienteSMTP.Credentials = new NetworkCredential(cuentaCorreo, contraseñaCorreo); + } + clienteSMTP.EnableSsl = usarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + + clienteSMTP.Send(mensaje); + } + catch (Exception myexp) + { + throw new Exception(myexp.Message, myexp); + } + } + + internal static void EnviaCorreoMultiplesDestinatarios(string servidorSMTP, string remitente, List listaDestinatarios, string asunto, string cuerpo, List ficherosAdjuntos, string CC = "", string BCC = "", string cuentaCorreo = "", string contraseñaCorreo = "", int puerto = 25, bool usarSSL = false, string responderA = "") + { + try + { + Attachment misAdjuntos; + SmtpClient clienteSMTP; + MailMessage miMensaje; + int i, iCnt; + + // // Si es alguna de kas máquinas de desarrollo de danmun, el correo se envía solamente a danmun. Son pruebas. + // If Environment.MachineName = "WINXP-PARALLELS" OrElse + // Environment.MachineName = "WINXP-DE-DANIEL" OrElse + // Environment.MachineName.ToUpper = "Win81PDdanmun".ToUpper OrElse + // Environment.MachineName.ToUpper.StartsWith("INTI") Then + // listaDestinatarios = New List(Of String) + // listaDestinatarios.Add("danmun@tecnosis.net") + // End If + + foreach (var destinatario in listaDestinatarios) + { + asunto = asunto.Replace(Environment.NewLine, " "); + miMensaje = new MailMessage(new MailAddress(remitente, remitente), new MailAddress(destinatario, destinatario)) + { + Subject = asunto, + Body = cuerpo, + BodyEncoding = System.Text.Encoding.UTF8 + }; + if (responderA is null || string.IsNullOrWhiteSpace(responderA)) + { + miMensaje.ReplyToList.Add(new MailAddress(remitente, remitente)); + } + else + { + miMensaje.ReplyToList.Add(new MailAddress(responderA, responderA)); + miMensaje.ReplyToList.Add(new MailAddress(remitente, remitente)); + } + miMensaje.Sender = new MailAddress(remitente, remitente); + + + if (!string.IsNullOrEmpty(CC)) + { + miMensaje.CC.Add(CC); + } + if (!string.IsNullOrEmpty(BCC)) + { + miMensaje.Bcc.Add(BCC); + } + if (ficherosAdjuntos != null) + { + iCnt = ficherosAdjuntos.Count - 1; + var loopTo = iCnt; + for (i = 0; i <= loopTo; i++) + { + if (File.Exists(ficherosAdjuntos[i])) + { + misAdjuntos = new Attachment(ficherosAdjuntos[i]); + miMensaje.Attachments.Add(misAdjuntos); + // misAdjuntos.Dispose() + } + } + } + + clienteSMTP = new SmtpClient(); + + if (!string.IsNullOrEmpty(servidorSMTP)) + clienteSMTP.Host = servidorSMTP; + clienteSMTP.Port = puerto; + if (!string.IsNullOrEmpty(cuentaCorreo)) + { + clienteSMTP.Credentials = new NetworkCredential(cuentaCorreo, contraseñaCorreo); + } + clienteSMTP.EnableSsl = usarSSL; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + clienteSMTP.Send(miMensaje); + System.Threading.Thread.Sleep(1000 * (listaDestinatarios.Count - 1)); + } + } + catch (Exception e) + { + throw new Exception(e.Message, e); + } + } + } + + public class FicheroAdjunto + { + public string Ruta { get; set; } + public string NombreFichero { get; set; } + public byte[] Fichero { get; set; } + } +} \ No newline at end of file diff --git a/TokenGmail.cs b/TokenGmail.cs new file mode 100644 index 0000000..cf21239 --- /dev/null +++ b/TokenGmail.cs @@ -0,0 +1,44 @@ +using Newtonsoft.Json.Linq; +using Org.BouncyCastle.Asn1; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace tsCorreos +{ + public class TokenGmail + { + private string _id; + public string id + { + get { return _id; } + set { _id = value; } + } + DateTime? UltimaUtilizacion; + public string Token {get;set;} + private GmailConfig _Config; + public GmailConfig Config + { + get { return _Config; } + set { _Config = value; } + + } + public static List ListaTokens; + public static async Task ObtieneTokenAsync(string id) + { + if (ListaTokens ==null) throw new Exception("No se ha establecido la lista de tokens para poder enviar correos con Gmail"); + var tk= ListaTokens.First(x=>x.id==id); + if (tk == null) throw new Exception("No se ha encontrado la configuración para la cuenta " + id); + + if (!tk.UltimaUtilizacion.HasValue || DateTime.UtcNow.Subtract(tk.UltimaUtilizacion.Value).TotalMinutes > 0) + { + tk.Token = await GmailTokenManager.ObtenerAccessTokenAsync(tk.Config); + tk.UltimaUtilizacion = DateTime.UtcNow; + } + return tk; + } + } + +} diff --git a/Utilidades.cs b/Utilidades.cs new file mode 100644 index 0000000..010b213 --- /dev/null +++ b/Utilidades.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace tsCorreos +{ + internal class Utilidades + { + public static string ObtieneDirectorioAleatorio() + { + string sDir = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName(); + + while (System.IO.Directory.Exists(sDir)) + { + sDir = System.IO.Path.GetTempPath() + "\\" + System.IO.Path.GetRandomFileName(); + } + + System.IO.Directory.CreateDirectory(sDir); + return sDir; + } + } +} diff --git a/tsCorreos.csproj b/tsCorreos.csproj new file mode 100644 index 0000000..8311e38 --- /dev/null +++ b/tsCorreos.csproj @@ -0,0 +1,24 @@ + + + + Library + tsCorreos + netstandard2.0 + tsCorreos + netstandard2.0, libreria + 1.0.0 + Manuel + Tecnosis S.A + Envío de correos diferenciando Gmail del resto + + - 2025-09-18 Primera versión + + + + + + + + + + diff --git a/tsCorreos.sln b/tsCorreos.sln new file mode 100644 index 0000000..c28b6a3 --- /dev/null +++ b/tsCorreos.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36511.14 d17.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tsCorreos", "tsCorreos.csproj", "{755D1138-364A-4D7B-AE31-AE66B629F9C4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {755D1138-364A-4D7B-AE31-AE66B629F9C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {755D1138-364A-4D7B-AE31-AE66B629F9C4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {755D1138-364A-4D7B-AE31-AE66B629F9C4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {755D1138-364A-4D7B-AE31-AE66B629F9C4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2D880A2C-DB68-46CF-9084-3ECCCF6B9D78} + EndGlobalSection +EndGlobal