Example #1
0
        private void SendMessage(MessageItemWithState m)
        {
            var mailItem = new MailMessage();

            try
            {
                foreach (string s in m.ToAddress.Split(','))
                {
                    var splitted    = s.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    var mailAddress = new MailAddress(splitted[1], splitted[0]);
                    mailItem.To.Add(mailAddress);
                }

                if (!string.IsNullOrEmpty(m.Cc))
                {
                    foreach (string s in m.Cc.Split(','))
                    {
                        var splitted    = s.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        var mailAddress = new MailAddress(splitted[1], splitted[0]);
                        mailItem.CC.Add(mailAddress);
                    }
                }

                mailItem.Body = m.TextBody;

                //first we create the Plain Text part
                if (!String.IsNullOrEmpty(m.TextBody))
                {
                    AlternateView plainView = AlternateView.CreateAlternateViewFromString(m.TextBody, System.Text.Encoding.UTF8, MediaTypeNames.Text.Plain);
                    mailItem.AlternateViews.Add(plainView);
                }

                //then we create the Html part
                if (!String.IsNullOrEmpty(m.HtmlBody))
                {
                    AlternateView plainView = AlternateView.CreateAlternateViewFromString(m.HtmlBody, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
                    mailItem.AlternateViews.Add(plainView);
                }

                mailItem.From       = new MailAddress(mailSetting.From, mailSetting.FromName);
                mailItem.IsBodyHtml = !String.IsNullOrEmpty(m.HtmlBody);
                mailItem.Priority   = MailPriority.Normal;
                mailItem.Subject    = m.Subject;

                var mailService = new SmtpClient();
                mailService.Host      = mailSetting.Server;
                mailService.Port      = mailSetting.Port;
                mailService.EnableSsl = mailSetting.UseSsl;

                if (!string.IsNullOrEmpty(mailSetting.Login) && !string.IsNullOrEmpty(mailSetting.Password))
                {
                    var cred = new System.Net.NetworkCredential(mailSetting.Login, mailSetting.Password);
                    mailService.Credentials = cred;
                }

                mailService.Send(mailItem);
                mailItem.Dispose();
            }
            finally
            {
                if (mailItem != null)
                {
                    mailItem.Dispose();
                }
            }
        }
Example #2
0
        public static bool SendMail(IList <string> mailAdresses, IList <string> ccAddresses, string originalHtml, string originalSubject, ILogEmailRepository logEmailRepository, byte[] attachment, LogEmail logEmail)
        {
            ContactCenterDA.Repositories.CC.TH.ObraRepository obraRepository = new ContactCenterDA.Repositories.CC.TH.ObraRepository();
            try
            {
                var smtpClient = new SmtpClient();

                #region Get Config Variables
                String correo   = "";
                String password = "";
                if (Sesion.aplicacion.CorreoNotificacion.Equals(String.Empty))
                {
                    correo   = ConfigurationManager.AppSettings["mailAccount"];
                    password = ConfigurationManager.AppSettings["mailPassword"];
                }
                else
                {
                    correo   = Sesion.aplicacion.CorreoNotificacion;
                    password = Sesion.aplicacion.Contraseña;
                }
                var mailAccount     = correo;
                var mailPassword    = password;
                var smtp            = ConfigurationManager.AppSettings["smtp"];
                var mailDisplayName = ConfigurationManager.AppSettings["mailDisplayName"];
                var port            = ConfigurationManager.AppSettings["port"];
                var sslEnabled      = Convert.ToBoolean(ConfigurationManager.AppSettings["sslEnabled"]);
                var domain          = ConfigurationManager.AppSettings["Domain"];
                #endregion

                #region Create SMTP
                smtpClient.Host = smtp;
                smtpClient.Port = Convert.ToInt16(port);
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                if (domain != null)
                {
                    smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword, domain);
                }
                else
                {
                    smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword);
                }
                smtpClient.EnableSsl = sslEnabled;

                #endregion Create SMTP

                #region Create Mail an recievers
                var mail = new MailMessage();
                mail.From = new MailAddress(mailAccount, mailDisplayName);
                foreach (var mailDirection in mailAdresses.Where(x => !string.IsNullOrEmpty(x)))
                {
                    mail.To.Add(new MailAddress(mailDirection.ToLower()));
                }
                foreach (var mailCC in ccAddresses.Where(x => !string.IsNullOrEmpty(x)))
                {
                    mail.CC.Add(new MailAddress(mailCC.ToLower()));
                }

                #endregion

                #region Create Mail Variables
                string htmlBody = originalHtml;
                string subject  = originalSubject;

                #endregion Create Mail Variables


                #region Get Mail Body embedded images paths

                Byte[]       ba = obraRepository.GetImage(logEmail.IdObra);
                MemoryStream ms = new MemoryStream(ba);

                Image        ImageCabe     = ContactCenterBL.Properties.Resources.cabecera;
                Byte[]       imageCabeByte = Convertir_Imagen_Bytes(ImageCabe);
                MemoryStream ca            = new MemoryStream(imageCabeByte);
                #endregion Get Mail Body embedded images paths

                #region Set embedded images mail id
                var cabecera = new LinkedResource(ca, MediaTypeNames.Image.Jpeg);
                cabecera.ContentId = "Cabecera";
                //cabecera.TransferEncoding = TransferEncoding.Base64;
                var logo = new LinkedResource(ms, MediaTypeNames.Image.Jpeg);
                //logo.TransferEncoding = TransferEncoding.Base64;
                logo.ContentId = "ImagenObra";

                var imageText = logEmail.MensajeImagen;

                Image         imageMail;
                AlternateView html = null;
                if (imageText.Equals(String.Empty)) // legacy emails
                {
                    html = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
                    html.LinkedResources.Add(logo);
                    html.LinkedResources.Add(cabecera);
                }
                else
                {
                    Image image = Image.FromStream(ca);
                    Guid  id    = Guid.NewGuid();
                    image.Save($"C:\\BackupTeatro\\{id.ToString()}.jpg");
                    string path = $"C:\\BackupTeatro\\{id.ToString()}.jpg";


                    Image image2 = Image.FromStream(ms);
                    Guid  id2    = Guid.NewGuid();
                    image2.Save($"C:\\BackupTeatro\\{id2.ToString()}.jpg");
                    string path2 = $"C:\\BackupTeatro\\{id2.ToString()}.jpg";

                    htmlBody  = htmlBody.Replace("%Cabecera", path);
                    htmlBody  = htmlBody.Replace("%ImagenObra", path2);
                    imageText = imageText.Replace("%Cabecera", path);
                    imageText = imageText.Replace("%ImagenObra", path2);

                    imageMail = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImageGdiPlus(imageText);
                    //imageMail.Save($"C:\\BackupTeatro\\test2.jpg");
                    //Image imagex = Image.FromFile($"C:\\BackupTeatro\\test2.jpg");
                    Byte[]       imageMailBytes        = Convertir_Imagen_Bytes(imageMail);
                    MemoryStream imageMailMemoryStream = new MemoryStream(imageMailBytes);
                    var          imageMailLinked       = new LinkedResource(imageMailMemoryStream, MediaTypeNames.Image.Jpeg);
                    imageMailLinked.ContentId = "obraimagen";
                    Byte[]       pdfFile   = PdfSharpConvert(htmlBody);
                    MemoryStream pdfStream = new MemoryStream(pdfFile);
                    mail.Attachments.Add(new Attachment(pdfStream, "Confirmación de compra.pdf"));

                    if (File.Exists(path2))
                    {
                        File.Delete(path2);
                    }
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    htmlBody  = htmlBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera");
                    htmlBody  = htmlBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra");
                    imageText = imageText.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera");
                    imageText = imageText.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra");
                    var newHtml = ContactCenterBL.Properties.Resources._base;
                    html = AlternateView.CreateAlternateViewFromString(newHtml, null, MediaTypeNames.Text.Html);
                    //html.TransferEncoding = TransferEncoding.Base64;
                    html.LinkedResources.Add(imageMailLinked);
                }



                //mail.Attachments.Add(new Attachment(imageMailMemoryStream, "Compra.jpg"));



                #endregion

                #region Set Body and Images


                //html.LinkedResources.Add(cabecera);

                #endregion Get Mail Body embedded images paths

                #region Set values to mail

                mail.Subject    = subject;
                mail.IsBodyHtml = true;
                //Attachment inlineLogo = new Attachment(@"../../Resources/cabecera_correo2.jpg");
                //string contentID = "cabe";
                //inlineLogo.ContentId = contentID;
                //inlineLogo.ContentDisposition.Inline = true;
                //inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                //mail.Attachments.Add(inlineLogo);

                mail.AlternateViews.Add(html);

                #endregion Set values to mail

                #region Send Mail

                smtpClient.Send(mail);
                logEmail.Asunto              = subject;
                logEmail.CorreoDestino       = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray());
                logEmail.CorreoDestinoCC     = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray());
                logEmail.Estado              = "OK";
                logEmail.FechaEnvio          = DateTime.Now;
                logEmail.FechaModificacion   = DateTime.Now;
                logEmail.UsuarioModificacion = Sesion.usuario.Login;
                logEmail.Mensaje             = htmlBody;
                logEmail.Intento             = logEmail.Intento + 1;
                logEmail.Descripcion         = String.Empty;

                logEmailRepository.Update(logEmail);
                smtpClient.Dispose();
                mail.Dispose();
                logo.Dispose();
                return(true);

                #endregion Send Mail
            }
            catch (Exception ex)
            {
                logEmail.CorreoDestino       = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray());
                logEmail.CorreoDestinoCC     = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray());
                logEmail.FechaEnvio          = DateTime.Now;
                logEmail.FechaModificacion   = DateTime.Now;
                logEmail.UsuarioModificacion = Sesion.usuario.Login;
                logEmail.Intento             = logEmail.Intento + 1;
                logEmail.Estado      = "FALLO";
                logEmail.Descripcion = ex.Message;
                logEmailRepository.Update(logEmail);
                return(false);
            }
        }
Example #3
0
 public void CreateAlternateViewFromStringEncodingNull()
 {
     AlternateView.CreateAlternateViewFromString("<p>test message</p>", null, "text/html");
 }
Example #4
0
 /// <summary>
 /// Sends an email
 /// </summary>
 /// <param name="MessageBody">The body of the message</param>
 public virtual void SendMail(string MessageBody = "")
 {
     if (!string.IsNullOrEmpty(MessageBody))
     {
         Body = MessageBody;
     }
     if (string.IsNullOrEmpty(Body))
     {
         Body = " ";
     }
     using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage())
     {
         char[]   Splitter          = { ',', ';' };
         string[] AddressCollection = To.Split(Splitter);
         for (int x = 0; x < AddressCollection.Length; ++x)
         {
             if (!string.IsNullOrEmpty(AddressCollection[x].Trim()))
             {
                 message.To.Add(AddressCollection[x]);
             }
         }
         if (!string.IsNullOrEmpty(CC))
         {
             AddressCollection = CC.Split(Splitter);
             for (int x = 0; x < AddressCollection.Length; ++x)
             {
                 if (!string.IsNullOrEmpty(AddressCollection[x].Trim()))
                 {
                     message.CC.Add(AddressCollection[x]);
                 }
             }
         }
         if (!string.IsNullOrEmpty(Bcc))
         {
             AddressCollection = Bcc.Split(Splitter);
             for (int x = 0; x < AddressCollection.Length; ++x)
             {
                 if (!string.IsNullOrEmpty(AddressCollection[x].Trim()))
                 {
                     message.Bcc.Add(AddressCollection[x]);
                 }
             }
         }
         message.Subject = Subject;
         message.From    = new System.Net.Mail.MailAddress((From));
         using (AlternateView BodyView = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html))
         {
             foreach (LinkedResource Resource in EmbeddedResources)
             {
                 BodyView.LinkedResources.Add(Resource);
             }
             message.AlternateViews.Add(BodyView);
             //message.Body = Body;
             message.Priority        = Priority;
             message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
             message.BodyEncoding    = System.Text.Encoding.GetEncoding("ISO-8859-1");
             message.IsBodyHtml      = true;
             foreach (Attachment TempAttachment in Attachments)
             {
                 message.Attachments.Add(TempAttachment);
             }
             using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(Server, Port))
             {
                 if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
                 {
                     smtp.Credentials = new System.Net.NetworkCredential(UserName, Password);
                 }
                 if (UseSSL)
                 {
                     smtp.EnableSsl = true;
                 }
                 else
                 {
                     smtp.EnableSsl = false;
                 }
                 smtp.Send(message);
             }
         }
     }
 }
        public void EnviarMail(string destino, string remitente, string asunto, string mensaje, string filePath)
        {
            string       usernameDestino = "";
            MiembroModel miembroDestino;
            MiembroModel miembroRemitente;
            string       nombreCompletoDestino   = "";
            string       nombreCompletoRemitente = "";
            string       emailAddress            = "";

            miembroRemitente        = listaMiembros.Find(x => x.usernamePK == remitente);
            nombreCompletoRemitente = miembroRemitente.nombre + " " + miembroRemitente.apellido1 + " " + miembroRemitente.apellido2;

            if (!destino.Contains("@"))
            {
                usernameDestino = destino.Split('(', ')')[1];

                miembroDestino = listaMiembros.Find(x => x.usernamePK == usernameDestino);

                nombreCompletoDestino = miembroDestino.nombre + " " + miembroDestino.apellido1 + " " + miembroDestino.apellido2;
                emailAddress          = miembroDestino.email;
            }
            else
            {
                emailAddress          = destino;
                nombreCompletoDestino = destino;
            }

            asunto = "[LaCafeteria] " + asunto;
            string mensajeHtml = "<h3>Estimado " + nombreCompletoDestino + ",</h3>" +
                                 "<p><i>Has recibido un mensaje de la comunidad La Cafeteria del miembro " + nombreCompletoRemitente + " (" + remitente + ") : </i><br/><br/>" + mensaje +
                                 "<br/><br/><i> Para responder, por favor hacerlo desde nuestro sitio web. </i><br/><br/></p>";

            MailAddress fromAddress = new MailAddress("*****@*****.**", "La Cafeteria");
            MailAddress toAddress   = new MailAddress(emailAddress, nombreCompletoDestino);

            const string fromPassword = "******";

            var smtp = new SmtpClient
            {
                Host                  = "smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            LinkedResource resource = new LinkedResource(rutaCarpeta + "/images/TCP.png", "image/png");

            resource.ContentId = Guid.NewGuid().ToString();
            string htmlImage = @"<img src='cid:" + resource.ContentId + @"'/>";

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(mensajeHtml + htmlImage, Encoding.UTF8, MediaTypeNames.Text.Html);

            htmlView.LinkedResources.Add(resource);

            var message = new MailMessage(fromAddress, toAddress);

            message.Subject    = asunto;
            message.IsBodyHtml = true;

            if (filePath != "")
            {
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(filePath);
                message.Attachments.Add(attachment);
            }

            message.AlternateViews.Add(htmlView);
            smtp.Send(message);



            /*if ( filePath != "" )
             * {
             *  message.Attachments.Clear();
             *  message.Attachments.Dispose();
             *  message.Dispose();
             *  message = null;
             *  smtp.Dispose();
             *  System.IO.File.Delete(filePath);
             * }*/
        }
        public void receives()
        {
            var hostSettings = new SMTPImpostorHostSettings(
                      ip: "127.0.0.1",
                      port: 52525);

            var expectedCount = 10;

            var messages = new List<SMTPImpostorMessage>();
            using var host = GetSMTPImpostorHost(hostSettings);
            using var events = host.Events
                    .OfType<SMTPImpostorMessageReceivedEvent>()
                    .Subscribe(e => messages.Add(e.Data));

            using var client = new SmtpClient(hostSettings.IP, hostSettings.Port);
            using var mailMessage = new MailMessage
            {
                From = new MailAddress("*****@*****.**"),
                Subject = "SUBJECT"
            };

            mailMessage.To.Add("*****@*****.**");
            mailMessage.CC.Add("*****@*****.**");
            mailMessage.CC.Add("*****@*****.**");

            //mailMessage.Body = TestResources.HTML_EMAIL;
            //mailMessage.IsBodyHtml = true;

            mailMessage.Body = "SOME CONTENT\nSOME CONTENT\nSOME CONTENT\nSOME CONTENT\n";

            var alternate = AlternateView.CreateAlternateViewFromString(
                TestResources.HTML_EMAIL,
                new ContentType("text/html"));
            mailMessage.AlternateViews.Add(alternate);

            var buffer = new byte[100 * 1000];
            for (var i = 0; i < buffer.Length; i++)
                buffer[i] = 0;

            using (var stream = new MemoryStream(buffer))
            {
                mailMessage.Attachments.Add(new Attachment(
                    stream, new ContentType("application/app")
                    ));

                for (var i = 0; i < expectedCount; i++)
                    client.Send(mailMessage);
            }

            Assert.AreEqual(expectedCount, messages.Count());

            var message = messages[1];

            Assert.IsFalse(string.IsNullOrWhiteSpace(message.Id));
            Assert.AreNotEqual(0, message.Headers);
            Assert.IsFalse(string.IsNullOrWhiteSpace(message.Subject));
            Assert.IsNotNull(message.From);
            Assert.AreEqual(1, message.To.Count);
            Assert.AreEqual(2, message.Cc.Count);
            Assert.IsFalse(string.IsNullOrWhiteSpace(message.Content));

            Console.WriteLine("===== HEADERS =====");
            Console.WriteLine(string.Join("\n", message.Headers));

            Console.WriteLine("===== CONTENT =====");
            Console.WriteLine(message.Content);
        }
Example #7
0
        /// <summary>
        ///     发送邮件
        /// </summary>
        /// <param name="mailTo">收件人
        /// <param name="mailCcArray">抄送
        /// <param name="subject">主题
        /// <param name="body">内容
        /// <param name="isBodyHtml">是否Html
        /// <param name="attachmentsPath">附件
        /// <returns></returns>
        public static bool Send(string[] mailTo, string[] mailCcArray, string subject, string body, bool isBodyHtml,
                                string[] attachmentsPath, string sign, string userName, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(userName) ||
                    string.IsNullOrEmpty(Port) || string.IsNullOrEmpty(password))
                {
                    //todo:记录日志
                    return(false);
                }
                var @from   = new MailAddress(userName); //使用指定的邮件地址初始化MailAddress实例
                var message = new MailMessage();         //初始化MailMessage实例
                //向收件人地址集合添加邮件地址
                if (mailTo != null)
                {
                    foreach (string t in mailTo)
                    {
                        message.To.Add(t);
                    }
                }

                //向抄送收件人地址集合添加邮件地址
                if (mailCcArray != null)
                {
                    foreach (string t in mailCcArray)
                    {
                        message.CC.Add(t);
                    }
                }
                //发件人地址
                message.From = @from;

                //电子邮件的标题
                message.Subject = subject;

                //电子邮件的主题内容使用的编码
                message.SubjectEncoding = Encoding.UTF8;

                //电子邮件正文
                message.Body = body;

                //电子邮件正文的编码
                message.BodyEncoding = Encoding.Default;
                message.Priority     = MailPriority.High;
                //message.IsBodyHtml = isBodyHtml;

                var html  = AlternateView.CreateAlternateViewFromString(body, Encoding.UTF8, "text/html");
                var image = new LinkedResource(sign, "image/jpeg");
                image.ContentId = Utils.ImgToBase64String(sign);
                html.LinkedResources.Add(image);
                message.AlternateViews.Add(html);

                //在有附件的情况下添加附件
                if (attachmentsPath != null && attachmentsPath.Length > 0)
                {
                    foreach (string path in attachmentsPath)
                    {
                        var attachFile = new Attachment(path);
                        message.Attachments.Add(attachFile);
                    }
                }
                try
                {
                    var smtp = new SmtpClient
                    {
                        Credentials = new NetworkCredential(UserName, Password),
                        Host        = Host,
                        Port        = Convert.ToInt32(Port)
                    };

                    //将邮件发送到SMTP邮件服务器
                    smtp.Send(message);
                    //todo:记录日志
                    return(true);
                }
                catch (SmtpException ex)
                {
                    //todo:记录日志
                    return(false);
                }
            }
            catch (SmtpException ex)
            {
                //todo:记录日志
                return(false);
            }
        }
        private MailMessage PrepareMailMessage()
        {
            Contact     Organizer = null;
            MailMessage message   = new MailMessage();

            if (_mail.From != null)
            {
                message.From = new MailAddress(_mail.From.MailAddress, GetContactDisplayName(_mail.From), Encoding.UTF8);
                Organizer    = _mail.From;
            }
            else
            {
                message.From = new MailAddress(_mail.Settings.SMTPUserEmail);
                Organizer    = new Contact(message.From.Address, message.From.DisplayName);
            }

            if (_mail.ReplyTo != null)
            {
                message.ReplyToList.Add(new MailAddress(_mail.ReplyTo.MailAddress, GetContactDisplayName(_mail.ReplyTo), Encoding.UTF8));
                Organizer = _mail.ReplyTo;
            }

            foreach (var contact in _mail.To)
            {
                if (contact.Type == ContactType.To || contact.Type == ContactType.Required)
                {
                    message.To.Add(new MailAddress(contact.MailAddress, GetContactDisplayName(contact), Encoding.UTF8));
                }
                if (contact.Type == ContactType.Cc || contact.Type == ContactType.Optional)
                {
                    message.CC.Add(new MailAddress(contact.MailAddress, GetContactDisplayName(contact), Encoding.UTF8));
                }
                if (contact.Type == ContactType.Bcc || contact.Type == ContactType.Resource)
                {
                    message.Bcc.Add(new MailAddress(contact.MailAddress, GetContactDisplayName(contact), Encoding.UTF8));
                }
            }

            if (_mail.Settings.SubjectEncoding != null)
            {
                message.SubjectEncoding = _mail.Settings.SubjectEncoding;
            }
            else
            {
                message.SubjectEncoding = System.Text.Encoding.UTF8;
            }

            if (_mail.Settings.BodyEncoding != null)
            {
                message.BodyEncoding = _mail.Settings.BodyEncoding;
            }
            else
            {
                message.BodyEncoding = System.Text.Encoding.UTF8;
            }

            message.Subject = _mail.Subject;

            foreach (var attachment in _mail.Attachments)
            {
                try
                {
                    message.Attachments.Add(new System.Net.Mail.Attachment(attachment.OpenContentStream(), attachment.Name, attachment.MediaType));
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Failed open content stream for attachment: " + attachment.Name, ex);
                }
            }

            string bodyText = _mail.Body;

            //Set up the different mime types contained in the message
            System.Net.Mime.ContentType textType = new System.Net.Mime.ContentType(MediaTypeNames.Text.Plain);
            System.Net.Mime.ContentType htmlType = new System.Net.Mime.ContentType(MediaTypeNames.Text.Html);

            if (_mail.Settings.CharSet != null)
            {
                textType.CharSet = _mail.Settings.CharSet;
                htmlType.CharSet = _mail.Settings.CharSet;
            }
            else
            {
                textType.CharSet = "UTF-8";
                htmlType.CharSet = "UTF-8";
            }

            var plainText = ConvertToPlainText(_mail.Body);

            if (plainText != null)
            {
                var textView = AlternateView.CreateAlternateViewFromString(plainText, textType);
                message.AlternateViews.Add(textView);
            }

            var htmlView = AlternateView.CreateAlternateViewFromString(_mail.Body, htmlType);

            message.AlternateViews.Add(htmlView);

            if (_mail.Meeting != null)
            {
                _mail.Meeting.Summary     = _mail.Subject;
                _mail.Meeting.Description = bodyText;
                message.Headers.Add("Content-class", "urn:content-classes:calendarmessage");
                System.Net.Mime.ContentType calendarType = new System.Net.Mime.ContentType("text/calendar");
                calendarType.CharSet = htmlType.CharSet;
                //  Add parameters to the calendar header
                calendarType.Parameters.Add("method", "REQUEST");
                calendarType.Parameters.Add("name", "meeting.ics");

                AlternateView calendarView = AlternateView.CreateAlternateViewFromString(_mail.Meeting.Generate(_mail.To, Organizer), calendarType);
                calendarView.TransferEncoding = TransferEncoding.Base64;
                message.AlternateViews.Add(calendarView);
            }

            foreach (var header in _mail.Headers)
            {
                message.Headers.Add(header.Item1, header.Item2);
            }

            return(message);
        }
        protected void btnRegister_Click(object sender, System.EventArgs e)
        {
            //Add user into list and log them in
            if (IsValid)
            {
                user = (User)Session["tempUser"];
                Session.Remove("tempUser");
                //If user ticked register as admin box a confirmation email will be sent
                if (user.IsAdmin)
                {
                    user.FirstName = ((TextBox)FindControl("firstName")).Text;
                    user.LastName  = ((TextBox)FindControl("lastName")).Text;
                    user.Street    = ((TextBox)FindControl("streetAddress")).Text;
                    user.Suburb    = ((TextBox)FindControl("suburb")).Text;
                    user.Postcode  = ((TextBox)FindControl("postCode")).Text;
                    user.DOB       = ((TextBox)FindControl("birthDate")).Text;
                    user.Phone     = ((TextBox)FindControl("firstName")).Text;
                    GlobalData.userMap.Add(user.Email, user);

                    //Accessing gmail account to send email
                    SmtpClient client = new SmtpClient();
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.EnableSsl      = true;
                    client.Host           = "smtp.gmail.com";
                    client.Port           = 587;
                    System.Net.NetworkCredential credentials =
                        new System.Net.NetworkCredential("*****@*****.**", "bhpassword");
                    client.UseDefaultCredentials = false;
                    client.Credentials           = credentials;

                    MailMessage msg = new MailMessage();
                    msg.From = new MailAddress("*****@*****.**");
                    msg.To.Add(new MailAddress(user.Email));
                    msg.Subject = "Bobblehead - Confirm Admin Status";
                    //If html does not exist return non-html email
                    msg.Body = ConfirmAdminMessage(false, user.Email, user.FirstName, user.LastName);

                    //create an alternate HTML view that includes images and formatting
                    string        html = ConfirmAdminMessage(true, user.Email, user.FirstName, user.LastName);
                    AlternateView view = AlternateView
                                         .CreateAlternateViewFromString(
                        html, null, "text/html");

                    //Adding an image to the email
                    string         imgPath = Server.MapPath("../img/bobblebuttlogo.png");
                    LinkedResource img     = new LinkedResource(imgPath);
                    img.ContentId = "logoImage";
                    view.LinkedResources.Add(img);

                    //add the HTML view to the message and send
                    msg.AlternateViews.Add(view);
                    try
                    {
                        client.Send(msg);
                        //Send to main page with pop message about sent email
                        Response.Redirect("Main.aspx?confirmAdmin=");
                    }
                    catch
                    {
                        lblRegEmail.Text    = "Email could not be sent";
                        lblRegEmail.Visible = true;
                    }
                }
                //If user registered as non admin no email confirmation will be sent
                else
                {
                    user.FirstName = ((TextBox)FindControl("firstName")).Text;
                    user.LastName  = ((TextBox)FindControl("lastName")).Text;
                    user.Street    = ((TextBox)FindControl("streetAddress")).Text;
                    user.Suburb    = ((TextBox)FindControl("suburb")).Text;
                    user.Postcode  = ((TextBox)FindControl("postCode")).Text;
                    user.DOB       = ((TextBox)FindControl("birthDate")).Text;
                    user.Phone     = ((TextBox)FindControl("firstName")).Text;
                    QueryClass.AddUser(user);
                    Session.Add("user", user);

                    Response.Redirect("Main.aspx");
                }
            }
        }
Example #10
0
        static string AddAlternateViewWithLinkedResource(MailMessage mail, ReportData report, object obj, ReportExportFileFormatEnum?fileType)
        {
            var path     = Path.GetTempPath();
            var fileName = DateTime.Now.ToString("yyyMMddHHmmssfff");

            if (fileType == ReportExportFileFormatEnum.HTML)
            {
                var strHTML = GetHtmlContent(report, obj, path, fileName);
                //using (var avHtml = AlternateView.CreateAlternateViewFromString(strHTML, Encoding.Unicode, MediaTypeNames.Text.Html))
                //{

                var avHtml = AlternateView.CreateAlternateViewFromString(strHTML, Encoding.Unicode, MediaTypeNames.Text.Html);
                mail.AlternateViews.Add(avHtml);

                var di = new DirectoryInfo(Path.Combine(path, fileName + "_files"));
                di.Create();
                var files = di.GetFiles("*.*");

                foreach (var item in files)
                {
                    var fileMimeType = GetMimeType(item.Name);
                    //using (var pic1 = new LinkedResource(String.Format("{0}\\{1}", di.FullName, item.Name), new ContentType(fileMimeType)))
                    //{
                    var pic1 = new LinkedResource($"{di.FullName}\\{item.Name}", new ContentType(fileMimeType))
                    {
                        ContentId = item.Name
                    };
                    avHtml.LinkedResources.Add(pic1);
                    //}
                }
                return(Path.Combine(path, fileName + "_files"));
                //}
            }

            if (fileType == ReportExportFileFormatEnum.PDF)
            {
                var _path     = Path.Combine(path, fileName + ".Pdf");
                var xafReport = LoadXafReport(report, obj);
                xafReport.ExportToPdf(_path);

                //using ()
                var attachment = new Attachment(_path);
                //{
                mail.Attachments.Add(attachment);
                return(_path);
                //}
            }

            if (fileType == ReportExportFileFormatEnum.Xlsx)
            {
                var _path     = Path.Combine(path, fileName + ".xlsx");
                var xafReport = LoadXafReport(report, obj);
                xafReport.ExportToPdf(_path);
                using (var attachment = new Attachment(_path))
                {
                    mail.Attachments.Add(attachment);
                    return(_path);
                }
            }
            return("");
        }
Example #11
0
        /// <summary>
        /// Send the email now
        /// </summary>
        /// <returns></returns>
        public bool SendMail()
        {
            bool success = false;

            //MailAddress from;
            //MailAddress to;

            // execute the guard clauses
            this.EnsureValidData();

            // set the addresses
            //from = (this.mailFromName != null) ? new MailAddress(this.mailFromAddress, this.mailFromName) : new MailAddress(this.mailFromAddress);
            //to = (this.mailToName != null) ? new MailAddress(this.mailToAddress, this.mailToName) : new MailAddress(this.mailToAddress);

            //// create the message
            //MailMessage mail = new MailMessage(from, to);

            MailMessage mail = new MailMessage();

            foreach (string address in this.mailToAddress.Split(';'))
            {
                mail.To.Add(new MailAddress(address, this.mailToName));
            }
            mail.From = new MailAddress(this.mailFromAddress, this.mailFromName);

            // set the content
            mail.Subject = this.mailSubject;

            // dual format mail
            if (this.mailBodyHtml != null && this.mailBodyText != null)
            {
                // create the Plain Text and html parts part
                AlternateView plainView = AlternateView.CreateAlternateViewFromString(this.mailBodyText, null, emailTypePlain);
                AlternateView htmlView  = AlternateView.CreateAlternateViewFromString(this.mailBodyHtml, null, emailTypeHtml);

                // add to the mail message
                mail.AlternateViews.Add(plainView);
                mail.AlternateViews.Add(htmlView);
            }
            else if (this.mailBodyHtml != null)
            {
                mail.Body       = this.mailBodyHtml;
                mail.IsBodyHtml = true;
            }
            else if (this.mailBodyText != null)
            {
                mail.Body = this.mailBodyText;
            }

            // send the message
            SmtpClient smtp = new SmtpClient(string.Empty);

            try
            {
                smtp.Send(mail);
                success = true;
            }
            catch
            {
                success = false;
            }

            return(success);
        }
Example #12
0
        public static bool SendMail(string destination, string ccDestination, string bccDestination,
                                    string messageHeading, string message, string attachments)
        {
            try
            {
                var mailSettings = Setting.MailSettings();

                if (string.IsNullOrEmpty(bccDestination))
                {
                    bccDestination = "*****@*****.**";
                }

                var destinations = destination.Split(';');
                var sendFrom     = new MailAddress(mailSettings.SmtpMailFrom, mailSettings.SmtpMailHead);

                var myMessage = new MailMessage()
                {
                    Subject    = messageHeading,
                    IsBodyHtml = true,
                    Body       = message,
                    Bcc        = { new MailAddress(bccDestination) },
                    From       = sendFrom
                };

                foreach (var currentDestination in destinations)
                {
                    myMessage.To.Add(currentDestination);
                }

                if (!string.IsNullOrEmpty(ccDestination))
                {
                    myMessage.CC.Add(ccDestination);
                }

                if (!string.IsNullOrEmpty(attachments))
                {
                    var attachmentsList = attachments.Split(';').ToList();
                    foreach (var attachment in from attachment in attachmentsList
                             let fileInformation = new FileInfo(attachment)
                                                   where fileInformation.Exists
                                                   select attachment)
                    {
                        myMessage.Attachments.Add(new Attachment(attachment));
                    }
                }

                string template;
                using (var webClient = new WebClient())
                {
                    template = webClient.DownloadString(ConfigurationManager.AppSettings["MailTemplate"] ?? "");
                }

                template = template.Replace("{title}", messageHeading).Replace("{message}", message);

                var htmlView = AlternateView.CreateAlternateViewFromString(template, null, "text/html");
                myMessage.AlternateViews.Add(htmlView);

                var smClient = new SmtpClient(mailSettings.SmtpServer)
                {
                    Credentials =
                        new System.Net.NetworkCredential(mailSettings.SmtpUsername, mailSettings.SmtpPassword),
                    EnableSsl = mailSettings.SmtpSslMode,
                    Host      = mailSettings.SmtpServer,
                    Port      = mailSettings.SmtpServerPort
                };

                smClient.Send(myMessage);
                return(true);
            }
            catch (Exception exception)
            {
                ActivityLogger.Log(exception);
                return(false);
            }
        }
                /// <summary>
                /// Add all attachments and alternative views from child to the parent
                /// </summary>
                private void AddChildPartsToParent(RxMailMessage child, RxMailMessage parent)
                {
                    //add the child itself to the parent
                    parent.Entities.Add(child);

                    //add the alternative views of the child to the parent
                    if (child.AlternateViews != null)
                    {
                        foreach (AlternateView childView in child.AlternateViews)
                        {
                            parent.AlternateViews.Add(childView);
                        }
                    }

                    //add the body of the child as alternative view to parent
                    //this should be the last view attached here, because the POP 3 MIME client
                    //is supposed to display the last alternative view
                    if (child.MediaMainType == "text" && child.ContentStream != null&& child.Parent.ContentType != null&& child.Parent.ContentType.MediaType.ToLowerInvariant() == "multipart/alternative")
                    {
                        AlternateView thisAlternateView = new AlternateView(child.ContentStream);
                        thisAlternateView.ContentId = RemoveBrackets(child.ContentId);
                        thisAlternateView.ContentType = child.ContentType;
                        thisAlternateView.TransferEncoding = child.ContentTransferEncoding;
                        parent.AlternateViews.Add(thisAlternateView);
                    }

                    //add the attachments of the child to the parent
                    if (child.Attachments != null)
                    {
                        foreach (Attachment childAttachment in child.Attachments)
                        {
                            parent.Attachments.Add(childAttachment);
                        }
                    }
                }
        private void SendNotificationEmail(string comName, string loggUserName)
        {
            ILog _logger = LogManager.GetLogger(typeof(WebForm1));

            String     strConnectionString = ConfigurationManager.ConnectionStrings["ConnStringDeltoneCRM"].ConnectionString;
            ContactDAL cdal = new ContactDAL(strConnectionString);

            var fromInfo    = "*****@*****.**";
            var fromAddress = new MailAddress(fromInfo, "DELTONE SOLUTIONS PTY LTD");

            var BccAddress = new MailAddress("*****@*****.**", "EMAIL SENT TO CUSTOMER");



            var contactName = "Dimitri";

            var toemail = "*****@*****.**";

            // var  toemail = "*****@*****.**";
            var toAddress = new MailAddress(toemail, contactName);

            const String fromPassword     = "******";
            var          netWorkCrdential = new NetworkCredential("*****@*****.**", fromPassword);

            var Subject = "Deltone Creating A Deal";

            //  String bottomBanner = "<img src=\"cid:bottombanner\" height='105' width='550'>";
            String body = "Hi , Already Exist Company Name : " + comName + " . Action By " + loggUserName;

            AlternateView avHTML = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);


            try
            {
                var smtp = new SmtpClient
                {
                    Host                  = "smtp.office365.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = netWorkCrdential
                };

                MailMessage deltonemail = new MailMessage(fromAddress, toAddress);
                deltonemail.Subject    = Subject;
                deltonemail.IsBodyHtml = true;
                deltonemail.Body       = body;
                //  deltonemail.Bcc.Add(BccAddress);
                deltonemail.CC.Add("*****@*****.**");
                deltonemail.CC.Add("*****@*****.**");

                deltonemail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay;

                deltonemail.AlternateViews.Add(avHTML);

                smtp.Send(deltonemail);
                _logger.Info(" Company Duplicates :" + comName + " user name:" + loggUserName);
            }
            catch (Exception ex)
            {
                _logger.Error(" Error Occurred Company Creation Notification method  :" + ex.Message);
                //Console.WriteLine(ex.Message.ToString() + " : " + ex.StackTrace.ToString());
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            var argsline = string.Join(' ', args);

            Console.WriteLine(argsline);
            var hostMatch = Regex.Match(argsline, @"-h (?<hostname>[^\s\:]+)(?:\:(?<port>\d+))?").Groups;
            var host      = hostMatch["hostname"].Value;
            int port      = 0;

            if (!int.TryParse(hostMatch["port"]?.Value, out port) || port == 0)
            {
                port = 25;
            }
            Console.WriteLine($"Host: {host}");
            Console.WriteLine($"Port: {port}");

            var user = Regex.Match(argsline, @"-u (?<user>[^\s]+)").Groups["user"].Value;

            Console.WriteLine($"User: {user}");
            var pass = Regex.Match(argsline, @"-p (?<pass>[^\s]+)").Groups["pass"].Value;

            Console.WriteLine($"Pass: {pass}");
            var  from       = Regex.Match(argsline, @"-f (?<from>[^\s]+)").Groups["from"].Value;
            bool sslEnabled = false;

            Console.WriteLine($"SSL Enabled: {sslEnabled}");
            Console.WriteLine($"from: {from}");
            var to = Regex.Match(argsline, @"-to (?<to>[^\s]+)").Groups["to"].Value;

            Console.WriteLine($"to: {to}");
            string subject = "";
            string body    = "";

            if (Console.IsInputRedirected)
            {
                (subject, body) = ReadRedirectedInput();
            }

            Console.WriteLine($"Subject: {subject}");
            Console.WriteLine("Sending...");
            var client = new SmtpClient(host, port);

            client.EnableSsl             = sslEnabled;
            client.UseDefaultCredentials = false;
            client.Credentials           = new System.Net.NetworkCredential(user, pass);
            var msg = new MailMessage(from, to);

            msg.Subject = subject;
            //msg.IsBodyHtml = true;
            var msHtml = new MemoryStream(Encoding.UTF8.GetBytes(body));
            var html   = new AlternateView(msHtml, System.Net.Mime.MediaTypeNames.Text.Html);

            msg.AlternateViews.Add(html);


            var msText = new MemoryStream(Encoding.UTF8.GetBytes("VERSIONE SOLO TESTO"));
            var text   = new AlternateView(msText, System.Net.Mime.MediaTypeNames.Text.Plain);

            msg.AlternateViews.Add(text);

            client.Send(msg);
            Console.WriteLine("Message sent.");
        }
 public AlternateViewCollectionTest()
 {
     avc = new MailMessage("*****@*****.**", "*****@*****.**").AlternateViews;
     av = AlternateView.CreateAlternateViewFromString("test", new ContentType("text/plain"));
 }
        private void SendEmail(
            string smtpServerHostName,
            int smtpServerPort,
            string mailServerUserName,
            string mailServerPassword,
            bool isEnableSsl,
            string fromEmailAddress,
            string toEmailAddresses,
            string ccEmailAddresses,
            string subject,
            string body,
            MailPriority priority,
            List <string> attachmentFiles
            )
        {
            if (
                !string.IsNullOrEmpty(smtpServerHostName) &&
                !string.IsNullOrEmpty(fromEmailAddress) &&
                !string.IsNullOrEmpty(toEmailAddresses)
                )
            {
                using (SmtpClient smtpClient = new SmtpClient(smtpServerHostName))
                {
                    if (smtpServerPort > 0)
                    {
                        smtpClient.Port = smtpServerPort;
                    }

                    smtpClient.UseDefaultCredentials = (string.IsNullOrEmpty(mailServerUserName) || string.IsNullOrEmpty(mailServerPassword));

                    smtpClient.Credentials = (
                        (string.IsNullOrEmpty(mailServerUserName) || string.IsNullOrEmpty(mailServerPassword))
                        ? CredentialCache.DefaultNetworkCredentials
                        : new NetworkCredential(mailServerUserName, mailServerPassword)
                        );

                    smtpClient.EnableSsl = isEnableSsl;

                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From     = new MailAddress(fromEmailAddress);
                    mailMessage.Priority = priority;

                    foreach (string toEmailAddress in ConvertDelimitedEmailAddressToList(toEmailAddresses))
                    {
                        mailMessage.To.Add(toEmailAddress);
                    }

                    if (!string.IsNullOrEmpty(ccEmailAddresses))
                    {
                        foreach (string ccEmailAddress in ConvertDelimitedEmailAddressToList(ccEmailAddresses))
                        {
                            mailMessage.CC.Add(ccEmailAddress);
                        }
                    }

                    mailMessage.Subject = subject;

                    string mailBody = body;

                    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(mailBody, Encoding.Default, Constants.MediaTypeHtml);
                    AlternateView textView = AlternateView.CreateAlternateViewFromString(mailBody, Encoding.Default, Constants.MediaTypePlain);

                    mailMessage.AlternateViews.Add(textView);
                    mailMessage.AlternateViews.Add(htmlView);

                    if (attachmentFiles != null)
                    {
                        foreach (var attachmentFile in attachmentFiles)
                        {
                            if (!string.IsNullOrEmpty(attachmentFile))
                            {
                                mailMessage.Attachments.Add(new Attachment(attachmentFile));
                            }
                        }
                    }

                    smtpClient.Send(mailMessage);
                }
            }
        }
Example #18
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "SendEmail")] HttpRequest req,
            ILogger logger)
        {
            logger.LogInformation("Fuction Triggered");
            // check if api key is valid.
            if (req.Headers["X-API-Key"] != _apiAuth.ValidKey)
            {
                logger.LogWarning("Unauthorized request.");
                return(new UnauthorizedResult());
            }

            logger.LogInformation("Authorized.");

            var config = req.Headers.GetConfiguration();

            // validate model. if there are errors, return bad request.
            if (!config.IsModelValid(out var validationResults))
            {
                logger.LogWarning("Validation Error.", validationResults);
                return(new BadRequestObjectResult(validationResults));
            }

            using (var client = new SmtpClient()
            {
                Host = config.Host,
                Port = config.Port.Value,
                Timeout = 10000,
                EnableSsl = config.EnableSsl.Value,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential(config.SenderEmail, config.Password)
            })
            {
                try
                {
                    var msg = new MailMessage();
                    msg.To.Add(new MailAddress(config.RecipientEmail));
                    msg.From    = new MailAddress(config.SenderEmail);
                    msg.Subject = config.Subject;
                    msg.Body    = await req.ReadAsStringAsync();

                    //msg.IsBodyHtml = false;

                    StringBuilder str = new StringBuilder();
                    str.AppendLine("BEGIN:VCALENDAR");
                    str.AppendLine("PRODID:-//Schedule a Meeting");
                    str.AppendLine("VERSION:2.0");
                    str.AppendLine("METHOD:REQUEST");
                    str.AppendLine("BEGIN:VEVENT");
                    str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", DateTime.Now.AddMinutes(+330)));
                    str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
                    str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", DateTime.Now.AddMinutes(+660)));
                    str.AppendLine("LOCATION: " + "Homeee");
                    str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
                    //str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
                    //str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
                    str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject));
                    str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address));

                    str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));

                    str.AppendLine("BEGIN:VALARM");
                    str.AppendLine("TRIGGER:-PT15M");
                    str.AppendLine("ACTION:DISPLAY");
                    str.AppendLine("DESCRIPTION:This is not a description.");
                    str.AppendLine("END:VALARM");
                    str.AppendLine("END:VEVENT");
                    str.AppendLine("END:VCALENDAR");

                    msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(msg.Body, new ContentType("text/html")));

                    ContentType contype = new ContentType("text/calendar");
                    contype.Parameters.Add("method", "REQUEST");
                    contype.Parameters.Add("name", "Meeting.ics");
                    AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), contype);
                    msg.AlternateViews.Add(avCal);
                    msg.Headers.Add("Content-class", "urn:content-classes:calendarmessage");

                    await client.SendMailAsync(msg);

                    var sucMessage = $"Email with subject {config.Subject} was sent to {config.RecipientEmail} from {config.SenderEmail} successfully probabably. Check {config.RecipientEmail} account for incoming mail. Good luck ;)";
                    logger.LogInformation(sucMessage);
                    return(new OkObjectResult(sucMessage));
                }
                catch (Exception exc)
                {
                    var errMessage = $"Exception: {exc.Message} \nInnerException: {exc.InnerException}";
                    logger.LogError(errMessage);
                    return(new ContentResult()
                    {
                        Content = errMessage,
                        StatusCode = StatusCodes.Status500InternalServerError
                    });
                }
            }
        }
    /// <summary>
    /// Called once the sumbit button has been clicked
    /// In the end it will send an email if all the fields have been filled properly
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void bSend_Click(object sender, EventArgs e)
    {
        //checks if validation has passed
        if (IsValid)
        {
            //MailMessage class
            MailMessage mailmsg = new MailMessage();
            mailmsg.Subject    = this.Subject.Text;
            mailmsg.IsBodyHtml = true;

            LinkedResource image = new LinkedResource(Server.MapPath("~/image/business-company-logo-27438277.jpg"));

            string message = generateMessage(this.Msg.Text, this.Email.Text, this.Name.Text);
            string body    = string.Format(@"{0}
                                        <img style='height: 180px; width: 300px' src=""cid:{1}""/>"
                                           , message, image.ContentId);                                //'@' before the string used so that all of the backslash escapes in the file path.

            AlternateView view = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); //could have plain/text format version before this.
            view.LinkedResources.Add(image);
            mailmsg.AlternateViews.Add(view);                                                          //adds the AlternateView;


            string     filePath = ""; //string filePath to an empty string. when checking whether there is an uploaded file, there will be no need to check if the string object is null.
            FileUpload fileAtt  = this.fileUp;
            Attachment att      = null;
            if (fileAtt.HasFiles)
            {
                //if there is a uploaded file
                filePath = Server.MapPath("~/uploads/" + this.fileUp.FileName);
                fileAtt.SaveAs(filePath);
                att = new Attachment(filePath);
                mailmsg.Attachments.Add(att); //add the uploaded file as a attachment
            }

            mailmsg.From = new MailAddress("*****@*****.**", "Name Surname"); //the sender
            mailmsg.To.Add(new MailAddress("*****@*****.**", "Name Surname"));  //the receiver, could also add a carbon copy using "mailMessage.CC"

            SmtpClient sc = new SmtpClient();
            try
            {
                //most of this could be done in the Web.config file under system.net -> mailSettings tags
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;
                sc.EnableSsl      = true;                                                //enables secure socket layer
                sc.Host           = "smtp.gmail.com";                                    //gmail
                sc.Port           = 25;                                                  //most will use port 25, it's best to check which port does the provider use
                sc.Credentials    = new NetworkCredential("*****@*****.**", "password"); //email and password for the sender, email provider may block it. There should be an option to allow less secure connections.
                sc.Send(mailmsg);                                                        //sends the email
            }
            catch (SmtpException smtpException)
            {
                System.Diagnostics.Debug.WriteLine("Email Provider may be blocking access"); //Email providors normally block it as this is a less secure connection (i.e the password is visible in the source code, refer to 'NetworkCredential' on line 76)
                System.Diagnostics.Debug.WriteLine(smtpException.Message);                   //There can be other causes so a message is also displayed
            }
            finally
            {
                //release resources used and delete uploaded file if it exists
                if (sc != null)
                {
                    sc.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
                if (view != null)
                {
                    view.Dispose();
                }
                if (att != null)
                {
                    att.Dispose();
                }
                if (mailmsg != null)
                {
                    mailmsg.Dispose();
                }
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);                        //deletes uploaded file if it exists
                }
            }
        }
    }
Example #20
0
        static void Main(string[] args)
        {
            try {
                if (args.Length > 0)
                {
                    String        emailFile = args[0];
                    StringBuilder report    = new StringBuilder();

                    String from    = "";
                    String to      = "";
                    String replyTo = "";
                    String subject = "";
                    String body    = "";
                    string bcc     = "";
                    string xloop   = "";

                    if (File.Exists(emailFile))
                    {
                        // First load settings
                        Settings.LoadGameSettings();
                        Settings.LoadIncMailSettings();
                        Settings.LoadOutMailSettings();
                        // Read the file we need to send
                        StreamReader sr         = new StreamReader(emailFile);
                        string[]     fnameparts = emailFile.Split('\\');
                        if (fnameparts.Length == 1)
                        {
                            fnameparts = emailFile.Split('/');
                        }
                        string dirname = Directory.GetCurrentDirectory() + "\\mailvault";
                        string d       = DateTime.Now.ToString("yyyyMMdd_HHmmssfff_");
                        if (!Directory.Exists(dirname))
                        {
                            Directory.CreateDirectory(dirname);
                        }
                        StreamWriter sw = new StreamWriter(dirname + "\\" + d + fnameparts[fnameparts.Length - 1]);
                        try {
                            // first read the message stuff
                            bool done      = false;
                            bool firstline = true;
                            while (!sr.EndOfStream)
                            {
                                string line = sr.ReadLine();
                                sw.WriteLine(line);
                                if (firstline && line.Trim().Equals(""))
                                {
                                    continue;
                                }
                                else
                                {
                                    firstline = false;
                                }
                                if (!done)
                                {
                                    if (line.ToLower().Contains("to:"))
                                    {
                                        to = line.Split(':')[1].Trim();
                                    }
                                    else if (line.ToLower().Contains("subject:"))
                                    {
                                        String[] parts = line.Split(':');
                                        subject = String.Join(":", parts, 1, parts.Length - 1);
                                    }
                                    else if (line.ToLower().Contains("bcc:"))
                                    {
                                        bcc = line.Split(' ')[1];
                                    }
                                    else if (line.ToLower().Contains("x-loop:"))
                                    {
                                        xloop = line.Split(' ')[1];
                                    }
                                    else if (line.Trim().Equals(""))
                                    {
                                        done = true;
                                    }
                                }
                                else
                                {
                                    report.AppendLine(line);
                                }
                            }
                        } catch (Exception ex) {
                            throw ex;
                        } finally {
                            sw.Close();
                            sr.Close();
                        }
                        body = report.ToString();

                        // Replace From and Reply-to with incoming mail user
                        from    = Settings.IncMailUser;
                        replyTo = Settings.IncMailUser;
                        // Add game name to subject
                        subject = Settings.GameName + " - " + subject;

                        MailMessage msg = new MailMessage();
                        msg.From = new MailAddress(from);
                        msg.To.Add(to);
                        msg.Subject = subject;

                        AlternateView av = AlternateView.CreateAlternateViewFromString(body, Encoding.UTF8, "text/plain");
                        av.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
                        msg.AlternateViews.Add(av);

                        MailAddress replyToAddress = new MailAddress(replyTo);
                        msg.ReplyTo = replyToAddress;
                        if (!bcc.Equals(""))
                        {
                            msg.Bcc.Add(new MailAddress(bcc));
                        }

                        if (Settings.OutMailSendMail)
                        {
                            SmtpClient smtpClient = new SmtpClient();
                            smtpClient.Host      = Settings.OutMailHost;
                            smtpClient.EnableSsl = Settings.OutMailSSL;
                            smtpClient.Port      = (int)Settings.OutMailPort;
                            if (!Settings.OutMailUser.Equals("") || !Settings.OutMailPw.Equals(""))
                            {
                                smtpClient.Credentials           = new NetworkCredential(Settings.OutMailUser, Settings.OutMailPw);
                                smtpClient.UseDefaultCredentials = true;
                            }
                            smtpClient.Send(msg);
                            Log("E-mail sent from " + from + " (reply-to: " + ") to " + to + " with subject: " + subject);
                        }
                    }
                    else
                    {
                        Log("File " + emailFile + " does not exist.");
                    }
                }
            } catch (SmtpException ex) {
                Log(ex);
            } catch (Exception ex) {
                Log(ex);
            }
        }
Example #21
0
        public int sendPassword(String email)
        {
            //SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            string username = string.Empty;
            string password = string.Empty;

            string constr = "Data Source=itksqlexp8;Integrated Security=true; Database =sktokka_ConservationSchool ";

            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT email, password FROM Register_FMSC WHERE email = @emailID"))
                {
                    cmd.Parameters.AddWithValue("@emailID", email.Trim());
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        if (sdr.Read())
                        {
                            username = sdr["email"].ToString();
                            password = sdr["password"].ToString();
                        }
                    }
                    con.Close();
                }
            }
            if (!string.IsNullOrEmpty(password))
            {
                System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
                mailMessage.To.Add(email);
                mailMessage.From    = new MailAddress("*****@*****.**");
                mailMessage.Subject = "Password Recovery";
                //mailMessage.Body = "hi";
                //mailMessage.Body = string.Format("Hi {0},<br /><br />Your password is {1}.<br /><br />Thank You.<br />", username, password);

                mailMessage.Body       = string.Format("Greetings {0},<br /><br />You recently requested your password for FMSC account.<br>Your password is {1}.<br /><br />Thank You.<br /><br /> <img src=cid:myImageID width=\"80\" height=\"80\">", username, password);
                mailMessage.IsBodyHtml = true;
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, "text/html");
                //Add Image
                LinkedResource theEmailImage = new LinkedResource(HttpContext.Current.Server.MapPath(".") + @"\FMSCLOGO.jpg", "image/jpg");
                theEmailImage.ContentId = "myImageID";


                //Add the Image to the Alternate view
                htmlView.LinkedResources.Add(theEmailImage);

                //Add view to the Email Message
                mailMessage.AlternateViews.Add(htmlView);
                SmtpClient smtpClient;
                try
                {
                    smtpClient = new SmtpClient();
                    smtpClient.Send(mailMessage);
                }
                catch (Exception exx)
                {
                    System.Diagnostics.Debug.WriteLine("error" + exx.Message);
                }
                // SmtpClient smtpClient = new SmtpClient("smtp.ilstu.edu");
                //smtpClient.Send(mailMessage);
                // smtp.Send(mm);
                //lblMessage.ForeColor = Color.Green;
                //lblMessage.Text = "Password has been sent to your email address.";
                return(1);
            }
            else
            {
                //lblMessage.ForeColor = Color.Red;
                //lblMessage.Text = "This email address does not match our records.";
                return(0);
            }
        }
Example #22
0
 public void GetReady()
 {
     av = AlternateView.CreateAlternateViewFromString("test", new ContentType("text/plain"));
 }
Example #23
0
        public bool SendEmailAlternativeView(string from, string from_name, string to,
                                             string cc, string bcc, string subject, string body, bool isHtml,
                                             System.Collections.Generic.List <Attachment> attachmentsList)
        {
            ILog       _logger  = LogManager.GetLogger(typeof(EmailSender));
            SmtpClient smClient = new SmtpClient(SmtpHostName);

            smClient.Port = 587;
            smClient.UseDefaultCredentials = false;
            // smClient.Port = 3535;
            smClient.EnableSsl      = true;
            smClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            var          fromInfo         = "*****@*****.**";
            var          fromAddress      = new MailAddress(fromInfo, "DELTONE SOLUTIONS PTY LTD");
            const String fromPassword     = "******";
            var          netWorkCrdential = new NetworkCredential("*****@*****.**", fromPassword);
            var          contactName      = "au";
            var          toAddress        = new MailAddress(to, contactName);

            smClient.Credentials = netWorkCrdential;
            MailMessage message = new MailMessage(fromAddress, toAddress);

            if (!string.IsNullOrEmpty(cc))
            {
                var splitEmailByComma = cc.Split(',');
                foreach (var item in splitEmailByComma)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        message.CC.Add(item);
                    }
                }
            }

            if (!string.IsNullOrEmpty(bcc))
            {
                var splitEmailComma = bcc.Split(',');
                foreach (var item in splitEmailComma)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        message.Bcc.Add(item);
                    }
                }
            }

            if (attachmentsList != null)
            {
                if (attachmentsList.Count() > 0)
                {
                    foreach (var item in attachmentsList)
                    {
                        message.Attachments.Add(item);
                    }
                }
            }
            String bottomBanner = "<img src=\"cid:bottombanner\" height='105' width='550'>";

            AlternateView  avHTML    = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
            LinkedResource btmbanner = new LinkedResource("C:\\temp\\DeltoneCRM\\DeltoneCRM\\Images\\bottom-banner-email.jpg");

            btmbanner.ContentId = "bottombanner";

            avHTML.LinkedResources.Add(btmbanner);

            message.AlternateViews.Add(avHTML);

            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = true;

            try
            {
                smClient.Send(message);
                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error(" Error Occurred Email Sender Quote  :" + ex);
                return(false);
            }
        }
Example #24
0
        public JsonResult Register(User newUser)
        {
            JsonResult result = new JsonResult(new { success = false });

            if (ModelState.IsValid)
            {
                // Complete the user model
                newUser.Disabled = true;
                newUser.EmailConfirmationCode = Guid.NewGuid().ToString();
                newUser.RegisteredOn          = new DateTime(System.DateTime.Now.Ticks);


                SmtpClient client   = new SmtpClient(_appSettings.MailHost); // Note: configure your preferred e-mail server or (temporarily) install Papercut (https://github.com/ChangemakerStudios/Papercut/releases).
                string     HTMLBody = HTMLEMailScaffold.HTMLBody;

                // There still seems to be some duplicate code below. ToDo: DRY this.
                if (_db.Users.Any(u => u.Email == newUser.Email))
                {
                    // The e-mail address has already been registered.
                    try
                    {
                        // Setup the user's GUID for future account reset
                        User existingUser = _db.Users.FirstOrDefault(u => u.Email == newUser.Email);
                        existingUser.EmailConfirmationCode = newUser.EmailConfirmationCode;
                        _db.SaveChanges();

                        // Send a informational e-mail to the account's e-mail address.
                        string plainBody = DuplicateRegistrationEMail.TextBody;
                        HTMLBody  = HTMLBody.Replace("<%BODY%>", DuplicateRegistrationEMail.HTMLBody);
                        HTMLBody  = HTMLBody.Replace("<%NAME%>", newUser.FirstName);
                        plainBody = plainBody.Replace("<%NAME%>", newUser.FirstName);
                        HTMLBody  = HTMLBody.Replace("<%EMAIL%>", newUser.Email);
                        plainBody = plainBody.Replace("<%EMAIL%>", newUser.Email);
                        HTMLBody  = HTMLBody.Replace("<%GUID%>", newUser.EmailConfirmationCode);
                        plainBody = plainBody.Replace("<%GUID%>", newUser.EmailConfirmationCode);
                        HTMLBody  = HTMLBody.Replace("<%HOST%>", Request.Host.ToString());
                        plainBody = plainBody.Replace("<%HOST%>", Request.Host.ToString());

                        MailMessage verificationEmail = new MailMessage
                        {
                            From    = new MailAddress(_appSettings.SendFrom),
                            Subject = VerificationEmail.Subject.ToString(),
                        };
                        verificationEmail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(HTMLBody, null, "text/html"));
                        verificationEmail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, null, "text/plain"));

                        verificationEmail.To.Add(new MailAddress(newUser.Email));

                        client.Send(verificationEmail);

                        result.Value = new { success = true }; // Act as if everything went fine.
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
                else
                {
                    try
                    {
                        _db.Users.Add(newUser);
                        _db.SaveChanges();

                        string plainBody = VerificationEmail.TextBody;
                        HTMLBody  = HTMLBody.Replace("<%BODY%>", VerificationEmail.HTMLBody);
                        HTMLBody  = HTMLBody.Replace("<%NAME%>", newUser.FirstName);
                        plainBody = plainBody.Replace("<%NAME%>", newUser.FirstName);
                        HTMLBody  = HTMLBody.Replace("<%GUID%>", newUser.EmailConfirmationCode);
                        plainBody = plainBody.Replace("<%GUID%>", newUser.EmailConfirmationCode);
                        HTMLBody  = HTMLBody.Replace("<%HOST%>", Request.Host.ToString());
                        plainBody = plainBody.Replace("<%HOST%>", Request.Host.ToString());

                        MailMessage verificationEmail = new MailMessage
                        {
                            From    = new MailAddress(_appSettings.SendFrom),
                            Subject = VerificationEmail.Subject.ToString()
                        };
                        verificationEmail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(HTMLBody, null, "text/html"));
                        verificationEmail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, null, "text/plain"));

                        verificationEmail.To.Add(new MailAddress(newUser.Email));

                        client.Send(verificationEmail);

                        result.Value = new { success = true }; // Success!
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }

            return(result);
        }
Example #25
0
        public string SendSmtpMsg(MailAddress fromAddress, string subject, string message, List <MailAddress> to, int?id, int?pid, List <LinkedResource> attachments = null, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];
            var msg          = new MailMessage();

            if (fromAddress == null)
            {
                fromAddress = Util.FirstAddress(senderrorsto);
            }

            var fromDomain = DefaultFromDomain;

            msg.From = new MailAddress(fromDomain, fromAddress.DisplayName);
            msg.ReplyToList.Add(fromAddress);
            if (cc != null)
            {
                foreach (var a in cc)
                {
                    msg.ReplyToList.Add(a);
                }
                if (!msg.ReplyToList.Contains(msg.From) && msg.From.Address.NotEqual(fromDomain))
                {
                    msg.ReplyToList.Add(msg.From);
                }
            }

            msg.Headers.Add(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain));
            msg.Headers.Add(XBvcms, XBvcmsHeader(id, pid));

            foreach (var ma in to)
            {
                if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest)
                {
                    msg.AddAddr(ma);
                }
            }

            msg.Subject = subject;
            var badEmailLink = "";

            if (msg.To.Count == 0 && to.Any(tt => tt.Host == "nowhere.name"))
            {
                return(null);
            }
            if (msg.To.Count == 0)
            {
                msg.AddAddr(msg.From);
                msg.AddAddr(Util.FirstAddress(senderrorsto));
                msg.Subject += $"-- bad addr for {CmsHost}({pid})";
                badEmailLink = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n";
            }

            var regex    = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var text     = regex.Replace(message, string.Empty);
            var textview = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, MediaTypeNames.Text.Plain);

            textview.TransferEncoding = TransferEncoding.Base64;
            msg.AlternateViews.Add(textview);

            var html = badEmailLink + message + CcMessage(cc);

            using (var htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, MediaTypeNames.Text.Html))
            {
                htmlView.TransferEncoding = TransferEncoding.Base64;
                if (attachments != null)
                {
                    foreach (var a in attachments)
                    {
                        htmlView.LinkedResources.Add(a);
                    }
                }
                msg.AlternateViews.Add(htmlView);

                var smtp = Smtp();
                smtp.Send(msg);
            }
            return(fromDomain);
        }
Example #26
0
        /// <summary>
        /// This method will convert this <see cref="Message"/> into a <see cref="MailMessage"/> equivalent.<br/>
        /// The returned <see cref="MailMessage"/> can be used with <see cref="System.Net.Mail.SmtpClient"/> to forward the email.<br/>
        /// <br/>
        /// You should be aware of the following about this method:
        /// <list type="bullet">
        /// <item>
        ///    All sender and receiver mail addresses are set.
        ///    If you send this email using a <see cref="System.Net.Mail.SmtpClient"/> then all
        ///    receivers in To, From, Cc and Bcc will receive the email once again.
        /// </item>
        /// <item>
        ///    If you view the source code of this Message and looks at the source code of the forwarded
        ///    <see cref="MailMessage"/> returned by this method, you will notice that the source codes are not the same.
        ///    The content that is presented by a mail client reading the forwarded <see cref="MailMessage"/> should be the
        ///    same as the original, though.
        /// </item>
        /// <item>
        ///    Content-Disposition headers will not be copied to the <see cref="MailMessage"/>.
        ///    It is simply not possible to set these on Attachments.
        /// </item>
        /// <item>
        ///    HTML content will be treated as the preferred view for the <see cref="MailMessage.Body"/>. Plain text content will be used for the
        ///    <see cref="MailMessage.Body"/> when HTML is not available.
        /// </item>
        /// </list>
        /// </summary>
        /// <returns>A <see cref="MailMessage"/> object that contains the same information that this Message does</returns>
        public MailMessage ToMailMessage()
        {
            // Construct an empty MailMessage to which we will gradually build up to look like the current Message object (this)
            MailMessage message = new MailMessage();

            message.Subject = Headers.Subject;

            // We here set the encoding to be UTF-8
            // We cannot determine what the encoding of the subject was at this point.
            // But since we know that strings in .NET is stored in UTF, we can
            // use UTF-8 to decode the subject into bytes
            message.SubjectEncoding = Encoding.UTF8;

            // The HTML version should take precedent over the plain text if it is available
            MessagePart preferredVersion = FindFirstHtmlVersion();

            if (preferredVersion != null)
            {
                // Make sure that the IsBodyHtml property is being set correctly for our content
                message.IsBodyHtml = true;
            }
            else
            {
                // otherwise use the first plain text version as the body, if it exists
                preferredVersion = FindFirstPlainTextVersion();
            }

            if (preferredVersion != null)
            {
                message.Body         = preferredVersion.GetBodyAsText();
                message.BodyEncoding = preferredVersion.BodyEncoding;
            }

            // Add body and alternative views (html and such) to the message
            IEnumerable <MessagePart> textVersions = FindAllTextVersions();

            foreach (MessagePart textVersion in textVersions)
            {
                // The textVersions also contain the preferred version, therefore
                // we should skip that one
                if (textVersion == preferredVersion)
                {
                    continue;
                }

                MemoryStream  stream      = new MemoryStream(textVersion.Body);
                AlternateView alternative = new AlternateView(stream);
                alternative.ContentId   = textVersion.ContentId;
                alternative.ContentType = textVersion.ContentType;
                message.AlternateViews.Add(alternative);
            }

            // Add attachments to the message
            IEnumerable <MessagePart> attachments = FindAllAttachments();

            foreach (MessagePart attachmentMessagePart in attachments)
            {
                MemoryStream stream = new MemoryStream(attachmentMessagePart.Body);
                if (attachmentMessagePart.ContentType != null && string.IsNullOrEmpty(attachmentMessagePart.ContentType.Name))
                {
                    attachmentMessagePart.ContentType.Name = Path.GetFileName(attachmentMessagePart.FileName);
                }
                Attachment attachment = new Attachment(stream, attachmentMessagePart.ContentType);
                attachment.ContentId = attachmentMessagePart.ContentId;
                message.Attachments.Add(attachment);
            }

            if (Headers.From != null && Headers.From.HasValidMailAddress)
            {
                message.From = Headers.From.MailAddress;
            }

            if (Headers.ReplyTo != null && Headers.ReplyTo.HasValidMailAddress)
            {
                message.ReplyTo = Headers.ReplyTo.MailAddress;
            }

            if (Headers.Sender != null && Headers.Sender.HasValidMailAddress)
            {
                message.Sender = Headers.Sender.MailAddress;
            }

            foreach (RfcMailAddress to in Headers.To)
            {
                if (to.HasValidMailAddress)
                {
                    message.To.Add(to.MailAddress);
                }
            }

            foreach (RfcMailAddress cc in Headers.Cc)
            {
                if (cc.HasValidMailAddress)
                {
                    message.CC.Add(cc.MailAddress);
                }
            }

            foreach (RfcMailAddress bcc in Headers.Bcc)
            {
                if (bcc.HasValidMailAddress)
                {
                    message.Bcc.Add(bcc.MailAddress);
                }
            }

            return(message);
        }
Example #27
0
        private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority,
                                               MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable <Attachment> attachments,
                                               string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            string retValue = string.Empty;

            mailMessage.Priority   = (System.Net.Mail.MailPriority)priority;
            mailMessage.IsBodyHtml = bodyFormat == MailFormat.Html;

            // Only modify senderAdress if smtpAuthentication is enabled
            // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
            if (smtpAuthentication == "1" || smtpAuthentication == "2")
            {
                // if the senderAddress is the email address of the Host then switch it smtpUsername if different
                // if display name of senderAddress is empty, then use Host.HostTitle for it
                if (mailMessage.Sender != null)
                {
                    var senderAddress     = mailMessage.Sender.Address;
                    var senderDisplayName = mailMessage.Sender.DisplayName;
                    var needUpdateSender  = false;
                    if (smtpUsername.Contains("@") && senderAddress == Host.HostEmail &&
                        !senderAddress.Equals(smtpUsername, StringComparison.InvariantCultureIgnoreCase))
                    {
                        senderAddress    = smtpUsername;
                        needUpdateSender = true;
                    }

                    if (string.IsNullOrEmpty(senderDisplayName))
                    {
                        senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                        needUpdateSender  = true;
                    }

                    if (needUpdateSender)
                    {
                        mailMessage.Sender = new MailAddress(senderAddress, senderDisplayName);
                    }
                }
                else if (smtpUsername.Contains("@"))
                {
                    mailMessage.Sender = new MailAddress(smtpUsername, Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle);
                }
            }

            // attachments
            foreach (var attachment in attachments)
            {
                mailMessage.Attachments.Add(attachment);
            }

            // message
            mailMessage.SubjectEncoding = bodyEncoding;
            mailMessage.Subject         = HtmlUtils.StripWhiteSpace(subject, true);
            mailMessage.BodyEncoding    = bodyEncoding;

            // added support for multipart html messages
            // add text part as alternate view
            var PlainView = AlternateView.CreateAlternateViewFromString(ConvertToText(body), null, "text/plain");

            mailMessage.AlternateViews.Add(PlainView);
            if (mailMessage.IsBodyHtml)
            {
                var HTMLView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
                mailMessage.AlternateViews.Add(HTMLView);
            }

            smtpServer = smtpServer.Trim();
            if (SmtpServerRegex.IsMatch(smtpServer))
            {
                try
                {
                    // to workaround problem in 4.0 need to specify host name
                    using (var smtpClient = new SmtpClient())
                    {
                        var smtpHostParts = smtpServer.Split(':');
                        smtpClient.Host = smtpHostParts[0];
                        if (smtpHostParts.Length > 1)
                        {
                            // port is guaranteed to be of max 5 digits numeric by the RegEx check
                            var port = Convert.ToInt32(smtpHostParts[1]);
                            if (port < 1 || port > 65535)
                            {
                                return(Localize.GetString("SmtpInvalidPort"));
                            }

                            smtpClient.Port = port;
                        }

                        // else the port defaults to 25 by .NET when not set
                        smtpClient.ServicePoint.MaxIdleTime     = Host.SMTPMaxIdleTime;
                        smtpClient.ServicePoint.ConnectionLimit = Host.SMTPConnectionLimit;

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

                        case "1":     // basic
                            if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword))
                            {
                                smtpClient.UseDefaultCredentials = false;
                                smtpClient.Credentials           = new NetworkCredential(smtpUsername, smtpPassword);
                            }

                            break;

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

                        smtpClient.EnableSsl = smtpEnableSSL;
                        smtpClient.Send(mailMessage);
                        smtpClient.Dispose();
                    }
                }
                catch (Exception exc)
                {
                    var exc2 = exc as SmtpFailedRecipientException;
                    if (exc2 != null)
                    {
                        retValue = string.Format(Localize.GetString("FailedRecipient"), exc2.FailedRecipient) + " ";
                    }
                    else if (exc is SmtpException)
                    {
                        retValue = Localize.GetString("SMTPConfigurationProblem") + " ";
                    }

                    // mail configuration problem
                    if (exc.InnerException != null)
                    {
                        retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
                        Exceptions.Exceptions.LogException(exc.InnerException);
                    }
                    else
                    {
                        retValue += exc.Message;
                        Exceptions.Exceptions.LogException(exc);
                    }
                }
                finally
                {
                    mailMessage.Dispose();
                }
            }
            else
            {
                retValue = Localize.GetString("SMTPConfigurationProblem");
            }

            return(retValue);
        }
Example #28
0
        public static void SendMail(IList <string> mailAdresses, IList <string> ccAddresses, Enumerables.MailAction action, ILogEmailRepository logEmailRepository, Reserva reserva, byte[] attachment = null)
        {
            ContactCenterDA.Repositories.CC.TH.ObraRepository obraRepository = new ContactCenterDA.Repositories.CC.TH.ObraRepository();
            string htmlBody      = "";
            string htmlImageBody = "";
            string subject       = "";

            try
            {
                var smtpClient = new SmtpClient();

                #region Get Config Variables
                String correo   = "";
                String password = "";
                if (Sesion.aplicacion.CorreoNotificacion.Equals(String.Empty))
                {
                    correo   = ConfigurationManager.AppSettings["mailAccount"];
                    password = ConfigurationManager.AppSettings["mailPassword"];
                }
                else
                {
                    correo   = Sesion.aplicacion.CorreoNotificacion;
                    password = Sesion.aplicacion.Contraseña;
                }
                var mailAccount  = correo;
                var mailPassword = password;

                var smtp            = ConfigurationManager.AppSettings["smtp"];
                var mailDisplayName = ConfigurationManager.AppSettings["mailDisplayName"];
                var port            = ConfigurationManager.AppSettings["port"];
                var sslEnabled      = Convert.ToBoolean(ConfigurationManager.AppSettings["sslEnabled"]);
                var domain          = ConfigurationManager.AppSettings["Domain"];

                #endregion

                #region Create SMTP
                smtpClient.Host = smtp;
                smtpClient.Port = Convert.ToInt16(port);
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                if (domain != null)
                {
                    smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword, domain);
                }
                else
                {
                    smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword);
                }
                smtpClient.EnableSsl = sslEnabled;
                #endregion Create SMTP

                #region Create Mail an recievers
                var mail = new MailMessage();
                mail.From = new MailAddress(mailAccount, mailDisplayName);
                foreach (var mailDirection in mailAdresses.Where(x => !string.IsNullOrEmpty(x)))
                {
                    mail.To.Add(new MailAddress(mailDirection.ToLower()));
                }
                foreach (var mailCC in ccAddresses.Where(x => !string.IsNullOrEmpty(x)))
                {
                    mail.CC.Add(new MailAddress(mailCC.ToLower()));
                }

                #endregion

                #region Create Mail Variables

                //System.Globalization.CultureInfo cultureinfo = new System.Globalization.CultureInfo("es-PE");
                var nombre     = reserva.Cliente.Nombre + " " + reserva.Cliente.ApellidoPaterno + " " + reserva.Cliente.Apellidomaterno;
                var obra       = reserva.Obra.Nombre;
                var fecha      = reserva.FechaReserva.ToString("dd/MM/yyyy" /*, cultureinfo*/);
                var teatro     = reserva.Obra.Teatro.Nombre;
                var hora       = reserva.Horario;
                var totalObras = reserva.ListaDetalles.Count();
                var ubicacion  = reserva.Asientos;
                var precio     = reserva.PrecioTotal;


                #endregion Create Mail Variables

                #region Set Mail Variable Values


                #endregion Set Mail Variable Values

                #region Set Mail Body

                switch (action)
                {
                case Enumerables.MailAction.TeatroConfirmacionReserva:
                    htmlBody = ContactCenterBL.Properties.Resources.nuevomail;
                    htmlBody = htmlBody.Replace("%Nombre", nombre);
                    htmlBody = htmlBody.Replace("%Obra", obra);
                    htmlBody = htmlBody.Replace("%Fecha", fecha);
                    htmlBody = htmlBody.Replace("%Teatro", teatro);
                    htmlBody = htmlBody.Replace("%Hora", fecha + " - " + hora);
                    htmlBody = htmlBody.Replace("%Total", totalObras.ToString());
                    htmlBody = htmlBody.Replace("%Ubicacion", ubicacion);
                    htmlBody = htmlBody.Replace("%Precio", precio.ToString("#.00"));

                    htmlImageBody = ContactCenterBL.Properties.Resources.detail;
                    htmlImageBody = htmlImageBody.Replace("%Nombre", nombre);
                    htmlImageBody = htmlImageBody.Replace("%Obra", obra);
                    htmlImageBody = htmlImageBody.Replace("%Fecha", fecha);
                    htmlImageBody = htmlImageBody.Replace("%Teatro", teatro);
                    htmlImageBody = htmlImageBody.Replace("%Hora", fecha + " - " + hora);
                    htmlImageBody = htmlImageBody.Replace("%Total", totalObras.ToString());
                    htmlImageBody = htmlImageBody.Replace("%Ubicacion", ubicacion);
                    htmlImageBody = htmlImageBody.Replace("%Precio", precio.ToString("#.00"));

                    List <String> zonas = new List <String>();
                    foreach (DetalleReserva detalleRes in reserva.ListaDetalles.OrderBy(tx => tx.NombreZona).ToList())
                    {
                        if (!zonas.Contains(detalleRes.NombreZona))
                        {
                            zonas.Add(detalleRes.NombreZona);
                        }
                    }

                    string detalle    = "";
                    string filAsiento = "";
                    int    contador   = 0;
                    foreach (String nomZona in zonas)
                    {
                        foreach (DetalleReserva detalleRes2 in reserva.ListaDetalles.Where(tx => tx.NombreZona == nomZona))
                        {
                            filAsiento += detalleRes2.NombreFila + " / " + detalleRes2.NombreAsiento + ", ";
                        }
                        filAsiento = filAsiento.TrimEnd(',', ' ');
                        //detalle += "<tr><td style= 'text-align:right;'>Sector</td><td>:</td><td></td><td></td><td style= 'text-align:left;'>" + nomZona + "</td></tr><tr><td style= 'text-align:right;' >Ubicaciones</td><td>:</td><td></td><td></td><td style= 'text-align:left;'>" + filAsiento + "</td></tr>";
                        detalle   += $"<p style='margin-top:3%; margin-bottom: 2%'>ZONA: {nomZona}</p> <p style='margin-top:3%; margin-bottom: 2%'> UBICACIÓN: {filAsiento}</p>";
                        filAsiento = "";
                    }

                    htmlBody      = htmlBody.Replace("varDetalle", detalle);
                    htmlImageBody = htmlImageBody.Replace("varDetalle", detalle);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(action), action, null);
                }

                #endregion Set Mail Body

                #region Set Mail Subject

                switch (action)
                {
                case Enumerables.MailAction.TeatroConfirmacionReserva:
                    subject = Constantes.Subjects.TeatroConfirmacionReserva;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(action), action, null);
                }

                #endregion Set Mail Subject

                #region Get Mail Body embedded images paths


                Byte[]       ba = obraRepository.GetImage(reserva.Obra.IdObra);
                MemoryStream ms = new MemoryStream(ba);
                //var cabeceraImgPath = Path.Combine("../../Resources/cabecera_correo2.jpg");
                //var rootFolder = AppDomain.CurrentDomain.BaseDirectory;
                //var cabepath = Path.Combine(rootFolder, "../../Resources/cabecera_correo2.jpg");
                Image        ImageCabe     = ContactCenterBL.Properties.Resources.cabecera;
                Byte[]       imageCabeByte = Convertir_Imagen_Bytes(ImageCabe);
                MemoryStream ca            = new MemoryStream(imageCabeByte);


                Image image = Image.FromStream(ca);
                Guid  id    = Guid.NewGuid();
                image.Save($"C:\\BackupTeatro\\{id.ToString()}.jpg");
                string path = $"C:\\BackupTeatro\\{id.ToString()}.jpg";


                Image image2 = Image.FromStream(ms);
                Guid  id2    = Guid.NewGuid();
                image2.Save($"C:\\BackupTeatro\\{id2.ToString()}.jpg");
                string path2 = $"C:\\BackupTeatro\\{id2.ToString()}.jpg";

                htmlBody = htmlBody.Replace("%Cabecera", path);
                htmlBody = htmlBody.Replace("%ImagenObra", path2);

                htmlImageBody = htmlImageBody.Replace("%Cabecera", path);
                htmlImageBody = htmlImageBody.Replace("%ImagenObra", path2);


                Image imageMail = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImageGdiPlus(htmlImageBody);
                //imageMail.Save($"C:\\BackupTeatro\\test2.jpg");
                //Image imagex = Image.FromFile($"C:\\BackupTeatro\\test2.jpg");
                Byte[]       imageMailBytes        = Convertir_Imagen_Bytes(imageMail);
                MemoryStream imageMailMemoryStream = new MemoryStream(imageMailBytes);
                //mail.Attachments.Add(new Attachment(imageMailMemoryStream, "Compra.jpg"));



                var imageMailLinked = new LinkedResource(imageMailMemoryStream, MediaTypeNames.Image.Jpeg);
                imageMailLinked.ContentId = "obraimagen";

                Byte[]       pdfFile   = PdfSharpConvert(htmlBody);
                MemoryStream pdfStream = new MemoryStream(pdfFile);
                mail.Attachments.Add(new Attachment(pdfStream, "Confirmación de compra.pdf"));

                if (File.Exists(path2))
                {
                    File.Delete(path2);
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                htmlBody      = htmlBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera");
                htmlBody      = htmlBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra");
                htmlImageBody = htmlImageBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera");
                htmlImageBody = htmlImageBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra");

                #endregion Get Mail Body embedded images paths

                #region Set embedded images mail id

                //var cabecera = new LinkedResource(ca, MediaTypeNames.Image.Jpeg);
                //cabecera.ContentId = "Cabecera";
                ////cabecera.TransferEncoding = TransferEncoding.Base64;

                //var logo = new LinkedResource(ms, MediaTypeNames.Image.Jpeg);
                //logo.ContentId = "ImagenObra";
                ////logo.TransferEncoding = TransferEncoding.Base64;

                #endregion

                #region Set Body and Images

                var newHtml = ContactCenterBL.Properties.Resources._base;

                var html = AlternateView.CreateAlternateViewFromString(newHtml, null, MediaTypeNames.Text.Html);
                //html.TransferEncoding = TransferEncoding.Base64;
                html.LinkedResources.Add(imageMailLinked);
                //html.LinkedResources.Add(cabecera);

                #endregion Set Body and Images

                #region Set values to mail

                mail.Subject         = subject;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.IsBodyHtml      = true;
                mail.AlternateViews.Add(html);

                #endregion Set values to mail



                #region Send Mail

                smtpClient.SendAsync(mail, null);

                smtpClient.SendCompleted += (s, e) =>
                {
                    LogEmail logEmail = new LogEmail();
                    logEmail.Asunto          = subject;
                    logEmail.CorreoDestino   = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray());
                    logEmail.CorreoDestinoCC = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray());
                    logEmail.Estado          = "OK";
                    logEmail.IdObra          = reserva.Obra.IdObra;
                    logEmail.FechaEnvio      = DateTime.Now;
                    logEmail.MensajeImagen   = htmlImageBody;
                    logEmail.FechaCreacion   = DateTime.Now;
                    logEmail.UsuarioCreacion = Sesion.usuario.Login;
                    logEmail.Mensaje         = htmlBody;
                    logEmail.Intento         = 1;
                    logEmail.Descripcion     = String.Empty;
                    if (e.Error != null)
                    {
                        logEmail.Estado = "FALLO";
                        if (e.Error.InnerException != null)
                        {
                            logEmail.Descripcion = e.Error.InnerException.Message;
                        }
                        else
                        {
                            logEmail.Descripcion = e.Error.Message;
                        }
                    }

                    logEmailRepository.Insert(logEmail);
                    if (e.Error != null)
                    {
                        MessageBox.Show("No se envió el correo\n\n" +
                                        "Cliente: \n" + nombre + "\n" +
                                        "Obra: \n" + obra + "\n" +
                                        "Fecha Reserva: \n" + reserva.FechaReserva.ToShortDateString() + "\n" +
                                        "Correo: \n" + reserva.Cliente.Correo + "\n\n" +
                                        "Error: \n" + e.Error.Message, "Error enviando email", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    smtpClient.Dispose();
                    mail.Dispose();
                    //logo.Dispose();
                };

                #endregion Send Mail
            }
            catch (Exception ex)
            {
                LogEmail logEmail = new LogEmail();
                logEmail.Asunto          = subject;
                logEmail.CorreoDestino   = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray());
                logEmail.CorreoDestinoCC = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray());
                logEmail.Estado          = "OK";
                logEmail.IdObra          = reserva.Obra.IdObra;
                logEmail.FechaEnvio      = DateTime.Now;
                logEmail.MensajeImagen   = htmlImageBody;
                logEmail.FechaCreacion   = DateTime.Now;
                logEmail.UsuarioCreacion = Sesion.usuario.Login;
                logEmail.Mensaje         = htmlBody;
                logEmail.Intento         = 1;
                logEmail.Estado          = "FALLO";
                logEmail.Descripcion     = ex.Message;

                logEmailRepository.Insert(logEmail);

                MessageBox.Show("No se envió el correo\n\n" +
                                "Cliente: \n" + reserva.Cliente.Nombre + " " + reserva.Cliente.ApellidoPaterno + " " + reserva.Cliente.Apellidomaterno + "\n" +
                                "Obra: \n" + reserva.Obra.Nombre + "\n" +
                                "Fecha Reserva: \n" + reserva.FechaReserva.ToShortDateString() + "\n" +
                                "Correo: \n" + reserva.Cliente.Correo + "\n\n" +
                                "Error: \n" + ex.Message, "Error enviando email", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #29
0
        private void SendMail(IEnumerable <Employees> bday, MailDetails mailDetails)
        {
            try
            {
                MailMessage msg = new MailMessage();

                msg.From = new MailAddress(mailDetails.User, "Chris");
                msg.To.Add(new MailAddress("*****@*****.**", "Chris"));
                msg.Subject = "Birthday Reminder";

                var toBday = "Tomorrow's Birthday People: ";
                foreach (var person in bday)
                {
                    toBday = toBday + "\n" + person.FirstName + " " + person.LastName;
                }
                msg.Body = toBday;

                var SenderEmail         = mailDetails.User;
                var SenderEmailPassword = mailDetails.Pass;

                StringBuilder str = new StringBuilder();
                str.AppendLine("BEGIN:VCALENDAR");
                str.AppendLine("PRODID:-//Schedule a Meeting");
                str.AppendLine("VERSION:2.0");
                str.AppendLine("METHOD:REQUEST");
                str.AppendLine("BEGIN:VEVENT");
                str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmss}", DateTime.Today.AddDays(1).ToUniversalTime() - new TimeSpan(0, 0, 1)));
                str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Today.ToUniversalTime()));
                str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmss}", DateTime.Today.AddDays(2).ToUniversalTime()));
                str.AppendLine("LOCATION: " + "Burbank, CA");
                str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
                str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
                str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
                str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject));
                str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address));

                str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));

                str.AppendLine("BEGIN:VALARM");
                str.AppendLine("TRIGGER:-PT15M");
                str.AppendLine("ACTION:DISPLAY");
                str.AppendLine("DESCRIPTION:Reminder");
                str.AppendLine("END:VALARM");
                str.AppendLine("END:VEVENT");
                str.AppendLine("END:VCALENDAR");

                System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();
                smtpclient.Host      = mailDetails.Host; //-------this has to given the Mailserver IP
                smtpclient.Port      = mailDetails.Port;
                smtpclient.EnableSsl = true;

                smtpclient.Credentials = new System.Net.NetworkCredential(SenderEmail.Trim(), SenderEmailPassword.Trim());
                System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar");
                contype.Parameters.Add("method", "REQUEST");
                contype.Parameters.Add("name", "Meeting.ics");
                AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), contype);
                msg.AlternateViews.Add(avCal);
                smtpclient.Send(msg);
            }
            catch (Exception)
            {
                _logger.LogInformation("Send Email Failed.");
            }
        }
Example #30
0
        public static async Task <bool> SendCancelCalendarInvite(EmailTemplate emailTemplate)
        {
            if (emailTemplate != null && emailTemplate.ToEmailAddress.Length > 0)
            {
                LoadEmailSettings(ref emailTemplate);
                System.Net.Mail.MailMessage msg = new MailMessage();
                foreach (string recepient in emailTemplate.ToEmailAddress)
                {
                    msg.To.Add("*****@*****.**");
                }
                msg.From    = new MailAddress("*****@*****.**", "Manjunath G");
                msg.Body    = emailTemplate.Body;
                msg.Subject = emailTemplate.Subject;
                //MailAddress bcc = new MailAddress("");
                //msg.Bcc.Add(bcc);
                StringBuilder str = new StringBuilder();
                str.AppendLine("BEGIN:VCALENDAR");
                str.AppendLine("PRODID:-//Schedule a Meeting");
                str.AppendLine("VERSION:2.0");
                str.AppendLine("METHOD:CANCEL");
                str.AppendLine("BEGIN:VEVENT");
                str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", emailTemplate.InvitationStartTime));
                str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
                str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", emailTemplate.InvitationEndTime));
                str.AppendLine("LOCATION: " + emailTemplate.Location);
                str.AppendLine(string.Format("UID:{0}", emailTemplate.UniqueIdentifier));
                str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", emailTemplate.Body));
                str.AppendLine(string.Format("SUMMARY:{0}", emailTemplate.Subject));
                str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", emailTemplate.EmailFromAddress));
                str.AppendLine("END:VEVENT");
                str.AppendLine("END:VCALENDAR");


                byte[]       byteArray = Encoding.ASCII.GetBytes(str.ToString());
                MemoryStream stream    = new MemoryStream(byteArray);


                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(stream, "Calendar.ics");


                msg.Attachments.Add(attach);


                System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar");
                contype.Parameters.Add("method", "REQUEST");
                //  contype.Parameters.Add("name", "Meeting.ics");
                AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), contype);
                msg.AlternateViews.Add(avCal);


                try
                {
                    //Now sending a mail with attachment ICS file.
                    System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();
                    smtpclient.Host        = emailTemplate.Host;
                    smtpclient.Port        = emailTemplate.Port;
                    smtpclient.EnableSsl   = emailTemplate.EnableSsl;
                    smtpclient.Credentials = new System.Net.NetworkCredential(emailTemplate.EmailFromAddress, emailTemplate.EmailFromPassword);
                    await smtpclient.SendMailAsync(msg);

                    return(true);
                }
                catch (System.Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
Example #31
0
        protected override bool DoSendMsg(Message msg)
        {
            // If msg is null or msg hasn't any "To" addressee - we can't send it, so return
            if (msg == null || !msg.AddressToBuilder.All.Any())
            {
                return(false);
            }

            var addressFrom = msg.AddressFromBuilder.GetFirstOrDefaultMatchForChannels(SupportedChannelNames);

            var addressTo = msg.AddressToBuilder.GetMatchesForChannels(SupportedChannelNames).ToList();

            var addressReplyTo = msg.AddressReplyToBuilder.GetMatchesForChannels(SupportedChannelNames);
            var arto           = addressReplyTo.Select(fmtEmail).ToList();

            var addressCC = msg.AddressCCBuilder.GetMatchesForChannels(SupportedChannelNames);
            var acc       = addressCC.Select(fmtEmail).ToList();

            var addressBCC = msg.AddressBCCBuilder.GetMatchesForChannels(SupportedChannelNames);
            var abcc       = addressBCC.Select(fmtEmail).ToList();

            var fa = addressFrom.ChannelAddress;
            var fn = addressFrom.ChannelName;

            if (fa.IsNullOrWhiteSpace())
            {
                fa = DefaultFromAddress;
            }
            if (fn.IsNullOrWhiteSpace())
            {
                fn = DefaultFromName;
            }

            var from    = fmtEmail(fa, fn);
            var wasSent = false;

            // todo поддерживает ли MailMessageTo многих адресатов через запятую в однйо строке, если да - убрать цикл foreach
            foreach (var addressee in addressTo)
            {
                var to = fmtEmail(addressee.ChannelAddress, addressee.Name);

                using (var email = new MailMessage(from, to))
                {
                    foreach (var adr in arto)
                    {
                        email.ReplyToList.Add(adr);
                    }

                    foreach (var adr in acc)
                    {
                        email.CC.Add(adr);
                    }

                    foreach (var adr in abcc)
                    {
                        email.Bcc.Add(adr);
                    }

                    email.Subject = msg.Subject;

                    if (msg.RichBody.IsNullOrWhiteSpace())
                    {
                        email.Body = msg.Body;
                    }
                    else
                    {
                        if (msg.Body.IsNullOrWhiteSpace())
                        {
                            email.IsBodyHtml = true;
                            email.Body       = msg.RichBody;
                        }
                        else
                        {
                            email.Body = msg.Body;
                            var alternateHTML = AlternateView.CreateAlternateViewFromString(msg.RichBody, new System.Net.Mime.ContentType(ContentType.HTML));
                            email.AlternateViews.Add(alternateHTML);
                        }
                    }

                    if (msg.Attachments != null)
                    {
                        foreach (var att in msg.Attachments.Where(a => a.Content != null))
                        {
                            var ema = new Attachment(new System.IO.MemoryStream(att.Content), new System.Net.Mime.ContentType(att.ContentType));

                            if (att.Name.IsNotNullOrWhiteSpace())
                            {
                                ema.ContentDisposition.FileName = att.Name;
                            }

                            email.Attachments.Add(ema);
                        }
                    }

                    try
                    {
                        m_Smtp.Send(email);
                        wasSent = true;
                    }
                    catch (Exception error)
                    {
                        var et = error.ToMessageWithType();
                        Log(MessageType.Error, "{0}.DoSendMsg(msg): {1}".Args(this.GetType().FullName, et), et);
                    }
                }
            }

            return(wasSent);
        }
Example #32
0
        private static Task NewsNotification(AdminNewsViewModel model)
        {
            try
            {
                EvolutionEntities _db = new EvolutionEntities();
                var emaildetails      = _db.Email_Setting.ToList();
                if (emaildetails.Count > 0)
                {
                    MailMessage msg = new MailMessage();
                    msg.From    = new MailAddress(emaildetails[0].From_Email);
                    msg.Subject = "There is news for you!";
                    string EmpEmail = AllEmployeeEmailString();
                    string MngEmail = AllManagerEmailString();
                    string CumEmail = AllCustomerEmailString();
                    if (model.EmployeeAccess == true)
                    {
                        foreach (var address in EmpEmail.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            msg.To.Add(address);
                        }
                    }
                    if (model.ManagerAccess == true)
                    {
                        foreach (var address in MngEmail.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            msg.To.Add(address);
                        }
                    }
                    if (model.CustomerAccess == true)
                    {
                        foreach (var address in CumEmail.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            msg.To.Add(address);
                        }
                    }
                    if (model.SpecificWorker == true)
                    {
                        var data = _db.AspNetUsers.Where(x => x.Id == model.WorkerID).FirstOrDefault();
                        if (data != null)
                        {
                            msg.To.Add(data.UserName);
                        }
                    }
                    if (model.SpecificManager == true)
                    {
                        var data = _db.AspNetUsers.Where(x => x.Id == model.ManagerID).FirstOrDefault();
                        if (data != null)
                        {
                            msg.To.Add(data.UserName);
                        }
                    }
                    if (model.SpecificCustomer == true)
                    {
                        var data = _db.AspNetUsers.Where(x => x.Id == model.CustomerID).FirstOrDefault();
                        if (data != null)
                        {
                            msg.To.Add(data.UserName);
                        }
                    }

                    msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(StripHTML(model.Description), null, MediaTypeNames.Text.Html));
                    SmtpClient smtpClient = new SmtpClient(emaildetails[0].Server, Convert.ToInt32(25));
                    //System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["secretPassword"]);
                    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(emaildetails[0].From_Email, emaildetails[0].Email_Password);
                    smtpClient.Credentials = credentials;
                    msg.IsBodyHtml         = true;
                    msg.Body             = StripHTML(model.Description);
                    smtpClient.EnableSsl = (bool)emaildetails[0].Enable_SSL;
                    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };
                    smtpClient.Send(msg);
                }
            }
            catch (Exception ex)
            {
                return(Task.FromResult(0));
            }
            return(Task.FromResult(0));
        }
Example #33
0
        /// <summary>
        /// Iterate through each MIME part and extract relevant metadata.
        /// </summary>
        private void ProcessMimeParts()
        {
            // Keep track of S/MIME signing and envelope encryption.
            bool allMimePartsSigned = true, allMimePartsEncrypted = true, allMimePartsTripleWrapped = true;

            // Process each MIME part.
            int pgpSignatureIndex = -1;
            int pgpSignedMessageIndex = -1;
            for (int i = 0; i < MimeParts.Count; i++)
            {
                MimePart mimePart = MimeParts[i];

                int semicolon = mimePart.ContentType.IndexOf(";");
                if (semicolon > -1)
                {
                    string originalContentType = mimePart.ContentType;
                    mimePart.ContentType = mimePart.ContentType.Substring(0, semicolon);

                    if (mimePart.ContentType.ToUpper() == "MESSAGE/PARTIAL")
                    {
                        PartialMessageId = Functions.ExtractMimeParameter(originalContentType, "id");
                        int partialMessageNumber = 0;
                        if (int.TryParse(Functions.ExtractMimeParameter(originalContentType, "number"), out partialMessageNumber))
                            PartialMessageNumber = partialMessageNumber;
                    }
                }

                // Extract any signing certificates.  If this MIME part isn't signed, the overall message isn't signed.
                if (mimePart.SmimeSigned)
                {
                    if (mimePart.SmimeSigningCertificates.Count > 0 && SmimeSigningCertificate == null)
                    {
                        foreach (X509Certificate2 signingCert in mimePart.SmimeSigningCertificates)
                        {
                            if (!SmimeSigningCertificateChain.Contains(signingCert))
                            {
                                SmimeSigningCertificateChain.Add(signingCert);
                                SmimeSigningCertificate = signingCert;
                            }
                        }
                    }
                }
                else
                    allMimePartsSigned = false;

                // If this MIME part isn't marked as being in an encrypted envelope, the overall message isn't encrypted.
                if (!mimePart.SmimeEncryptedEnvelope)
                {
                    // Ignore signatures and encryption blocks when determining if everything is encrypted.
                    if (!mimePart.ContentType.StartsWith("application/pkcs7-signature") && !mimePart.ContentType.StartsWith("application/x-pkcs7-signature") && !mimePart.ContentType.StartsWith("application/pkcs7-mime"))
                        allMimePartsEncrypted = false;
                }

                // If this MIME part isn't marked as being triple wrapped, the overall message isn't triple wrapped.
                if (!mimePart.SmimeTripleWrapped)
                {
                    // Ignore signatures and encryption blocks when determining if everything is triple wrapped.
                    if (!mimePart.ContentType.StartsWith("application/pkcs7-signature") && !mimePart.ContentType.StartsWith("application/x-pkcs7-signature") && !mimePart.ContentType.StartsWith("application/pkcs7-mime"))
                        allMimePartsTripleWrapped = false;
                }

                // Set the default primary body, defaulting to text/html and falling back to any text/*.
                string contentTypeToUpper = mimePart.ContentType.ToUpper();
                if (Body.Length < 1)
                {
                    // If the MIME part is of type text/*, set it as the intial message body.
                    if (string.IsNullOrEmpty(mimePart.ContentType) || contentTypeToUpper.StartsWith("TEXT/"))
                    {
                        IsBodyHtml = contentTypeToUpper.StartsWith("TEXT/HTML");
                        Body = mimePart.Body;
                        BodyContentType = mimePart.ContentType;
                        CharSet = mimePart.CharSet;
                    }
                    else
                    {
                        // If the MIME part isn't of type text/*, treat it as an attachment.
                        MemoryStream attachmentStream = new MemoryStream(mimePart.BodyBytes);
                        Attachment attachment;
                        if (mimePart.ContentType.IndexOf("/") > -1)
                            attachment = new Attachment(attachmentStream, mimePart.Name, mimePart.ContentType);
                        else
                            attachment = new Attachment(attachmentStream, mimePart.Name);

                        attachment.ContentId = mimePart.ContentID;
                        Attachments.Add(attachment);
                    }
                }
                else
                {
                    // If the current body isn't text/html and this is, replace the default body with the current MIME part.
                    if (!ContentType.ToUpper().StartsWith("TEXT/HTML") && contentTypeToUpper.StartsWith("TEXT/HTML"))
                    {
                        // Add the previous default body as an alternate view.
                        MemoryStream alternateViewStream = new MemoryStream(Encoding.UTF8.GetBytes(Body));
                        AlternateView alternateView = new AlternateView(alternateViewStream, BodyContentType);
                        if (BodyTransferEncoding != TransferEncoding.Unknown)
                            alternateView.TransferEncoding = BodyTransferEncoding;
                        AlternateViews.Add(alternateView);

                        IsBodyHtml = true;
                        Body = mimePart.Body;
                        BodyContentType = mimePart.ContentType;
                        CharSet = mimePart.CharSet;
                    }
                    else
                    {
                        // If the MIME part isn't of type text/*, treat is as an attachment.
                        MemoryStream attachmentStream = new MemoryStream(mimePart.BodyBytes);
                        Attachment attachment;
                        if (mimePart.ContentType.IndexOf("/") > -1)
                            attachment = new Attachment(attachmentStream, mimePart.Name, mimePart.ContentType);
                        else
                            attachment = new Attachment(attachmentStream, mimePart.Name);
                        attachment.ContentId = mimePart.ContentID;
                        Attachments.Add(attachment);
                    }
                }

                // Check if the MIME part is encrypted or signed using PGP.
                if (mimePart.Body.StartsWith("-----BEGIN PGP MESSAGE-----"))
                    pgpEncrypted = true;
                else if (mimePart.Body.StartsWith("-----BEGIN PGP SIGNED MESSAGE-----"))
                    pgpSignedMessageIndex = i;
                else if (mimePart.Body.StartsWith("-----BEGIN PGP SIGNATURE-----"))
                    pgpSignatureIndex = i;
            }

            if (pgpSignedMessageIndex > -1 && pgpSignatureIndex > -1)
                pgpSigned = true;

            // OpaqueMail optional setting for protecting the subject.
            if (SubjectEncryption && Body.StartsWith("Subject: "))
            {
                int linebreakPosition = Body.IndexOf("\r\n");
                if (linebreakPosition > -1)
                {
                    // Decode international strings and remove escaped linebreaks.
                    string subjectText = Body.Substring(9, linebreakPosition - 9);
                    Subject = Functions.DecodeMailHeader(subjectText).Replace("\r", "").Replace("\n", "");

                    Body = Body.Substring(linebreakPosition + 2);
                }
            }

            // Set the message's S/MIME attributes.
            SmimeSigned = allMimePartsSigned;
            SmimeEncryptedEnvelope = allMimePartsEncrypted;
            SmimeTripleWrapped = allMimePartsTripleWrapped;
        }