Пример #1
0
        } // End Constructor

        // https://stackoverflow.com/questions/18358534/send-inline-image-in-email
        private static System.Net.Mail.AlternateView GetAlternativeView(string htmlBody, System.Collections.Generic.List <Resource> embeddedImages)
        {
            foreach (Resource thisResource in embeddedImages)
            {
                htmlBody = htmlBody.Replace(thisResource.FileName, "cid:" + thisResource.UID);
            } // Next thisResource

            System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(
                htmlBody
                , null
                , System.Net.Mime.MediaTypeNames.Text.Html
                );

            foreach (Resource thisResource in embeddedImages)
            {
                System.Net.Mail.LinkedResource res = new System.Net.Mail.LinkedResource(
                    thisResource.Stream
                    , thisResource.ContentType
                    );

                res.ContentId = thisResource.UID;
                alternateView.LinkedResources.Add(res);
            } // Next thisResource

            return(alternateView);
        } // End Function GetAlternativeView
Пример #2
0
        }         // End Sub SendAttachment

        // https://stackoverflow.com/questions/18358534/send-inline-image-in-email
        private static System.Net.Mail.AlternateView GetAlternativeView(string htmlBody, string filePath)
        {
            System.Net.Mail.LinkedResource res = new System.Net.Mail.LinkedResource(filePath, "image/png");
            res.ContentId = System.Guid.NewGuid().ToString();
            htmlBody      = htmlBody.Replace("{@COR_LOGO}", "cid:" + res.ContentId);

            System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(htmlBody, null, System.Net.Mime.MediaTypeNames.Text.Html);

            alternateView.LinkedResources.Add(res);
            return(alternateView);
        } // End Function GetAlternativeView
Пример #3
0
        void email_DoWork(object sender, DoWorkEventArgs e)
        {
            System.Diagnostics.Debugger.Break();
            while (true)
            {
                Thread.Sleep(_emailQueueProcessDelayMS);

                if (_emailQueue.Count > 0)
                {
                    var email_export = _emailQueue.Dequeue();

                    var email_resources = new List <System.Net.Mail.LinkedResource>();

                    var email_html = new StringBuilder("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                    email_html.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /><title>iNQUIRE Items Export</title>");
                    email_html.Append("<style type=\"text/css\">span.label { font-weight: bold; } div.desc { margin-bottom: 10px; }</style></head>");
                    email_html.Append("<body><h1><u>iNQUIRE Items Export</u></h1>");

                    email_html.Append(String.Format("<div>{0}</div>", email_export.Message));

                    int count = 0;

                    foreach (ExportItem ei in email_export.Items)
                    {
                        email_html.Append("<div><table width=\"950\"><tr>");

                        System.Net.Mail.LinkedResource lr;
                        string content_id = null;

                        if (!string.IsNullOrEmpty(ei.ImageUri))
                        {
                            lr                       = new System.Net.Mail.LinkedResource(ImageHelper.GetImageStream(ei.ImageUri, email_export.ImageNotFoundUri));
                            content_id               = String.Format("image{0}", Guid.NewGuid().ToString().Replace("-", ""));
                            lr.ContentId             = content_id;
                            lr.ContentType.MediaType = "image/jpeg";
                            email_resources.Add(lr);
                        }

                        email_html.Append(ei.Item.ExportHtml(content_id));
                        email_html.Append("</td></tr></table></div>");

                        if (count < email_export.Items.Count - 1)
                        {
                            email_html.Append("<hr />");
                        }
                        count++;
                    }

                    email_html.Append("</body></html>");

                    Helper.EmailHelper.SendEmail(email_export.EmailTo, email_html.ToString(), email_resources);
                }
            }
        }
Пример #4
0
        private bool SendEmail()
        {
            try
            {
                //create the mail message
                using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage())
                {
                    //set the addresses
                    mail.From = new System.Net.Mail.MailAddress(UserSettings.MAIL_USERNAME);
                    mail.To.Add(_emailAddress);

                    //set the content
                    mail.Subject = "Closet Drawing";
                    mail.Attachments.Add(new System.Net.Mail.Attachment(_closetDrawingPath));

                    //first we create the Plain Text part
                    System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(String.Format("{0}Width (feet) : {1}{0}Depth (feet) : {2}{0}Height (feet) : {3}{0}Ply Thickness (inches) : {4}{0}Door Height as % of total height: {5}{0}Number of drawers : {6}{0}Is Split drawers ? : {7}{0}"
                                                                                                                                        , Environment.NewLine, _width, _depth, _height, _plyThickness, _doorHeightPercentage, _iNumOfDrawers, _isSplitDrawers), null, "text/plain");

                    //then we create the Html part
                    //to embed images, we need to use the prefix 'cid' in the img src value
                    //the cid value will map to the Content-Id of a Linked resource.
                    //thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'
                    System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body><h3>Here is a preview of the closet. AutoCAD drawing file is attached.</h3><br/><img src='cid:closetimg'/></body></html>", null, "text/html");

                    if (!String.IsNullOrEmpty(_imagePath))
                    {
                        //create the LinkedResource (embedded image)
                        System.Net.Mail.LinkedResource closetLR = new System.Net.Mail.LinkedResource(_imagePath);
                        closetLR.ContentId = "closetimg";
                        htmlView.LinkedResources.Add(closetLR);
                    }

                    //add the views
                    mail.AlternateViews.Add(plainView);
                    mail.AlternateViews.Add(htmlView);

                    //send the message
                    using (System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587))
                    {
                        smtpClient.Credentials = new System.Net.NetworkCredential(UserSettings.MAIL_USERNAME, UserSettings.MAIL_PASSWORD);
                        smtpClient.EnableSsl   = true;
                        smtpClient.Send(mail);
                    }
                }
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
Пример #5
0
        private static System.Net.Mail.LinkedResource GetImageResource(string contentId, string imagePath)
        {
            byte[] imageBytes;
            using (WebClient webClient = new WebClient())
            {
                imageBytes = webClient.DownloadData(imagePath);
            }

            System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(new MemoryStream(imageBytes), "image/gif");
            imageResource.ContentId        = contentId;
            imageResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            return(imageResource);
        }
Пример #6
0
        private static System.Net.Mail.AlternateView GetMasterBodyForWindowService(string body, string subject, string path)
        {
            string masterEmailTemplate = Email.GetEmailTemplateForWindowService(SystemEnum.EmailTemplateFileName.MasterEmailTemplate.ToString(), path);

            body = masterEmailTemplate.Replace("[@MainContent]", body);

            body = body.Replace("[@Subject]", subject);

            System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html");

            string logo = path + "\\Content\\images\\logo.png";

            System.Net.Mail.LinkedResource logoResource = new System.Net.Mail.LinkedResource(logo, "image/gif");
            logoResource.ContentId        = "LogoImage";
            logoResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlView.LinkedResources.Add(logoResource);
            return(htmlView);
        }
Пример #7
0
        public List <System.Net.Mail.LinkedResource> getLinkedResources()
        {
            List <System.Net.Mail.LinkedResource> vLinkedResourcesColl = new List <System.Net.Mail.LinkedResource>();

            // ==============================Gestion des images ressources ===================================================================================================================================================================
            if (this.imagesRessources.Count != 0)
            {
                // Ajout de toutes les imagesRessources en tant que "LinkedResource" nécessaires à la vue de la signature (collection à ajouter à une alternateview)
                foreach (var vImageRessource in this.imagesRessources)
                {
                    // Conversion de la base64 à image et conversion de l'imageRessource en "linkedResource"
                    System.Net.Mail.LinkedResource vImageLinkedResource;
                    vImageLinkedResource = new System.Net.Mail.LinkedResource(vImageRessource.base64ToImage(), "image/" + vImageRessource.Extension + "");
                    // Indication de l'identifiant cid obligatoire !!
                    vImageLinkedResource.ContentId = vImageRessource.NomFichier;
                    vLinkedResourcesColl.Add(vImageLinkedResource);
                }
            }
            return(vLinkedResourcesColl);
        }
Пример #8
0
        /// <summary>
        /// Get Master Body HTML
        /// </summary>
        /// <param name="body">Body Text</param>
        /// <param name="subject">Mail Subject</param>
        /// <param name="emailType">Email Type</param>
        /// <returns>Alternate View</returns>
        private static System.Net.Mail.AlternateView GetMasterBody(string body, string subject, EmailType emailType)
        {
            if (emailType == EmailType.Default)
            {
                string masterEmailTemplate = Email.GetEmailTemplate(SystemEnum.EmailTemplateFileName.MasterEmailTemplate.ToString());
                body = masterEmailTemplate.Replace("[@MainContent]", body);

                body = body.Replace("[@Subject]", subject);

                System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html");

                string logo = ProjectConfiguration.ApplicationRootPath + "\\Content\\images\\logo.png";

                System.Net.Mail.LinkedResource logoResource = new System.Net.Mail.LinkedResource(logo, "image/gif");
                logoResource.ContentId        = "LogoImage";
                logoResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                htmlView.LinkedResources.Add(logoResource);
                return(htmlView);
            }
            else
            {
                return(System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html"));
            }
        }
        private bool SendEmail()
        {
            try
            {
                //create the mail message
                using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage())
                {
                    //set the addresses
                    mail.From = new System.Net.Mail.MailAddress(UserSettings.MAIL_USERNAME);
                    mail.To.Add(_emailAddress);

                    //set the content
                    mail.Subject = "Closet Drawing";
                    mail.Attachments.Add(new System.Net.Mail.Attachment(_closetDrawingPath));

                    //first we create the Plain Text part
                    System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(String.Format("{0}Width (feet) : {1}{0}Depth (feet) : {2}{0}Height (feet) : {3}{0}Ply Thickness (inches) : {4}{0}Door Height as % of total height: {5}{0}Number of drawers : {6}{0}Is Split drawers ? : {7}{0}"
                        , Environment.NewLine, _width, _depth, _height, _plyThickness, _doorHeightPercentage, _iNumOfDrawers, _isSplitDrawers), null, "text/plain");

                    //then we create the Html part
                    //to embed images, we need to use the prefix 'cid' in the img src value
                    //the cid value will map to the Content-Id of a Linked resource.
                    //thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'
                    System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body><h3>Here is a preview of the closet. AutoCAD drawing file is attached.</h3><br/><img src='cid:closetimg'/></body></html>", null, "text/html");

                    if (! String.IsNullOrEmpty(_imagePath))
                    {
                        //create the LinkedResource (embedded image)
                        System.Net.Mail.LinkedResource closetLR = new System.Net.Mail.LinkedResource(_imagePath);
                        closetLR.ContentId = "closetimg";
                        htmlView.LinkedResources.Add(closetLR);
                    }

                    //add the views
                    mail.AlternateViews.Add(plainView);
                    mail.AlternateViews.Add(htmlView);

                    //send the message
                    using (System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587))
                    {
                        smtpClient.Credentials = new System.Net.NetworkCredential(UserSettings.MAIL_USERNAME, UserSettings.MAIL_PASSWORD);
                        smtpClient.EnableSsl = true;
                        smtpClient.Send(mail);
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
        public void SendMail(string Name, string Message, string Gender, string Email, string Copy = "")
        {
            int    i           = 0;
            string strFrom     = "";
            string host        = "";
            string subject     = "";
            string strCc       = "";
            string strMessage  = GetEmailTemplate();
            string DisplayName = "";

            if (Settings.Contains("Bcc"))
            {
                strCc = Settings["Bcc"].ToString();
            }

            if (Settings.Contains("From"))
            {
                strFrom = Settings["From"].ToString();
            }

            if (Settings.Contains("Host"))
            {
                host = Settings["Host"].ToString();
            }

            if (Settings.Contains("Subject"))
            {
                subject = Settings["Subject"].ToString();
            }

            if (Settings.Contains("DisplayName"))
            {
                DisplayName = Settings["DisplayName"].ToString();
            }
            else
            {
                DisplayName = PortalSettings.PortalName;
            }

            System.Data.DataTable dt = new System.Data.DataTable();

            if (string.IsNullOrEmpty(strFrom) || string.IsNullOrEmpty(host) || string.IsNullOrEmpty(host) || string.IsNullOrEmpty(subject))
            {
                throw new Exception("Error al enviar el correo, el módulo no se encuentra configurado correctamente.");
            }

            string appPath = string.Format("{0}Resources/Images/", ControlPath);

            if (appPath.EndsWith("/") == false)
            {
                appPath = appPath + Convert.ToString("/");
            }

            strMessage = strMessage.Replace("$TURNO", GetTimeTitle());
            strMessage = strMessage.Replace("$GENDER", Gender.ToUpper() == "MASCULINO" ? "estimado" : "estimada");
            strMessage = strMessage.Replace("$NOMBRE", Name);
            strMessage = strMessage.Replace("$MENSAJE", Message);

            string logo    = appPath + Convert.ToString("LogoMail.png");
            string appName = appPath + Convert.ToString("AppName.png");

            try
            {
                // Instantiate a new instance of MailMessage
                System.Net.Mail.MailMessage mMailMessage = new System.Net.Mail.MailMessage()
                {
                    //Set the sender address of the mail message
                    From = new System.Net.Mail.MailAddress(strFrom, DisplayName),
                };

                System.Net.Mail.AlternateView av1 = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strMessage, null, System.Net.Mime.MediaTypeNames.Text.Html);

                System.Net.Mail.LinkedResource linkedResource  = new System.Net.Mail.LinkedResource(Server.MapPath(logo));
                System.Net.Mail.LinkedResource appNameResource = new System.Net.Mail.LinkedResource(Server.MapPath(appName));

                linkedResource.ContentId        = "logo";
                linkedResource.ContentType.Name = logo;

                appNameResource.ContentId        = "appname";
                appNameResource.ContentType.Name = appName;

                av1.LinkedResources.Add(linkedResource);
                av1.LinkedResources.Add(appNameResource);
                mMailMessage.AlternateViews.Add(av1);


                //Set the recepient address of the mail message
                string[] arrTo = Email.Split(',');

                for (i = arrTo.GetLowerBound(0); i <= arrTo.GetUpperBound(0); i++)
                {
                    if (IsMail(arrTo[i].Trim()))
                    {
                        mMailMessage.To.Add(new System.Net.Mail.MailAddress(arrTo[i].Trim()));
                    }
                }

                if (mMailMessage.To.Count == 0)
                {
                    mMailMessage.To.Add(new System.Net.Mail.MailAddress(strFrom));
                }

                //Check if the cc value is nothing or an empty value
                if (!string.IsNullOrEmpty(Copy))
                {
                    //Set the CC address of the mail message
                    mMailMessage.CC.Add(new System.Net.Mail.MailAddress(Copy));
                }

                //Check if the cc value is nothing or an empty value
                if (!string.IsNullOrEmpty(strCc))
                {
                    //Set the BCC address of the mail message
                    mMailMessage.Bcc.Add(new System.Net.Mail.MailAddress(strCc));
                }

                //Set the subject of the mail message
                mMailMessage.Subject = subject;

                //Set the body of the mail message
                mMailMessage.Body = strMessage;

                //Set the format of the mail message body as HTML
                mMailMessage.IsBodyHtml = true;

                //Instantiate a new instance of SmtpClient
                System.Net.Mail.SmtpClient emailServer = new System.Net.Mail.SmtpClient(host);

                //Send the mail message
                //emailServer.Send(mMailMessage);

                mMailMessage.Dispose();
            }
            catch (System.Net.Mail.SmtpFailedRecipientsException ehttp)
            {
                string err = "";
                for (i = 0; i <= ehttp.InnerExceptions.Length; i++)
                {
                    err = (err + Convert.ToString("SMTP.Send: Error! ")) + ehttp.InnerExceptions[i].StatusCode.ToString() + " Failed to deliver message to " + ehttp.InnerExceptions[i].FailedRecipient.ToString();
                }

                LogError(err);
                throw new Exception(err);
            }
        }
Пример #11
0
        private System.Net.Mail.MailMessage PreparateMailMessage(List <String> Senders, List <String> SendersCC, List <String> SendersBCC, String Subject, String Body, List <ImageAttached> ImagesAttached, bool isHTML, out String Sender)
        {
            Sender = String.Empty;
            System.Net.Mail.MailMessage mailmsg = new System.Net.Mail.MailMessage();
            mailmsg.From = new System.Net.Mail.MailAddress(Mail);
            String SenderTemp = String.Empty;

            if (Senders != null)
            {
                Senders.ForEach(sender =>
                {
                    mailmsg.To.Add(sender);
                    SenderTemp += sender + ";";
                });
                Sender = SenderTemp;
            }
            else
            {
                throw new Exception("The sender can not be null");
            }

            if (SendersCC != null)
            {
                SendersCC.ForEach(sendercc => mailmsg.CC.Add(sendercc));
            }

            if (SendersBCC != null)
            {
                SendersBCC.ForEach(senderbcc => mailmsg.Bcc.Add(senderbcc));
            }

            if (isHTML)
            {
                List <ImageAttached> imagesTemp = null;

                if (Body.Contains("\"data:image/"))
                {
                    Body = SplitImages(Body, out imagesTemp);
                }

                if (ImagesAttached == null && imagesTemp != null)
                {
                    ImagesAttached = new List <ImageAttached>();
                }

                if (imagesTemp != null)
                {
                    ImagesAttached.AddRange(imagesTemp);
                }

                if (ImagesAttached != null)
                {
                    System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html);
                    alternateView.ContentId        = "htmlview";
                    alternateView.TransferEncoding = TransferEncoding.SevenBit;
                    ImagesAttached.ForEach(imageAttached =>
                    {
                        imageAttached.Tipo.Name = imageAttached.ContentId;
                        System.Net.Mail.LinkedResource linkedResource1 = new System.Net.Mail.LinkedResource(new System.IO.MemoryStream(System.Convert.FromBase64String(imageAttached.ImageBase64)), imageAttached.Tipo);
                        linkedResource1.ContentId        = imageAttached.ContentId;
                        linkedResource1.TransferEncoding = TransferEncoding.Base64;
                        alternateView.LinkedResources.Add(linkedResource1);
                    });
                    mailmsg.AlternateViews.Add(alternateView);
                }
            }

            mailmsg.Subject    = Subject;
            mailmsg.Body       = Body;
            mailmsg.IsBodyHtml = isHTML;
            mailmsg.Priority   = mailPriority;

            return(mailmsg);
        }
Пример #12
0
        public bool SendMail(Competitors c)
        {
            string login = "******";
            string password = "******";
            string fromMail = "*****@*****.**";

            string subject = "Конкурс комментаторов GameShow";

            var mailClient = new System.Net.Mail.SmtpClient
            {
                Host = "smtp.mailgun.org",
                Port = 587,
                EnableSsl = true,
                UseDefaultCredentials = false,
                Credentials = new System.Net.NetworkCredential(login, password)
            };

            using( var msg = new System.Net.Mail.MailMessage(/*fromMail, c.Email, subject, content*/))
            {
                msg.From = (new System.Net.Mail.MailAddress(fromMail));
                msg.To.Add(new System.Net.Mail.MailAddress(c.Email));
                msg.Subject = subject;
                msg.IsBodyHtml = true;    
                var inlineLogo = new System.Net.Mail.LinkedResource(Server.MapPath("~/Resources/mailservice.jpg"));
                inlineLogo.ContentId = Guid.NewGuid().ToString();

                  string body3 = string.Format(
                    @"<div class=""b-message-body__content"" data-lang=""1"">
                        <div dir=""ltr"">
                            Здравствуй, {0} {1}!
                            <br><br>
                            Спасибо за участие в нашем конкурсе!
                            <div>
                                <br>
                            </div>
                            <div>
                                <span style=""font-size:12.8px;"">Мы верим, что именно ты станешь новой звездой первого кибер-спортивного канала в СНГ.</span>
                                <br style=""font-size:12.8px;"">
                                <br style=""font-size:12.8px;"">
                                <span style=""font-size:12.8px;"">
                                    Мы обязательно рассмотрим твою заявку и сообщим о результатах по почте {2}!
                                </span><br style=""font-size:12.8px;"">
                                <br style=""font-size:12.8px;"">
                                <div style=""font-size:12.8px;"">
                                    С уважением,&nbsp;
                                    <font color=""#3d85c6"">Game</font>&nbsp;<font color=""#cc0000"">Show&nbsp;</font><font color=""#3d85c6"">Media Holding!</font>
                                </div>
                            </div>
                            <div>
                                <font color=""#3d85c6"">
                                    <br>
                                </font>
                            </div>
                            <div>
                                <table style=""font-size:12.8px;border:none;border-collapse:collapse;"">
                                    <tbody>
                                        <tr style=""height:0px;"">
                                              <td style=""border:0px solid rgb(0,0,0);vertical-align:top;padding:7px;"">
                                                <div style=""line-height:1.44;margin-top:0pt;margin-bottom:0pt;"">
                                                    <img src=""cid:{3}"">
                                                </div>
                                                    <br>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>", c.Name, c.Surname, c.Email, inlineLogo.ContentId);


                var view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body3, null, "text/html");
                view.LinkedResources.Add(inlineLogo);
                msg.AlternateViews.Add(view);

                try
                {
                    mailClient.Send(msg);
                    return true;
                }
                catch (Exception)
                {
                    // TODO: Handle the exception
                    return false;
                }
            }
        }