Ejemplo n.º 1
0
        public static void SendEmail(string subject, string emailTo, string emailCC, string content)
        {
            //string smtpServer = "smtp-mail.outlook.com";
            string smtpServer = "smtp.office365.com";

            //Send teh High priority Email
            EmailManager mailMan = new EmailManager(smtpServer);

            EmailSendConfigure myConfig = new EmailSendConfigure();

            // replace with your email userName
            myConfig.ClientCredentialUserName = "******";
            // replace with your email account password
            myConfig.ClientCredentialPassword = "******";
            myConfig.TOs = new string[] { "*****@*****.**" };
            //myConfig.TOs = new string[] { emailTo };
            myConfig.CCs = new string[] { };
            //myConfig.CCs = new string[] { emailCC };
            myConfig.From            = "*****@*****.**";
            myConfig.FromDisplayName = "Pedido Click";
            myConfig.Priority        = System.Net.Mail.MailPriority.Normal;
            //myConfig.Subject = "WebSite was down - please investigate";
            myConfig.Subject = subject;

            EmailContent myContent = new EmailContent();

            //myContent.Content = "The following URLs were down - 1. Foo, 2. bar";
            myContent.Content = content;

            mailMan.SendMail(myConfig, myContent);
        }
Ejemplo n.º 2
0
            public void SendMail(EmailSendConfigure emailConfig, EmailContent content)
            {
                //Construimos el Mensaje de email para ser enviado
                MailMessage msg = ConstructEmailMessage(emailConfig, content);

                Send(msg, emailConfig);
            }
        public async void Send(string subject, string[] Tos, string[] CCs, string[] BCCs, EmailContent emailContent)
        {
            EmailSendConfigure emailConfig = await GetEmailConfig();

            EmailContent content = GetEmailContent();

            emailConfig.Subject = subject;
            emailConfig.TOs     = Tos;
            emailConfig.CCs     = CCs;
            emailConfig.BCCs    = BCCs;
            content             = emailContent;
            MailMessage msg = ConstructEmailMessage(emailConfig, content);

            await Send(msg, emailConfig);
        }
Ejemplo n.º 4
0
        static void SendEmail(string smtpServer, MemoryStream filePath)
        {
            //Creamos un objeto EmailManager con el servidor outlook
            EmailManager mailMan = new EmailManager(smtpServer);

            //Creamos una configuración de envío
            EmailSendConfigure myConfig = new EmailSendConfigure();

            // coloca tu email que funcionará como host para enviar
            myConfig.ClientCredentialUserName = "******";
            // coloca tu contraseña del correo que funcionarpa como host
            myConfig.ClientCredentialPassword = "******";

            //Configuramos los envíos "PARA" en un arreglo de string, puedes agregar N correos o generar un método que obtenga los correos Se puede enviar a diferentes dominios.
            myConfig.TOs = new string[] { "*****@*****.**", "*****@*****.**", "*****@*****.**" };

            //Puedes agregar Copias con la misma estructura
            myConfig.CCs = new string[] { };

            //Este es el correo del cual aparecerá "DE" puede ser una mascara
            myConfig.From            = "*****@*****.**";
            myConfig.FromDisplayName = "Nombre a mostrar";

            //COlocamos un orden de prioridad normal
            myConfig.Priority = MailPriority.Normal;

            //Titulo del correo
            myConfig.Subject = "Esta es una prueba de mailing";

            //Generamos un objeto de contenido de mail
            EmailContent myContent = new EmailContent();

            //Puede ser texto plano o un html
            myContent.Content = "The following URLs were down - 1. Foo, 2. bar";

            //El attachFileName puede ser un archivo con un PATH fisico o un stream, como es el caso
            myContent.AttachFileName = filePath;

            /**
             * Puedes agregar al contenido html, para eso debe asignarse IsHtml = true;
             */
            //myContent.IsHtml = true;

            //Enviamos el eMail
            mailMan.SendMail(myConfig, myContent);
        }
        /// <summary>
        /// Send the email using the SMTP server
        /// </summary>
        /// <param name="message"></param>
        /// <param name="emailConfig"></param>
        public async Task Send(MailMessage message, EmailSendConfigure emailConfig)
        {
            SmtpClient client = new SmtpClient
            {
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(
                    emailConfig.ClientCredentialUserName,
                    emailConfig.ClientCredentialPassword),
                Host      = emailConfig.SmtpServer,
                Port      = emailConfig.Port,
                EnableSsl = emailConfig.EnableSsl,
            };

            Console.WriteLine("------------------------------------ Email:" + emailConfig.FromEmail);
            Console.WriteLine("------------------------------------ ClientCredentialUserName:"******"------------------------------------ Password:"******"SmtpFailedRecipientsExceptionMessage:" + ex.Message);
                Console.WriteLine("SmtpFailedRecipientsException:" + ex.StackTrace);
                throw new Exception("SmtpFailedRecipientsException:" + ex.StackTrace);
            }
            catch (Exception e)
            {
                Console.WriteLine("ExceptionMAILMessage:" + e.Message);
                Console.WriteLine("ExceptionMAIL:" + e.StackTrace);
                throw new Exception("ExceptionMAIL:" + e.StackTrace);
            }
            finally
            {
                message.Dispose();
            }
        }
Ejemplo n.º 6
0
            // Ponemos las propiedades del email incluyendo "to", "cc", "from", "subject" y "email body"
            private MailMessage ConstructEmailMessage(EmailSendConfigure emailConfig, EmailContent content)
            {
                //Configuramos el mensaje email obteniendo los "to" y "cc"
                MailMessage msg = new MailMessage();

                foreach (string to in emailConfig.TOs)
                {
                    if (!string.IsNullOrEmpty(to))
                    {
                        msg.To.Add(to);
                    }
                }

                foreach (string cc in emailConfig.CCs)
                {
                    if (!string.IsNullOrEmpty(cc))
                    {
                        msg.CC.Add(cc);
                    }
                }

                msg.From = new MailAddress(emailConfig.From,
                                           emailConfig.FromDisplayName,
                                           Encoding.UTF8);
                msg.IsBodyHtml      = content.IsHtml;
                msg.Body            = content.Content;
                msg.Priority        = emailConfig.Priority;
                msg.Subject         = emailConfig.Subject;
                msg.BodyEncoding    = Encoding.UTF8;
                msg.SubjectEncoding = Encoding.UTF8;


                //Si no hay archivos, no se agrega ninguno.
                if (content.AttachFileName != null)
                {
                    Attachment data = new Attachment(content.AttachFileName,
                                                     MediaTypeNames.Application.Zip);
                    msg.Attachments.Add(data);
                }

                return(msg);
            }
Ejemplo n.º 7
0
        /*
         * //with sendgrid api
         * public static bool SendEmail(string subject, string message, string toemail, bool IsHTML = true)
         * {
         *
         *
         *  // Your gmail email address
         *  var FromEmail = ConfigurationManager.AppSettings["MailUser"];//"*****@*****.**";
         *  var apiKey = ConfigurationManager.AppSettings["SendGridKey"];
         *
         *
         *  try
         *  {
         *      var client = new SendGridClient(apiKey);
         *      var from = new EmailAddress(FromEmail, "SILPO - Balai Penelitian Tanah");
         *
         *      var to = new EmailAddress(toemail);
         *      var plainTextContent = message;
         *      var htmlContent = IsHTML ? message : $"<strong>{message}</strong>";
         *      var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
         *      var response = client.SendEmailAsync(msg).GetAwaiter().GetResult();
         *      return response.StatusCode == HttpStatusCode.Accepted;
         *  }
         *  catch (Exception ex)
         *  {
         *      //Console.WriteLine("failed to send email with the following error:");
         *      //Console.WriteLine(ep.Message);
         *      LogHelpers.source = typeof(EmailService).ToString();
         *      LogHelpers.message = "failed to send email with the following error:" + ex.Message;
         *      LogHelpers.user = CommonWeb.GetCurrentUser();
         *      LogHelpers.WriteLog();
         *      return false;
         *  }
         * }
         */
        /*
         * //with SMTP
         * public static bool SendEmail(string subject, string message, string toemail,bool IsHTML=true)
         * {
         *  SmtpMail oMail = new SmtpMail("TryIt");
         *  SmtpClient oSmtp = new SmtpClient();
         *
         *  // Your gmail email address
         *  oMail.From = ConfigurationManager.AppSettings["MailUser"];//"*****@*****.**";
         *
         *  // Set recipient email address
         *  oMail.To = toemail;
         *
         *  // Set email subject
         *  oMail.Subject = subject;
         *
         *  // Set email body
         *  if (IsHTML)
         *      oMail.HtmlBody = message;
         *  else
         *      oMail.TextBody = message;
         *
         *  // Gmail SMTP server address
         *  SmtpServer oServer = new SmtpServer(ConfigurationManager.AppSettings["MailServer"]);//"SMTP.Office365.com"
         *
         *  // If you want to use direct SSL 465 port,
         *  // please add this line, otherwise TLS will be used.
         *  // oServer.Port = 465;
         *
         *  // set 587 TLS port;
         *  oServer.Port = int.Parse(ConfigurationManager.AppSettings["MailPort"]); //587;
         *
         *  // detect SSL/TLS automatically
         *  oServer.ConnectType = SmtpConnectType.ConnectSTARTTLS;
         *
         *  // Gmail user authentication
         *  // For example: your email is "*****@*****.**", then the user should be the same
         *  oServer.User = ConfigurationManager.AppSettings["MailUser"];//"*****@*****.**";
         *  oServer.Password = ConfigurationManager.AppSettings["MailPassword"];//"Balittanah123";
         *
         *  try
         *  {
         *      Console.WriteLine("start to send email over SSL ...");
         *      oSmtp.SendMail(oServer, oMail);
         *      Console.WriteLine("email was sent successfully!");
         *      return true;
         *  }
         *  catch (Exception ex)
         *  {
         *      //Console.WriteLine("failed to send email with the following error:");
         *      //Console.WriteLine(ep.Message);
         *      LogHelpers.source = typeof(EmailService).ToString();
         *      LogHelpers.message = "failed to send email with the following error:"+ ex.Message;
         *      LogHelpers.user = CommonWeb.GetCurrentUser();
         *      LogHelpers.WriteLog();
         *      return false;
         *  }
         * }*/
        //using outlook without EAMail
        public static bool SendEmail(string subject, string message, string toemail, bool IsHTML = true)
        {
            string smtpServer = "smtp-mail.outlook.com";

            var UserMail     = ConfigurationManager.AppSettings["MailUser"];     //"*****@*****.**";
            var UserPassword = ConfigurationManager.AppSettings["MailPassword"]; //"Balittanah123";

            try
            {
                //Send teh High priority Email
                EmailManager mailMan = new EmailManager(smtpServer);

                EmailSendConfigure myConfig = new EmailSendConfigure();
                // replace with your email userName
                myConfig.ClientCredentialUserName = UserMail;
                // replace with your email account password
                myConfig.ClientCredentialPassword = UserPassword;
                myConfig.TOs             = new string[] { toemail };
                myConfig.CCs             = new string[] { };
                myConfig.From            = UserMail;
                myConfig.FromDisplayName = "SILPO - Balai Penelitian Tanah";
                myConfig.Priority        = System.Net.Mail.MailPriority.Normal;
                myConfig.Subject         = subject;

                EmailContent myContent = new EmailContent();
                myContent.Content = message;
                myContent.IsHtml  = IsHTML;
                mailMan.SendMail(myConfig, myContent);
                Console.WriteLine("email was sent successfully!");
                return(true);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("failed to send email with the following error:");
                //Console.WriteLine(ep.Message);
                LogHelpers.source  = typeof(EmailService).ToString();
                LogHelpers.message = "failed to send email with the following error:" + ex.Message;
                LogHelpers.user    = CommonWeb.GetCurrentUser();
                LogHelpers.WriteLog();
                return(false);
            }
        }
        /// <summary>
        /// Lấy thông tin cấu hình Email
        /// </summary>
        /// <returns></returns>
        public async Task <EmailSendConfigure> GetEmailConfig()
        {
            EmailSendConfigure emailSendConfigure = new EmailSendConfigure();
            var configuration = await this.unitOfWork.Repository <EmailConfiguration>().GetQueryable().Where(e => !e.Deleted).FirstOrDefaultAsync();

            emailSendConfigure = new EmailSendConfigure()
            {
                CCs = new string[] { },
                ClientCredentialPassword = StringCipher.Decrypt(configuration.Password, StringCipher.PassPhrase),
                ClientCredentialUserName = configuration.UserName,
                EnableSsl       = configuration.EnableSsl,
                From            = configuration.UserName,
                FromEmail       = configuration.Email,
                FromDisplayName = configuration.DisplayName,
                Port            = configuration.Port,
                Priority        = MailPriority.Normal,
                SmtpServer      = configuration.SmtpServer,
                Subject         = string.Empty,
                TOs             = new string[] { }
            };
            return(emailSendConfigure);
        }
Ejemplo n.º 9
0
    // Put the properties of the email including "to", "cc", "from", "subject" and "email body"
    private MailMessage ConstructEmailMessage(EmailSendConfigure emailConfig, EmailContent content)
    {
        MailMessage msg = new System.Net.Mail.MailMessage();

        foreach (string to in emailConfig.TOs)
        {
            if (!string.IsNullOrEmpty(to))
            {
                msg.To.Add(to);
            }
        }

        foreach (string cc in emailConfig.CCs)
        {
            if (!string.IsNullOrEmpty(cc))
            {
                msg.CC.Add(cc);
            }
        }

        msg.From = new MailAddress(emailConfig.From,
                                   emailConfig.FromDisplayName,
                                   System.Text.Encoding.UTF8);
        msg.IsBodyHtml      = content.IsHtml;
        msg.Body            = content.Content;
        msg.Priority        = emailConfig.Priority;
        msg.Subject         = emailConfig.Subject;
        msg.BodyEncoding    = System.Text.Encoding.UTF8;
        msg.SubjectEncoding = System.Text.Encoding.UTF8;

        if (content.AttachFileName != null)
        {
            Attachment data = new Attachment(content.AttachFileName,
                                             MediaTypeNames.Application.Zip);
            msg.Attachments.Add(data);
        }

        return(msg);
    }
Ejemplo n.º 10
0
            //Enviamos el mail usando SMTP
            private void Send(MailMessage message, EmailSendConfigure emailConfig)
            {
                SmtpClient client = new SmtpClient();

                client.UseDefaultCredentials = false;
                client.Credentials           = new System.Net.NetworkCredential(
                    emailConfig.ClientCredentialUserName,
                    emailConfig.ClientCredentialPassword);
                client.Host      = m_HostName;
                client.Port      = 25;   // es importante colocar el puerto
                client.EnableSsl = true; // habilitamos la seguridad SSL

                try
                {
                    client.Send(message);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error al enviar el correo: {0}", e.Message);
                    throw;
                }
                message.Dispose();
            }
Ejemplo n.º 11
0
    //Send the email using the SMTP server
    private void Send(MailMessage message, EmailSendConfigure emailConfig)
    {
        SmtpClient client = new SmtpClient();

        client.UseDefaultCredentials = false;
        client.Credentials           = new System.Net.NetworkCredential(
            emailConfig.ClientCredentialUserName,
            emailConfig.ClientCredentialPassword);
        client.Host      = m_HostName;
        client.Port      = 587;  // this is critical
        client.EnableSsl = true; // this is critical


        try
        {
            client.Send(message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error in Send email: {0}", e.Message);
            throw;
        }
        message.Dispose();
    }
        public MailMessage ConstructEmailMessage(EmailSendConfigure emailConfig, EmailContent content)
        {
            MailMessage msg = new MailMessage();

            if (emailConfig.TOs != null)
            {
                foreach (string to in emailConfig.TOs)
                {
                    if (!string.IsNullOrEmpty(to))
                    {
                        msg.To.Add(to);
                    }
                }
            }
            //Chuỗi email
            if (!string.IsNullOrEmpty(emailConfig.EmailTo))
            {
                var emailLists = emailConfig.EmailTo.Split(';');
                if (emailLists != null && emailLists.Any())
                {
                    foreach (var email in emailLists)
                    {
                        if (!string.IsNullOrEmpty(email))
                        {
                            msg.To.Add(email);
                        }
                    }
                }
            }

            if (emailConfig.CCs != null)
            {
                foreach (string cc in emailConfig.CCs)
                {
                    if (!string.IsNullOrEmpty(cc))
                    {
                        msg.CC.Add(cc);
                    }
                }
            }
            if (emailConfig.BCCs != null)
            {
                foreach (string bcc in emailConfig.BCCs)
                {
                    if (!string.IsNullOrEmpty(bcc))
                    {
                        msg.Bcc.Add(bcc);
                    }
                }
            }
            if (string.IsNullOrEmpty(emailConfig.FromEmail))
            {
                emailConfig.FromEmail = emailConfig.From;
            }
            msg.From = new MailAddress(emailConfig.FromEmail,
                                       emailConfig.FromDisplayName,
                                       Encoding.UTF8);
            msg.IsBodyHtml      = content.IsHtml;
            msg.Body            = content.Content;
            msg.Priority        = emailConfig.Priority;
            msg.Subject         = emailConfig.Subject;
            msg.BodyEncoding    = Encoding.UTF8;
            msg.SubjectEncoding = Encoding.UTF8;

            if (content.Attachments != null && content.Attachments.Count > 0)
            {
                foreach (var attachment in content.Attachments)
                {
                    msg.Attachments.Add(attachment);
                }
            }
            return(msg);
        }
Ejemplo n.º 13
0
    public void SendMail(EmailSendConfigure emailConfig, EmailContent content)
    {
        MailMessage msg = ConstructEmailMessage(emailConfig, content);

        Send(msg, emailConfig);
    }