Beispiel #1
0
        /// <summary>
        /// send email
        /// </summary>
        /// <param name="fromAddress"></param>
        /// <param name="toAddress"></param>
        /// <param name="mainBody"></param>
        /// <param name="subject"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool SendEmail(MailAddress fromAddress, MailAddress toAddress, string mainBody, string subject)
        {
            try {
                //create email message
                DeliveryNotificationOptions  DeliveryOptions = DeliveryNotificationOptions.OnFailure;
                System.Net.Mail.MailPriority Priority        = MailPriority.Normal;

                string      Attachfile = null;
                MailAddress bcc        = null;
                MailAddress CC         = null;

                //add header (greetings) to body
                dynamic Body = "<p></p>Dear " + toAddress.DisplayName.ToUpperInvariant() + "," + "<p></p>" + mainBody;
                //add footer to body
                Body = Body + "<p></p><br /><br />Kind Regards," + "<p></p><br />" + fromAddress.DisplayName.ToUpperInvariant();


                return(SendMail.Send(Body, subject, DeliveryOptions, Priority, toAddress, fromAddress, Attachfile, bcc, CC));
            }
            catch (Exception ex) {
                //do nothing if there is an exception logging an exception - really bad!
                System.Diagnostics.Debug.Print("Error in sending email exception " + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Message);
                ExceptionHandling.LogException(ref ex);
                //UtilsShared.LogException(ex3);
                return(false);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Executes the logic for this workflow activity
        /// </summary>
        protected override void InternalExecute()
        {
            // Initialise defaults
            if (this.UseDefaultCredentials.Expression == null)
            {
                this.UseDefaultCredentials.Set(this.ActivityContext, true);
            }

            if (this.Format.Expression == null)
            {
                this.Format.Set(this.ActivityContext, "HTML");
            }

            if (!string.IsNullOrEmpty(this.Priority.Get(this.ActivityContext)))
            {
                this.priority = (System.Net.Mail.MailPriority)Enum.Parse(typeof(System.Net.Mail.MailPriority), this.Priority.Get(this.ActivityContext));
            }

            switch (this.Action)
            {
            case EmailAction.Send:
                this.Send();
                break;

            default:
                throw new ArgumentException("Action not supported");
            }
        }
        public static void SendMail(string from, string to, string cc, string bcc, System.Net.Mail.MailPriority priority, string subject, string body, bool bodyFormat, System.Text.Encoding bodyEncoding, string[] AttachedfilesNames)
        {
            MailMessage objMail;
            SmtpClient  objSmtpClient = null;

            to      = to.Replace(";", ",");
            objMail = new MailMessage();
            body    = body.Replace("[LINK]", ConfigurationManager.AppSettings["WETOS_Link"].ToString());
            objMail.To.Add(to);
            objMail.To.Add(from);

            objMail.From = new MailAddress(ConfigurationManager.AppSettings["SMTPUsername"]);
            if (!String.IsNullOrEmpty(cc))
            {
                objMail.CC.Add(cc);
            }
            if (!String.IsNullOrEmpty(bcc))
            {
                objMail.Bcc.Add(bcc);
            }
            objMail.Priority     = MailPriority.High;
            objMail.Subject      = subject;
            objMail.IsBodyHtml   = bodyFormat;
            objMail.BodyEncoding = bodyEncoding;
            objMail.Body         = body;
            if (AttachedfilesNames != null && AttachedfilesNames.Length > 0)
            {
                for (int i = 0; i < AttachedfilesNames.Length; i++)
                {
                    objMail.Attachments.Add(new Attachment(AttachedfilesNames[i]));
                }
            }
            objSmtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServerName"]);
            //objSmtpClient = new SmtpClient("67.212.165.234");
            objSmtpClient.UseDefaultCredentials = false;

            //NetworkCredential credential = new NetworkCredential("*****@*****.**", "Sharad");
            objSmtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["SMTPUsername"], ConfigurationManager.AppSettings["SMTPPassword"]);
            try
            {
                objSmtpClient.Send(objMail);
            }
            catch (SmtpException ex)
            {
                throw ex;
            }
        }
Beispiel #4
0
        /// <summary>
        /// Executes the logic for this workflow activity
        /// </summary>
        protected override void InternalExecute()
        {
            // Initialise defaults
            if (this.UseDefaultCredentials.Expression == null)
            {
                this.UseDefaultCredentials.Set(this.ActivityContext, true);
            }

            if (this.Format.Expression == null)
            {
                this.Format.Set(this.ActivityContext, "HTML");
            }

            if (!string.IsNullOrEmpty(this.Priority.Get(this.ActivityContext)))
            {
                this.priority = (System.Net.Mail.MailPriority)Enum.Parse(typeof(System.Net.Mail.MailPriority), this.Priority.Get(this.ActivityContext));
            }

            switch (this.Action)
            {
                case EmailAction.Send:
                    this.Send();
                    break;
                default:
                    throw new ArgumentException("Action not supported");
            }
        }
Beispiel #5
0
        private async Task <string> SendMailAsync(bool SendAsync, string MailFrom, string MailTo, string MailToDisplayName, string Cc, string Bcc, string ReplyTo, System.Net.Mail.MailPriority Priority,
                                                  string Subject, Encoding BodyEncoding, string Body, string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL)
        {
            string          strSendMail     = "";
            GeneralSettings GeneralSettings = await _generalSettingsService.GetGeneralSettingsAsync();

            // SMTP server configuration
            if (SMTPServer == "")
            {
                SMTPServer = GeneralSettings.SMTPServer;

                if (SMTPServer.Trim().Length == 0)
                {
                    return("Error: Cannot send email - SMTPServer not set");
                }
            }

            if (SMTPAuthentication == "")
            {
                SMTPAuthentication = GeneralSettings.SMTPAuthendication;
            }

            if (SMTPUsername == "")
            {
                SMTPUsername = GeneralSettings.SMTPUserName;
            }

            if (SMTPPassword == "")
            {
                SMTPPassword = GeneralSettings.SMTPPassword;
            }

            MailTo = MailTo.Replace(";", ",");
            Cc     = Cc.Replace(";", ",");
            Bcc    = Bcc.Replace(";", ",");

            System.Net.Mail.MailMessage objMail = null;
            try
            {
                System.Net.Mail.MailAddress SenderMailAddress    = new System.Net.Mail.MailAddress(MailFrom, MailFrom);
                System.Net.Mail.MailAddress RecipientMailAddress = new System.Net.Mail.MailAddress(MailTo, MailToDisplayName);

                objMail = new System.Net.Mail.MailMessage(SenderMailAddress, RecipientMailAddress);

                if (Cc != "")
                {
                    objMail.CC.Add(Cc);
                }
                if (Bcc != "")
                {
                    objMail.Bcc.Add(Bcc);
                }

                if (ReplyTo != string.Empty)
                {
                    objMail.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo));
                }

                objMail.Priority   = (System.Net.Mail.MailPriority)Priority;
                objMail.IsBodyHtml = IsHTMLMail(Body);

                foreach (string myAtt in Attachment)
                {
                    if (myAtt != "")
                    {
                        objMail.Attachments.Add(new System.Net.Mail.Attachment(myAtt));
                    }
                }

                // message
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject         = Subject.Trim();
                objMail.BodyEncoding    = BodyEncoding;

                System.Net.Mail.AlternateView PlainView =
                    System.Net.Mail.AlternateView.CreateAlternateViewFromString(Utility.ConvertToText(Body),
                                                                                null, "text/plain");

                objMail.AlternateViews.Add(PlainView);

                //if body contains html, add html part
                if (IsHTMLMail(Body))
                {
                    System.Net.Mail.AlternateView HTMLView =
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

                    objMail.AlternateViews.Add(HTMLView);
                }
            }
            catch (Exception objException)
            {
                // Problem creating Mail Object
                strSendMail = MailTo + ": " + objException.Message;

                // Log Error
                BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs();
                objLog.LogDate      = DateTime.Now;
                objLog.LogAction    = $"{Constants.EmailError} - Error: {strSendMail}";
                objLog.LogUserName  = MailTo;
                objLog.LogIpaddress = "127.0.0.1";
            }

            if (objMail != null)
            {
                // external SMTP server alternate port
                int?SmtpPort = null;
                int portPos  = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort   = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                if (SMTPServer != "")
                {
                    smtpClient.Host = SMTPServer;
                    smtpClient.Port = (SmtpPort == null) ? (int)25 : (Convert.ToInt32(SmtpPort));

                    switch (SMTPAuthentication)
                    {
                    case "":
                    case "0":
                        // anonymous
                        break;

                    case "1":
                        // basic
                        if (SMTPUsername != "" & SMTPPassword != "")
                        {
                            smtpClient.UseDefaultCredentials = false;
                            smtpClient.Credentials           = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
                        }

                        break;

                    case "2":
                        // NTLM
                        smtpClient.UseDefaultCredentials = true;
                        break;
                    }
                }
                smtpClient.EnableSsl = SMTPEnableSSL;

                try
                {
                    if (SendAsync) // Send Email using SendAsync
                    {
                        // Set the method that is called back when the send operation ends.
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;

                        // Send the email
                        MailMessage objMailMessage = new MailMessage();
                        objMailMessage = objMail;

                        smtpClient.SendAsync(objMail, objMailMessage);
                        strSendMail = "";
                    }
                    else // Send email and wait for response
                    {
                        smtpClient.Send(objMail);
                        strSendMail = "";

                        // Log the Email
                        LogEmail(objMail);

                        objMail.Dispose();
                        smtpClient.Dispose();
                    }
                }
                catch (Exception objException)
                {
                    // mail configuration problem
                    if (!(objException.InnerException == null))
                    {
                        strSendMail = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message);
                    }
                    else
                    {
                        strSendMail = objException.Message;
                    }

                    // Log Error
                    BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs();
                    objLog.LogDate      = DateTime.Now;
                    objLog.LogAction    = $"{Constants.EmailError} - Error: {strSendMail}";
                    objLog.LogUserName  = null;
                    objLog.LogIpaddress = "127.0.0.1";

                    _context.Logs.Add(objLog);
                    _context.SaveChanges();
                }
            }

            return(strSendMail);
        }
Beispiel #6
0
        /// <summary>
        /// Método que envia email
        /// </summary>
        /// <param name="emailFrom">Email From</param>
        /// <param name="emailTo">Email To</param>
        /// <param name="emailCopy">Email a ser copiado (CC)</param>
        /// <param name="body">Corpo do email</param>
        /// <param name="subject">Assunto do email</param>
        /// <param name="FormatoHTML">Se é no formato HTML</param>
        /// <param name="prioridade">Prioridade do email</param>
        public static void SendNetEmailWithCopy(string emailFrom, string emailTo, string emailCopy, string body, string subject, bool FormatoHTML, System.Net.Mail.MailPriority prioridade)
        {
            try
            {
                System.Net.Mail.MailMessage mensagem = new System.Net.Mail.MailMessage();

                //======================================================
                //ATENÇÃO PARA NÃO ESQUECER DE TROCAR AS LINHAS ABAIXO
                //======================================================

                //Usar esse bloco para testes
                //mensagem.From = new MailAddress("*****@*****.**");
                //mensagem.To.Add(new MailAddress("*****@*****.**"));

                //Usar esse bloco para produção
                mensagem.From = new MailAddress("*****@*****.**");
                mensagem.To.Add(new MailAddress(emailTo));

                if (emailCopy != string.Empty)
                {
                    mensagem.CC.Add(new MailAddress(emailCopy));
                }

                //======================================================

                mensagem.ReplyToList.Add(new MailAddress("*****@*****.**"));
                mensagem.Body            = body;
                mensagem.Subject         = subject;
                mensagem.IsBodyHtml      = FormatoHTML;
                mensagem.SubjectEncoding = System.Text.Encoding.UTF8;
                mensagem.BodyEncoding    = System.Text.Encoding.UTF8;
                mensagem.Priority        = prioridade;

                if (ConfigurationManager.AppSettings["local"] == "Des")
                {
                    SmtpClient cliente = new SmtpClient(ConfigurationManager.AppSettings["SMTP"].ToString());

                    NetworkCredential credenciais = new NetworkCredential(ConfigurationManager.AppSettings["EmailFaleConosco"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
                    cliente.Credentials = credenciais;
                    cliente.Port        = Convert.ToInt16(ConfigurationManager.AppSettings["Porta"]);
                    cliente.EnableSsl   = true;

                    //Defino o timeout máximo em 10 minutos para envio do email
                    cliente.Timeout = 600000;

                    cliente.Send(mensagem);
                }
                else
                {
                    SmtpClient smtp = new SmtpClient
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Port           = 25,
                        Host           = ConfigurationManager.AppSettings["SMTP"].ToString()
                    };
                    smtp.Send(mensagem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #7
0
        ///// <summary>
        ///// Método de envio de email no padrão anterior, usado para poder
        ///// se compativel com o servidor smtp antigo
        ///// </summary>
        ///// <param name="emailTo"></param>
        ///// <param name="body"></param>
        ///// <param name="subject"></param>
        //public static void SendWebEmail(string emailTo, string body, string subject)
        //{
        //    try
        //    {
        //        System.Web.Mail.MailMessage mensagem = new System.Web.Mail.MailMessage();
        //        mensagem.To = emailTo;
        //        mensagem.From = ConfigurationManager.AppSettings["EmailComercial"].ToString();
        //        mensagem.Subject = subject;
        //        mensagem.BodyFormat = MailFormat.Html;
        //        mensagem.Body = body;
        //        mensagem.Priority = System.Web.Mail.MailPriority.High;
        //        mensagem.BodyEncoding = System.Text.Encoding.UTF8;

        //        SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SMTP"].ToString();
        //        SmtpMail.Send(mensagem);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// Método de envio de email no padrão anterior, usado para poder
        /// se compativel com o servidor smtp do radar55
        /// </summary>
        /// <param name="emailTo"></param>
        /// <param name="body"></param>
        /// <param name="subject"></param>
        public static void SendNetEmail(string emailFrom, string emailTo, string emailReply, string body, string subject, bool FormatoHTML, System.Net.Mail.MailPriority prioridade)
        {
            try
            {
                MailMessage mensagem = new MailMessage();

                //======================================================
                //ATENÇÃO PARA NÃO ESQUECER DE TROCAR AS LINHAS ABAIXO
                //======================================================

                //Usar esse bloco para testes
                //mensagem.From = new MailAddress("*****@*****.**");
                //mensagem.To.Add(new MailAddress("*****@*****.**"));

                //Usar esse bloco para produção
                mensagem.From = new MailAddress(emailFrom);
                mensagem.To.Add(new MailAddress(emailTo));

                if (emailReply != string.Empty)
                {
                    mensagem.ReplyToList.Add(new MailAddress(emailReply));
                }

                //======================================================

                mensagem.Body            = body;
                mensagem.Subject         = subject;
                mensagem.IsBodyHtml      = FormatoHTML;
                mensagem.SubjectEncoding = Encoding.UTF8;
                mensagem.BodyEncoding    = Encoding.UTF8;
                mensagem.Priority        = prioridade;

                if (ConfigurationManager.AppSettings["local"] == "Des")
                {
                    SmtpClient cliente = new SmtpClient(ConfigurationManager.AppSettings["SMTP"].ToString());

                    NetworkCredential credenciais = new NetworkCredential(ConfigurationManager.AppSettings["EmailSuporte"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
                    cliente.Credentials = credenciais;
                    cliente.Port        = Convert.ToInt16(ConfigurationManager.AppSettings["Porta"]);
                    cliente.EnableSsl   = true;

                    ServicePointManager.ServerCertificateValidationCallback = delegate(object s,
                                                                                       System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                                                                       System.Security.Cryptography.X509Certificates.X509Chain chain,
                                                                                       System.Net.Security.SslPolicyErrors sslPolicyErrors)
                    {
                        return(true);
                    };

                    //Defino o timeout máximo em 10 minutos para envio do email
                    cliente.Timeout = 600000;

                    cliente.Send(mensagem);
                }
                else
                {
                    SmtpClient smtp = new SmtpClient();
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.Port           = 25;
                    smtp.Host           = ConfigurationManager.AppSettings["SMTP"].ToString();
                    smtp.Send(mensagem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool SendMail(string To, string ToCc, string ToBcc, string displayName
                             , string subject, string body, string attachFiles, bool IsBodyHtml, System.Net.Mail.MailPriority priority)
        {
            if (To.Length == 0 && ToCc.Length == 0 && ToBcc.Length == 0)
            {
                //errorMessage = "Missing \"To\" address.";
                return(false);
            }

            //errorMessage = "";
            bool        flag = true;
            MailMessage mail = new MailMessage();

            mail.IsBodyHtml   = IsBodyHtml;
            mail.BodyEncoding = Encoding.UTF8;
            mail.Priority     = priority;
            mail.Body         = body;

            if (!string.IsNullOrEmpty(ToCc))
            {
                foreach (string s in ToCc.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    mail.CC.Add(s);
                }
            }

            if (!string.IsNullOrEmpty(ToBcc))
            {
                foreach (string s in ToBcc.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    mail.Bcc.Add(s);
                }
            }
            if (!string.IsNullOrEmpty(To))
            {
                foreach (string s in To.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    mail.To.Add(s);
                }
            }

            if (!string.IsNullOrEmpty(To))
            {
                if (Config.IsTest && Config.TestMails != null && Config.TestMails.Trim().Length > 0)
                {
                    body = string.Format("{0}\r\n This is an email send from test website,it's really send to {1},bcc {2},cc{3}\r\n",
                                         body,
                                         string.Join(",", mail.To.Select(x => x.Address).ToArray()),
                                         string.Join(",", mail.CC.Select(x => x.Address).ToArray()),
                                         string.Join(",", mail.Bcc.Select(x => x.Address).ToArray()));
                    mail.Body = body;
                    mail.To.Clear();
                    var testReceivers = Config.TestMails.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s in testReceivers)
                    {
                        mail.To.Add(s);
                    }
                    mail.CC.Clear();
                    mail.Bcc.Clear();
                }
            }
            //mail.From = new MailAddress(from, displayName);
            if (string.IsNullOrEmpty(displayName))
            {
                if (!string.IsNullOrEmpty(SFConfig.EmailDisplayName))
                {
                    displayName = SFConfig.EmailDisplayName;
                }
            }
            mail.From    = new MailAddress(SF.Framework.SFConfig.FromEmailAddress, displayName);
            mail.Subject = subject;
            if (!string.IsNullOrEmpty(attachFiles))
            {
                foreach (string s in attachFiles.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    Attachment attach = new Attachment(s);
                    mail.Attachments.Add(attach);
                }
            }
            SmtpClient client = new SmtpClient();

            client.EnableSsl = SFConfig.EnableSSL;
            try
            {
                client.Send(mail);
            }
            catch (Exception ex)
            {
                flag = false;
            }
            finally
            {
                logger.Log(body);
                mail.Dispose();
            }
            return(flag);
        }
Beispiel #9
0
/// <summary>
/// 發郵件函數
/// </summary>
/// <param name="strSubject">主題</param>
/// <param name="strFrom">發件人</param>
/// <param name="strTo">收件人</param>
/// <param name="strCc">CC</param>
/// <param name="strBcc">BCC</param>
/// <param name="strBody">主題</param>
/// <param name="MailPriority">郵件重要性</param>
    public static void SendMail(string strSubject, string strFrom, string strTo, string strCc, string strBcc, string strBody, System.Net.Mail.MailPriority MailPriority)
    {
        string mailserver = ConfigurationManager.AppSettings["mailserver"];
        string teststatus = ConfigurationManager.AppSettings["test"];
        string testmail   = ConfigurationManager.AppSettings["testmail"].Trim();

        if (teststatus == "1")
        {
            strBody += "\r\n*" + strTo + "&" + strCc;
            strTo    = testmail;
            strCc    = testmail;
            strBcc   = "";
        }

        MailMessage clsMailSvc;

        clsMailSvc = new MailMessage( );

        clsMailSvc.From = new MailAddress(strFrom);
        if (strTo != "")
        {
            string [] str = strTo.Split(';');
            for (int i = 0; i < str.Length; i++)
            {
                if (str.GetValue(i).ToString( ) != null && str.GetValue(i).ToString( ).Trim( ) != "")
                {
                    clsMailSvc.To.Add(new MailAddress(str.GetValue(i).ToString( )));
                }
            }
        }
        clsMailSvc.Subject = strSubject;
        if (strCc != "")
        {
            string [] str = strCc.Split(';');
            for (int i = 0; i < str.Length; i++)
            {//"The hash code for \"{0}\" is: 0x{1:X8}, {1}"
                if (str.GetValue(i).ToString( ) != null && str.GetValue(i).ToString( ).Trim( ) != "")
                {
                    clsMailSvc.CC.Add(new MailAddress(str.GetValue(i).ToString( )));
                }
            }
        }
        if (strBcc != "")
        {
            string [] str = strBcc.Split(';');
            for (int i = 0; i < str.Length; i++)
            {
                if (str.GetValue(i).ToString( ) != null && str.GetValue(i).ToString( ).Trim( ) != "")
                {
                    clsMailSvc.CC.Add(new MailAddress(str.GetValue(i).ToString( )));
                }
            }
        }
        clsMailSvc.Body         = strBody;
        clsMailSvc.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
        clsMailSvc.IsBodyHtml   = true;
        clsMailSvc.Priority     = MailPriority;


        System.Net.Mail.SmtpClient clsSmtpClient = new SmtpClient(mailserver);
        try
        {
            clsSmtpClient.Send(clsMailSvc);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Beispiel #10
0
 /// <summary>
 /// Send an e-mail within VIE Portal software using System.Net.Mail namespace.
 /// </summary>
 /// <param name="from">Sender name and e-mail address.</param>
 /// <param name="replyTo">Address will be replied to.</param>
 /// <param name="to">Recipients. Seperate multiple by comma (,).</param>
 /// <param name="cc">CC recipients. Seperate multiple by comma (,).</param>
 /// <param name="bcc">BCC recipients. Seperate multiple by comma (,).</param>
 /// <param name="subject">Mail subject.</param>
 /// <param name="body">Mail body.</param>
 /// <param name="attachment">Path to attachment file.</param>
 /// <param name="priority">Priority. See <c>System.Net.Mail.MailPriority</c> class for more information.</param>
 /// <param name="isHtmlFormat">TRUE if the message body is HTML formated.</param>
 /// <param name="encoding">Encoding of body message. See <c>System.Web.Mail.MailEncoding</c> class for more information.</param>
 /// <param name="smtpServer">IP address or host name of SMTP server.</param>
 /// <param name="smtpServerPort">Port number for SMTP service on the SMTP server.</param>
 /// <param name="smtpUsername">Username of the SMTP server use for sending mail.</param>
 /// <param name="smtpPassword">Password of user on the SMTP server use for sending mail.</param>
 /// <param name="smtpEnableSsl">TRUE if the SMTP server requires SSL.</param>
 /// <param name="cancellationToken">Token for cancelling this task.</param>
 public static Task SendMailAsync(string from, string replyTo, string to, string cc, string bcc, string subject, string body, string attachment, System.Net.Mail.MailPriority priority, bool isHtmlFormat, Encoding encoding, string smtpServer, string smtpServerPort, string smtpUsername, string smtpPassword, bool smtpEnableSsl = true, CancellationToken cancellationToken = default(CancellationToken))
 => UtilityService.ExecuteTask(() => MessageService.SendMail(from, replyTo, to, cc, bcc, subject, body, attachment, priority, isHtmlFormat, encoding, smtpServer, smtpServerPort, smtpUsername, smtpPassword, smtpEnableSsl, null, null), cancellationToken);
Beispiel #11
0
        /// <summary>
        /// Send an e-mail within VIE Portal software using System.Net.Mail namespace.
        /// </summary>
        /// <param name="from">Sender name and e-mail address.</param>
        /// <param name="replyTo">Address will be replied to.</param>
        /// <param name="to">Recipients. Seperate multiple by comma (,).</param>
        /// <param name="cc">CC recipients. Seperate multiple by comma (,).</param>
        /// <param name="bcc">BCC recipients. Seperate multiple by comma (,).</param>
        /// <param name="subject">Mail subject.</param>
        /// <param name="body">Mail body.</param>
        /// <param name="attachment">Path to attachment file.</param>
        /// <param name="priority">Priority. See <c>System.Net.Mail.MailPriority</c> class for more information.</param>
        /// <param name="isHtmlFormat">TRUE if the message body is HTML formated.</param>
        /// <param name="encoding">Encoding of body message. See <c>System.Web.Mail.MailEncoding</c> class for more information.</param>
        /// <param name="smtpServer">IP address or host name of SMTP server.</param>
        /// <param name="smtpServerPort">Port number for SMTP service on the SMTP server.</param>
        /// <param name="smtpUsername">Username of the SMTP server use for sending mail.</param>
        /// <param name="smtpPassword">Password of user on the SMTP server use for sending mail.</param>
        /// <param name="smtpEnableSsl">TRUE if the SMTP server requires SSL.</param>
        /// <param name="additionalFooter">Additional content will be added into email as footer.</param>
        /// <param name="preventDomains">Collection of harmful domains need to prevent.</param>
        public static void SendMail(string from, string replyTo, string to, string cc, string bcc, string subject, string body, string attachment, System.Net.Mail.MailPriority priority, bool isHtmlFormat, Encoding encoding, string smtpServer, string smtpServerPort, string smtpUsername, string smtpPassword, bool smtpEnableSsl, string additionalFooter, HashSet <string> preventDomains)
        {
            // check sender
            if (from.Equals(""))
            {
                throw new InvalidDataException("No sender information for the message!");
            }

            // validate recipients
            var toEmails = string.IsNullOrWhiteSpace(to)
                                ? ""
                                : to.Trim();

            var ccEmails = string.IsNullOrWhiteSpace(cc)
                                ? ""
                                : cc.Trim();

            var bccEmails = string.IsNullOrWhiteSpace(bcc)
                                ? ""
                                : bcc.Trim();

            // remove all harmful domains
            if (preventDomains != null && preventDomains.Count > 0)
            {
                string[] emails = null;

                // to
                if (!toEmails.Equals(""))
                {
                    emails   = toEmails.ToArray(';');
                    toEmails = "";
                    emails.ForEach(email => toEmails += (!toEmails.Equals("") ? ";" : "") + (!preventDomains.Contains(email.GetDomain()) ? email : ""));
                }

                // cc
                if (!ccEmails.Equals(""))
                {
                    emails   = ccEmails.ToArray(';');
                    ccEmails = "";
                    emails.ForEach(email => ccEmails += (!ccEmails.Equals("") ? ";" : "") + (!preventDomains.Contains(email.GetDomain()) ? email : ""));
                }

                // bcc
                if (!bccEmails.Equals(""))
                {
                    emails    = bccEmails.ToArray(';');
                    bccEmails = "";
                    emails.ForEach(email => bccEmails += (!bccEmails.Equals("") ? ";" : "") + (!preventDomains.Contains(email.GetDomain()) ? email : ""));
                }
            }

            // check recipients
            if (toEmails.Equals("") && ccEmails.Equals("") && bccEmails.Equals(""))
            {
                throw new InvalidDataException("No recipients for the message!");
            }

            // get sender information
            MailAddress fromAddress = null;

            try
            {
                fromAddress = from.ConvertUnicodeToANSI().GetMailAddress();
            }
            catch
            {
                fromAddress = "VIEApps NGX <*****@*****.**>".GetMailAddress();
            }

            // reply to
            MailAddress replyToAddress = null;

            if (!string.IsNullOrWhiteSpace(replyTo))
            {
                try
                {
                    replyToAddress = replyTo.GetMailAddress();
                }
                catch { }
            }

            // recipients
            List <MailAddress> toAddresses = null;

            if (!string.IsNullOrWhiteSpace(toEmails))
            {
                toAddresses = new List <MailAddress>();
                toEmails.ToArray(';').ForEach(email =>
                {
                    try
                    {
                        toAddresses.Add(email.GetMailAddress());
                    }
                    catch { }
                });
            }

            List <MailAddress> ccAddresses = null;

            if (!string.IsNullOrWhiteSpace(ccEmails))
            {
                ccAddresses = new List <MailAddress>();
                ccEmails.ToArray(';').ForEach(email =>
                {
                    try
                    {
                        ccAddresses.Add(email.GetMailAddress());
                    }
                    catch { }
                });
            }

            List <MailAddress> bccAddresses = null;

            if (!string.IsNullOrWhiteSpace(bccEmails))
            {
                bccAddresses = new List <MailAddress>();
                bccEmails.ToArray(';').ForEach(email =>
                {
                    try
                    {
                        bccAddresses.Add(email.GetMailAddress());
                    }
                    catch { }
                });
            }

            // prepare attachments
            var attachments = attachment != null && File.Exists(attachment)
                                ? new List <string>()
            {
                attachment
            }
                                :  null;

            // send mail
            MessageService.SendMail(fromAddress, replyToAddress, toAddresses, ccAddresses, bccAddresses, subject, body, attachments, additionalFooter, priority, isHtmlFormat, encoding, smtpServer, smtpServerPort, smtpUsername, smtpPassword, smtpEnableSsl);
        }
Beispiel #12
0
 /// <summary>
 /// Send an e-mail within VIE Portal software using System.Net.Mail namespace.
 /// </summary>
 /// <param name="from">Sender name and e-mail address.</param>
 /// <param name="replyTo">Address will be replied to.</param>
 /// <param name="to">Recipients. Seperate multiple by comma (,).</param>
 /// <param name="cc">CC recipients. Seperate multiple by comma (,).</param>
 /// <param name="bcc">BCC recipients. Seperate multiple by comma (,).</param>
 /// <param name="subject">Mail subject.</param>
 /// <param name="body">Mail body.</param>
 /// <param name="attachment">Path to attachment file.</param>
 /// <param name="priority">Priority. See <c>System.Net.Mail.MailPriority</c> class for more information.</param>
 /// <param name="isHtmlFormat">TRUE if the message body is HTML formated.</param>
 /// <param name="encoding">Encoding of body message. See <c>System.Web.Mail.MailEncoding</c> class for more information.</param>
 /// <param name="smtpServer">IP address or host name of SMTP server.</param>
 /// <param name="smtpServerPort">Port number for SMTP service on the SMTP server.</param>
 /// <param name="smtpUsername">Username of the SMTP server use for sending mail.</param>
 /// <param name="smtpPassword">Password of user on the SMTP server use for sending mail.</param>
 /// <param name="additionalFooter">Additional content will be added into email as footer.</param>
 /// <param name="preventDomains">Collection of harmful domains need to prevent.</param>
 public static void SendMail(string from, string replyTo, string to, string cc, string bcc, string subject, string body, string attachment, System.Net.Mail.MailPriority priority, bool isHtmlFormat, Encoding encoding, string smtpServer, string smtpServerPort, string smtpUsername, string smtpPassword, string additionalFooter, HashSet <string> preventDomains)
 => MessageService.SendMail(from, replyTo, to, cc, bcc, subject, body, attachment, priority, isHtmlFormat, encoding, smtpServer, smtpServerPort, smtpUsername, smtpPassword, false, additionalFooter, preventDomains);
        public bool SendMail(string To, string ToCc, string ToBcc, string replyTo, string from, string displayName
                             , string subject, string body, string attachFiles, bool IsBodyHtml, System.Net.Mail.MailPriority priority
                             , out string errorMessage)
        {
            if (from == null)
            {
                from = "";
            }


            To = To.ToLower().Replace(";" + from.ToLower(), "").Replace(from.ToLower() + ";", "");
            if (To.Length == 0 && ToCc.Length == 0 && ToBcc.Length == 0)
            {
                errorMessage = "Missing \"To\" address.";
                return(false);
            }
            if (from.Length == 0)
            {
                errorMessage = "Missing \"From\" address.";
                return(false);
            }
            errorMessage = "";
            bool        flag = true;
            MailMessage mail = new MailMessage();

            mail.IsBodyHtml   = IsBodyHtml;
            mail.BodyEncoding = Encoding.UTF8;
            mail.Priority     = priority;
            if (To.Length != 0)
            {
                foreach (string s in To.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    mail.To.Add(s);
                }
            }
            if (ToCc.Length != 0)
            {
                foreach (string s in ToCc.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    mail.CC.Add(s);
                }
            }
            mail.From = new MailAddress(from, displayName);
            if (ToBcc.Length != 0)
            {
                foreach (string s in ToBcc.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    mail.Bcc.Add(s);
                }
            }
            mail.Subject = subject;
            mail.Sender  = mail.From;
            mail.Body    = body;
            //mail.ReplyToList.Add(replyTo);
            if (attachFiles.Length != 0)
            {
                foreach (string s in attachFiles.Split(';'))
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    Attachment attach = new Attachment(s);
                    mail.Attachments.Add(attach);
                }
            }
            SmtpClient client = new SmtpClient();

            client.EnableSsl = true;
            try
            {
                if (Config.IsTest && Config.TestMails != null && Config.TestMails.Trim().Length > 0)
                {
                    body = string.Format("{0}\r\n This is an emial send from test website,it's really send to {1},bcc {2},cc{3}\r\n",
                                         body,
                                         string.Join(",", mail.To.Select(x => x.Address).ToArray()),
                                         string.Join(",", mail.CC.Select(x => x.Address).ToArray()),
                                         string.Join(",", mail.Bcc.Select(x => x.Address).ToArray()));
                    mail.Body = body;
                    mail.To.Clear();
                    var testReceivers = Config.TestMails.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s in testReceivers)
                    {
                        mail.To.Add(s);
                    }
                    mail.CC.Clear();
                    mail.Bcc.Clear();
                }
                client.Send(mail);
                using (StreamWriter write = new StreamWriter(System.Configuration.ConfigurationManager.AppSettings["EmailLog"], true))
                {
                    write.WriteLine(string.Format("To:{0}  On:{1}  发送成功", To, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")));
                    write.WriteLine(string.Format("Body: {0}", body));
                    write.WriteLine("");
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.ToString();
                logger.Log(ex);
                flag = false;
                using (StreamWriter write = new StreamWriter(System.Configuration.ConfigurationManager.AppSettings["EmailLog"], true))
                {
                    write.WriteLine(string.Format("To:{0}  On:{1}  发送失败", To, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")));
                    write.WriteLine(string.Format("Body: {0}", body));
                    write.WriteLine("");
                }
            }
            finally
            {
                mail.Dispose();
            }
            return(flag);
        }
 public bool SendMail(string To, string from, string subject, string body, bool isBodyHtml, System.Net.Mail.MailPriority priority, out string errorMessage)
 {
     return(SendMail(To, "", "", from, from, from, subject, body, "", true, priority, out errorMessage));
 }
 public TextBasedEmailTemplate Priority(System.Net.Mail.MailPriority priority)
 {
     this._priority = new System.Net.Mail.MailPriority?(priority);
     return(this);
 }
        public static void MailGonderAsync(List <string> aliciMailAdresleri, string epostaKonusu, string epostaIcerigi, System.Net.Mail.MailPriority oncelikSeviyesi)
        {
            try
            {
                int    port        = 587;
                string sunucu      = "smtp.gmail.com";
                string sifre       = "Gmail Şifreniz";
                string kullaniciAd = "Gmail Adresiniz";
                bool   sslAktifMi  = true;

                SmtpClient smtpClient = new SmtpClient(sunucu, port);
                smtpClient.Credentials = new System.Net.NetworkCredential(kullaniciAd, sifre);
                smtpClient.EnableSsl   = sslAktifMi;

                System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage
                {
                    From     = new MailAddress(kullaniciAd, epostaKonusu, System.Text.Encoding.UTF8),
                    Priority = oncelikSeviyesi
                };

                foreach (var alici in aliciMailAdresleri)
                {
                    mm.To.Add(alici);
                }
                mm.SubjectEncoding = System.Text.ASCIIEncoding.GetEncoding("UTF-8");
                mm.BodyEncoding    = System.Text.ASCIIEncoding.GetEncoding("UTF-8");
                mm.Subject         = epostaKonusu;
                mm.Body            = epostaIcerigi;
                mm.IsBodyHtml      = true;
                smtpClient.Send(mm);

                Console.WriteLine("==================== BİTTİ ====================");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hata" + ex);
            }
        }
Beispiel #17
0
    public static bool SendMail(string MsgToEMail, System.Net.Mail.MailPriority mpPriority, string MsgSubject, string MsgBody)
    {
        try
        {
            //System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(strSMTPHost);
            //MailMessage msg = new MailMessage();
            //msg.From = mdSpeedoSender;
            //msg.To.Add(new System.Net.Mail.MailAddress(MsgToEMail));
            //msg.Bcc.Add(new System.Net.Mail.MailAddress("*****@*****.**"));
            //msg.IsBodyHtml = true;
            //msg.Priority = mpPriority;
            //msg.Subject = MsgSubject;
            //msg.Body = MsgBody;
            //sc.Send(msg);
            //return true;

            //string to = MsgToEMail; //To address
            //string from = "*****@*****.**"; //From address
            //MailMessage message = new MailMessage(from, to);

            //string mailbody = MsgBody;
            //message.Subject = MsgSubject;
            //message.Priority = mpPriority;
            //message.Body = mailbody;
            //message.BodyEncoding = Encoding.UTF8;
            //message.IsBodyHtml = true;
            //message.CC.Add("*****@*****.**");
            //message.Bcc.Add("*****@*****.**");
            //System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.office365.com", 587); //office365 smtp
            //System.Net.NetworkCredential basicCredential1 = new
            //System.Net.NetworkCredential("*****@*****.**", "masterP0rtal");
            //client.EnableSsl = true;
            //client.UseDefaultCredentials = false;
            //client.Credentials = basicCredential1;

            // ADDED by CALVIN FEB 20, 2018
            string      to       = MsgToEMail;
            string      from     = "*****@*****.**";
            MailMessage message  = new MailMessage(from, to);
            string      mailbody = MsgBody;
            message.Subject      = MsgSubject;
            message.Body         = mailbody;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml   = true;
            System.Net.Mail.SmtpClient   client           = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); //gmail smtp
            System.Net.NetworkCredential basicCredential1 = new
                                                            System.Net.NetworkCredential("*****@*****.**", "pficportal2018");
            client.EnableSsl             = true;
            client.UseDefaultCredentials = false;
            client.Credentials           = basicCredential1;
            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Beispiel #18
0
        //public bool EnviarCorreo(string idCanalContenido, string idContenido, Dictionary<string, string> comodinesNotificacion, string idCanalNotificaciones, string idContenidoNotificaciones, string rutaFrondEnd = "")
        //{
        //    bool result = false;
        //    string destino = "";
        //    try
        //    {
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Inicio :");
        //        //List<string> comodines = new List<string>();
        //        List<string> valores = new List<string>();

        //        List<string> comodines = new List<string>();

        //        (new ManejadorLog()).RegistrarEvento("dentro de mailerEnviarCorreo");

        //        //Obtener la plantilla para el envio de correo
        //        ScriptorChannel canalNotificaciones = Common.ScriptorClient.GetChannel(new Guid(idCanalNotificaciones));
        //        ScriptorContent contenidoNotificaciones = canalNotificaciones.GetContent(new Guid(idContenidoNotificaciones));
        //        //ScriptorContent contenidoNotificaciones = canalNotificaciones.Contents.Find(x => x.Id.ToString().ToUpper() == idContenidoNotificaciones.ToUpper());

        //        (new ManejadorLog()).RegistrarEvento("despues de canalNotificaciones");


        //        HelperEnviarCorreo.CrearLog("Bien 1");
        //        //var d = contenidoNotificaciones.Parts.A[0].Parts.A;
        //        var archivos = (ScriptorContentInsert)contenidoNotificaciones.Parts.ArchivosAdjuntos;

        //        HelperEnviarCorreo.CrearLog("Bien 2");
        //        CorreoBE correo = new CorreoBE();

        //        if (contenidoNotificaciones.Parts.CorreoPara != "" && contenidoNotificaciones.Parts.CorreoPara != null)
        //        {
        //            correo.Para.Add(contenidoNotificaciones.Parts.CorreoPara);
        //        }

        //        if (comodinesNotificacion != null && comodinesNotificacion.ContainsKey("_para_"))
        //        {
        //            correo.Para.Clear();
        //            destino = comodinesNotificacion["_para_"];
        //            correo.Para.Add(destino);
        //            comodinesNotificacion.Remove("_para_");
        //        }
        //        HelperEnviarCorreo.CrearLog("Bien 3");


        //        if (idCanalContenido != string.Empty && idContenido != string.Empty)
        //        {
        //            //Obtener el contenido para reemplazar los valores en el cuerpo del correo
        //            ScriptorChannel canalContenido = Common.ScriptorClient.GetChannel(new Guid(idCanalContenido));
        //            ScriptorContent contenido = canalContenido.GetContent(new Guid(idContenido));

        //            //ScriptorContent contenido = canalContenido.Contents.Find(x => x.Id.ToString().ToUpper() == idContenido.ToUpper());
        //            HelperEnviarCorreo.CrearLog(idContenido.ToUpper());

        //            if (correo.Para.Count == 0)
        //            {
        //                HelperEnviarCorreo.CrearLog("correo1");

        //                if (contenido.Parts.NombreCompleto != "" && contenido.Parts.NombreCompleto != null)
        //                {
        //                    HelperEnviarCorreo.CrearLog("correo2");
        //                    correo.Para.Add(contenido.Parts.NombreCompleto);
        //                    HelperEnviarCorreo.CrearLog("correo3");
        //                }
        //            }

        //            foreach (var llave in contenido.Parts.Values)
        //            {
        //                string valor = "";

        //                if (llave.GetType().ToString() == "Viatecla.Factory.Scriptor.ScriptorDropdownListValue")
        //                {
        //                    valor = llave.Title;
        //                }
        //                else if (llave.GetType().ToString() == "Viatecla.Factory.Scriptor.ScriptorContentInsert")
        //                {

        //                }
        //                else
        //                {
        //                    valor = llave;
        //                }

        //                valores.Add(valor);
        //            }

        //            comodines = new List<string>(contenido.Parts.Keys);
        //        }
        //        else
        //        {
        //            comodines = comodinesNotificacion.Keys.ToList<string>();
        //            valores = comodinesNotificacion.Values.ToList<string>();
        //        }

        //        HelperEnviarCorreo.CrearLog("Bien 4");
        //        if (contenidoNotificaciones.Parts.CorreoCCO != "" && contenidoNotificaciones.Parts.CorreoCCO != null)
        //        {
        //            correo.ConCopiaOculta.Add(contenidoNotificaciones.Parts.CorreoCCO);
        //        }

        //        HelperEnviarCorreo.CrearLog("Bien 5");
        //        String from = contenidoNotificaciones.Parts.CorreoDe;

        //        correo.Asunto = contenidoNotificaciones.Parts.Asunto;
        //        correo.CuerpoMensaje = contenidoNotificaciones.Parts.CorreoBody.ToString();

        //        HelperEnviarCorreo.CrearLog("Bien 6");
        //        //correo.CuerpoMensaje = ReemplazarComodines(correo.CuerpoMensaje, this.GetComodines(comodines), valores, rutaFrondEnd);

        //        correo.ArchivosAdjuntos = this.GetArchivosAdjuntos(archivos, rutaFrondEnd);

        //        HelperEnviarCorreo helperEnviarCorreo = new HelperEnviarCorreo(from);
        //        helperEnviarCorreo.EnviarCorreoLocal(correo);

        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Fin:");

        //        result = true;

        //    }
        //    catch (Exception ex)
        //    {
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Error:" + ex.Message);
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Error:" + ex.InnerException);
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Error:" + ex.StackTrace);
        //        result = false;
        //    }

        //    return result;
        //}

        //public List<ArchivoAdjunto> GetArchivosAdjuntos(ScriptorContentInsert contentInsert, string pathFrontEnd)
        //{
        //    List<ArchivoAdjunto> archivoAdjuntoList = new List<ArchivoAdjunto>();

        //    foreach (ScriptorContent content in contentInsert)
        //    {
        //        ArchivoAdjunto archivoAdjunto = new ArchivoAdjunto();
        //        archivoAdjunto.NombreArchivo = content.Parts.Titulo;
        //        archivoAdjunto.RutaArchivoWeb = string.Format("{0}{1}", pathFrontEnd, content.Parts.ArchivoAdjunto);
        //        archivoAdjunto.RutaArchivoWeb = archivoAdjunto.GetRutaArchivoWebFront();
        //        archivoAdjuntoList.Add(archivoAdjunto);
        //    }

        //    return archivoAdjuntoList;
        //}

        private void EnviarCorreo_Aux(CorreoBE correo,
                                      Boolean isbodyHtml,
                                      System.Net.Mail.MailPriority prioridad)
        {
            System.Net.Mail.MailMessage Mail = new System.Net.Mail.MailMessage();

            isbodyHtml = true;
            prioridad  = System.Net.Mail.MailPriority.High;

            List <LinkedResource> lstLinked = new List <LinkedResource>();

            //'----------------------------------------------------------------------------------
            if (correo.Para != null)
            {
                foreach (String reg in correo.Para)
                {
                    Mail.To.Add(reg);
                }
            }
            if (correo.ConCopia != null)
            {
                foreach (String reg in correo.ConCopia)
                {
                    Mail.CC.Add(reg);
                }
            }
            if (correo.ConCopiaOculta != null)
            {
                foreach (String reg in correo.ConCopiaOculta)
                {
                    Mail.Bcc.Add(reg);
                }
            }
            if (correo.ArchivosAdjuntos != null)
            {
                foreach (ArchivoAdjunto reg in correo.ArchivosAdjuntos)
                {
                    if (String.IsNullOrEmpty(reg.RutaArchivoDisco))
                    {
                        if (!String.IsNullOrEmpty(reg.RutaArchivoWeb))
                        {
                            System.Net.Mail.Attachment archivo = null;
                            switch (System.Configuration.ConfigurationManager.AppSettings["TipoCorreoAdjunto"])
                            {
                            case "1":    //adjunto
                                reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo);
                                //adjunto
                                archivo = new System.Net.Mail.Attachment(reg.RutaArchivoDisco);
                                Mail.Attachments.Add(archivo);
                                break;

                            case "2":    //base64

                                if (reg.NombreArchivo.ToUpper().Contains(".PNG") ||
                                    reg.NombreArchivo.ToUpper().Contains(".JPEG") ||
                                    reg.NombreArchivo.ToUpper().Contains(".GIF") ||
                                    reg.NombreArchivo.ToUpper().Contains(".JPG"))
                                {
                                    /*
                                     * string imagen64bits = "";
                                     * reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo, out imagen64bits);
                                     * reg.Imagen64bits = imagen64bits;
                                     *
                                     * correo.CuerpoMensaje = correo.CuerpoMensaje.Replace("cid:" + reg.NombreArchivo, "data:image/jpeg;base64," + reg.Imagen64bits);
                                     */
                                    reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo);
                                    LinkedResource sampleImage = new LinkedResource(reg.RutaArchivoDisco,
                                                                                    MediaTypeNames.Image.Jpeg);
                                    sampleImage.ContentId = reg.NombreArchivo;
                                    lstLinked.Add(sampleImage);
                                }
                                else
                                {
                                    reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo);
                                    //adjunto
                                    archivo = new System.Net.Mail.Attachment(reg.RutaArchivoDisco);
                                    Mail.Attachments.Add(archivo);
                                }
                                break;

                            case "3":    //url
                                string   urlDominioWebFrontEnd = System.Configuration.ConfigurationManager.AppSettings["UrlDominioWebFrontEnd"];
                                string   urlTmp       = reg.GetRutaArchivoWebFront();
                                string   urlTmpSufijo = "";
                                string[] listatmp     = urlTmp.Split('/');
                                for (int i = 0; i < listatmp.Length; i++)
                                {
                                    if (i >= 3)
                                    {
                                        urlTmpSufijo = urlTmpSufijo + '/' + listatmp[i];
                                    }
                                }
                                urlTmp = urlDominioWebFrontEnd + urlTmpSufijo;
                                correo.CuerpoMensaje = correo.CuerpoMensaje.Replace("cid:" + reg.NombreArchivo, urlTmp);
                                break;
                            }
                        }
                    }
                }
            }



            Mail.From = new System.Net.Mail.MailAddress(this.From);

            Mail.Subject    = correo.Asunto;
            Mail.IsBodyHtml = isbodyHtml;
            Mail.Body       = correo.CuerpoMensaje;
            switch (System.Configuration.ConfigurationManager.AppSettings["TipoCorreoAdjunto"])
            {
            case "2":    //adjunto
            {
                /*ContentType mimeType = new System.Net.Mime.ContentType("text/html");
                 * AlternateView alternate = AlternateView.CreateAlternateViewFromString(correo.CuerpoMensaje, mimeType);
                 * Mail.AlternateViews.Add(alternate);*/
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(correo.CuerpoMensaje, null, MediaTypeNames.Text.Html);
                foreach (var item in lstLinked)
                {
                    htmlView.LinkedResources.Add(item);
                }
                Mail.AlternateViews.Add(htmlView);
            }
            break;
            }

            //'----------------------------------------------------------------------------------
            SmtpClient cliente = new SmtpClient();

            cliente.Host = "" + System.Configuration.ConfigurationManager.AppSettings["Host"];
            if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Port"]) != "")
            {
                cliente.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);
            }
            cliente.EnableSsl             = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableSsl"]);
            cliente.UseDefaultCredentials = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseDefaultCredentials"]);
            if (cliente.UseDefaultCredentials == false)
            {
                cliente.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["CredentialsUser"], "" + System.Configuration.ConfigurationManager.AppSettings["CredentialsClave"]);
            }

            //'----------------------------------------------------------------------------------
            try
            {
                cliente.Send(Mail);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 public bool SendMail(string To, string subject, string body, bool isBodyHtml, System.Net.Mail.MailPriority priority) //6
 {
     return(SendMail(To, "", "", "", subject, body, "", isBodyHtml, priority));
 }