Пример #1
0
        private static string FlattenCSSFileAux(string fileContent, Uri path, HashSet <String> doneList, string hostName)
        {
            doneList.Add(RemoveSubRelativeDirs(path.ToString()));

            fileContent = NormalizeCSS(fileContent);

            if (StringUtils.ContainsIgnoreCase(fileContent, "<html>") || StringUtils.ContainsIgnoreCase(fileContent, "<!DOCTYPE"))
            {
                return(string.Empty);
            }

            fileContent = AddPathToURLs(path, fileContent, hostName);

            MatchCollection matches = ScriptableEmailFunctions.GetRegex(@"@import\s+url\s*\(\s*(?:'([^']+)'|""([^""]+)"")\s*\)\s*;").Matches(fileContent);

            if (matches.Count == 0)
            {
                return(fileContent);
            }

            string result = fileContent.Substring(0, matches[0].Index);

            for (int i = 0; i < matches.Count; i++)
            {
                Match  m          = matches[i];
                string location   = m.Groups[1].Value + m.Groups[2].Value;
                int    matchstart = m.Index;
                int    matchend   = m.Index + m.Length; // first char after match

                if (!doneList.Contains(RemoveSubRelativeDirs(location)))
                {
                    try{
                        string externalCss;
                        string externalCssEncoding;
                        if (IsLocal(location))
                        {
                            Uri uri = GetAbsolutePathFromRequest(path, location);
                            EmailHelper.HttpGet(uri.AbsoluteUri, EmailProcessor.MailUA, /*cookie*/ null, out externalCss, out externalCssEncoding);
                            result += FlattenCSSFileAux(externalCss, uri, doneList, hostName);
                        }
                        else
                        {
                            EmailHelper.HttpGet(location, EmailProcessor.MailUA, /*cookie*/ null, out externalCss, out externalCssEncoding);
                            result += FlattenCSSFileAux(externalCss, new Uri(location), doneList, hostName);
                        }
                    }catch {
                    }
                }
                if (i == matches.Count - 1)
                {
                    result += fileContent.Substring(matchend, fileContent.Length - matchend);
                }
                else
                {
                    result += fileContent.Substring(matchend, matches[i + 1].Index - matchend);
                }
            }
            return(result);
        }
Пример #2
0
        // Receives an email in a valid format for an email header, and returns just the
        //	trimmed email address, removing all the other text and delimiters ('<' and '>').
        public static string GetCleanEmailAddress(string address)
        {
            Match match = ScriptableEmailFunctions.GetRegex("<([^>]+)>").Match(address);

            if (match != Match.Empty)
            {
                return(match.Groups[1].Value.Trim());
            }
            return(address.Trim());
        } // GetCleanEmailAddress
Пример #3
0
        } // HttpBinaryGet

        /// <summary>
        /// Removes tags from an HTML string, producing a clean text version of the input
        /// </summary>
        /// <param name="html">The HTML text to be converted</param>
        /// <returns>The resulting text</returns>
        public static string HtmlToText(string html)
        {
            string lineBreak = "-----------LB------------";

            // Strip out title tag
            html = ScriptableEmailFunctions.GetRegex(@"<title[^>]*>(.*?)</title[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, String.Empty);

            // Strip out script tags
            html = ScriptableEmailFunctions.GetRegex(@"<script[^>]*>.*?</script[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, String.Empty);

            // Strip comments
            html = ScriptableEmailFunctions.GetRegex(@"<!--.*?-->", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, String.Empty);

            // Strip out style tags
            html = ScriptableEmailFunctions.GetRegex(@"<style[^>]*>.*?</style[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, String.Empty);

            // Line Breaks
            html = ScriptableEmailFunctions.GetRegex(@"<\s*(br|h[1-3]|p|div|tr|li)[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, lineBreak);
            //html = GetRegex( @"<\s*h1[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            //html = GetRegex( @"<\s*h2[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            //html = GetRegex( @"<\s*h3[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            //html = GetRegex( @"<\s*p[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            //html = GetRegex( @"<\s*div[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            //html = GetRegex( @"<\s*tr[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            //html = GetRegex( @"<\s*li[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);
            html = ScriptableEmailFunctions.GetRegex(@"</\s*(ul|ol)[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, lineBreak);
            //html = GetRegex( @"</\s*ol[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(HTML, lineBreak);

            // Strip out html tags
            html = ScriptableEmailFunctions.GetRegex(@"<[/!]*?[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Replace(html, " ");

            // colapse spaces and \n
            html = ScriptableEmailFunctions.GetRegex(@"\s+", RegexOptions.Singleline).Replace(html, " ");

            //put linebreaks back
            html = ScriptableEmailFunctions.GetRegex(lineBreak).Replace(html, "\r\n");

            // Replace html entities
            html = ReplaceHtmlEntities(html);

            //trim spaces
            html = ScriptableEmailFunctions.GetRegex(@"[ \xA0]+\r\n", RegexOptions.Multiline).Replace(html, "\r\n");

            //trim blank lines
            html = ScriptableEmailFunctions.GetRegex(@"(\r\n){3,}", RegexOptions.Multiline).Replace(html, "\r\n\r\n");

            //trim start
            html = ScriptableEmailFunctions.GetRegex(@"^(\r\n)*", RegexOptions.Singleline).Replace(html, "");

            //trim end
            html = ScriptableEmailFunctions.GetRegex(@"\s*$", RegexOptions.Singleline).Replace(html, "");

            return(html);
        }
Пример #4
0
        private static string RemoveSubRelativeDirs(string path)
        {
            path = ScriptableEmailFunctions.GetRegex(@"/[\.]{1}/([\.]{1}/)*").Replace(path, "/");
            var r1 = ScriptableEmailFunctions.GetRegex(@"[^\.]/\.\.");
            var r2 = ScriptableEmailFunctions.GetRegex(@"[^/\.]+/[\.]{2}/");

            while (r1.IsMatch(path))
            {
                path = r2.Replace(path, "");
            }
            return(path);
        }
Пример #5
0
        /// <summary>
        /// Downloads Text content from the specified URL
        /// </summary>
        /// <param name="ssUrl">URL to get the content from</param>
        /// <param name="method">The request method.</param>
        /// <param name="contentType">The request contentType header</param>
        /// <param name="userAgent">The request userAgent.</param>
        /// <param name="cookie">Cookie to use in the request.</param>
        /// <param name="parameters">Query parameters for the request.</param>
        /// <param name="ssContent">Actual text content downloaded from URL</param>
        /// <param name="ssContentEncoding">The Content enconding.</param>
        public static void HttpGetContent(string ssUrl, string method, string contentType, string userAgent, Cookie cookie, QueryParameter[] parameters, out string ssContent, out string ssContentEncoding)
        {
            ssContent = "";

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(ssUrl);

            if (method != null)
            {
                req.Method = method;
            }
            if (contentType != null)
            {
                req.ContentType = contentType;
            }
            req.AllowAutoRedirect = true;
            req.UserAgent         = userAgent;
            req.CookieContainer   = new CookieContainer();
            if (cookie != null)
            {
                req.CookieContainer.Add(cookie);
            }

            if (parameters != null)
            {
                string urlEncodedParameters = parameters.Select(p => p.Name + "=" + HttpUtility.UrlEncode(p.Value)).StrCat("&");

                using (var requestWriter = new StreamWriter(req.GetRequestStream())) {
                    requestWriter.Write(urlEncodedParameters);
                }
            }

            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) {
                Encoding encoding = null;

                // try get charset from response Content Type
                try {
                    Match charsetMatch = ScriptableEmailFunctions.GetRegex("charset=\"?(.*)\"?", RegexOptions.IgnoreCase).Match(resp.ContentType);
                    if (charsetMatch.Success)
                    {
                        encoding = Encoding.GetEncoding(charsetMatch.Groups[1].Value);
                    }
                } catch {
                }
                if (encoding == null)
                {
                    encoding = Encoding.ASCII;
                }
                using (StreamReader sr = new StreamReader(resp.GetResponseStream(), encoding)) {
                    ssContent = sr.ReadToEnd();
                }
                ssContentEncoding = resp.ContentEncoding;
            }
        } // HttpGet
Пример #6
0
        private static string RemoveFromHtmlIf(string inputHtml, string startReExpr, string endReExpr, HtmlTagFilter @if, bool preserveContents)
        {
            Regex startRe = ScriptableEmailFunctions.GetRegex(startReExpr, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
            Regex endRe   = ScriptableEmailFunctions.GetRegex(endReExpr, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

            StringBuilder sb         = new StringBuilder(inputHtml.Length);
            int           inputIndex = 0;

            var startMc = startRe.Matches(inputHtml);

            foreach (Match startMatch in startMc)
            {
                if (@if(startMatch.Value))
                {
                    // Include everything up to startMatch
                    sb.Append(inputHtml.Substring(inputIndex, startMatch.Index - inputIndex));
                    inputIndex = startMatch.Index + startMatch.Length;

                    var endMatch = endRe.Match(inputHtml, startMatch.Index + startMatch.Length);
                    if (endMatch.Success)
                    {
                        if (preserveContents)
                        {
                            // Include everything up to endMatch
                            sb.Append(inputHtml.Substring(inputIndex, endMatch.Index - inputIndex));
                            inputIndex = endMatch.Index + endMatch.Length;
                        }
                        else
                        {
                            // Do not include anything, just update inputIndex
                            inputIndex = endMatch.Index + endMatch.Length;
                        }
                    }
                }
                else
                {
                    // Include the match
                    sb.Append(inputHtml.Substring(inputIndex, startMatch.Index + startMatch.Length - inputIndex));
                    inputIndex = startMatch.Index + startMatch.Length;
                }
            }

            // Include the remaining of the inputHtml
            sb.Append(inputHtml.Substring(inputIndex));

            return(sb.ToString());
        }
Пример #7
0
 public static string NormalizeCSS(string css)
 {
     if (normalizeCSSRegexs == null)
     {
         normalizeCSSRegexs = new Pair <Regex, string>[] {
             Pair.Create(ScriptableEmailFunctions.GetRegex("/\\*.*?\\*/", RegexOptions.Singleline), ""),
             Pair.Create(ScriptableEmailFunctions.GetRegex("^[ \t]+"), ""),
             Pair.Create(ScriptableEmailFunctions.GetRegex("[ \t]+$"), ""),
             Pair.Create(ScriptableEmailFunctions.GetRegex("[\r\n]+"), "\r\n"),
             Pair.Create(ScriptableEmailFunctions.GetRegex("[ \t]+"), " ")
         };
     }
     foreach (Pair <Regex, string> regex in normalizeCSSRegexs)
     {
         css = regex.First.Replace(css, regex.Second);
     }
     return(css);
 }
Пример #8
0
        private static string RemoveFromHtmlFormActionAndOnSubmit(string inputHtml)
        {
            Regex formPattern     = ScriptableEmailFunctions.GetRegex("<\\s*form\\b[^>]*>", RegexOptions.IgnoreCase);
            Regex actionPattern   = ScriptableEmailFunctions.GetRegex("action=(?:(?:\"[^\"]*\")|(?:'[^']*'))", RegexOptions.IgnoreCase);
            Regex onSubmitPattern = ScriptableEmailFunctions.GetRegex("onsubmit=(?:(?:\"[^\"]*\")|(?:'[^']*'))", RegexOptions.IgnoreCase);

            StringBuilder sb         = new StringBuilder(inputHtml.Length);
            int           inputIndex = 0;
            Match         startMatch = formPattern.Match(inputHtml);

            // Include the text up to match
            sb.Append(inputHtml.Substring(inputIndex, startMatch.Index));
            inputIndex = startMatch.Index + startMatch.Length;

            //Append modified match
            sb.Append(onSubmitPattern.Replace(actionPattern.Replace(startMatch.Value, "action=\"-\""), "onsubmit=\"\""));

            // Include the remaining of the inputHtml
            sb.Append(inputHtml.Substring(inputIndex));

            return(sb.ToString());
        }
        public static string Normalize(string addresses)
        {
            if (addresses == null)
            {
                return("");
            }

            StringBuilder buf   = new StringBuilder();
            bool          first = true;

            foreach (string emailAddr in addresses.Split(',', ';'))
            {
                string trimmedEmail = emailAddr.Trim();
                if (!trimmedEmail.IsEmpty())
                {
                    trimmedEmail = EncloseEmail(trimmedEmail);
                    if (!ScriptableEmailFunctions.IsValid(trimmedEmail))
                    {
                        throw new ArgumentException("'" + emailAddr + "' is not a valid email address.");
                    }

                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        buf.Append(", ");
                    }

                    buf.Append(trimmedEmail);
                }
            }

            return(buf.ToString());
        }
Пример #10
0
        // Parses an HTML body looking for elements with src or href attributes
        // and trying to resolve the uri's into absolute uris.
        // If calcCIDs is set it will assign a ContentID to each image
        // If replaceByCIDs is set it will replace the image url with a CID url
        internal static void HtmlProcessPaths(string html, string url, bool calcCIDs, bool replaceByCIDs, out string result, out StringCollection uris, out Hashtable uri2cidMap)
        {
            StringBuilder sb = new StringBuilder(html);

            uris       = new StringCollection();
            uri2cidMap = new Hashtable();

            //#33590 - Added [^#] to the regular expression to make it skip named anchors inside the same page (relative named anchors)
            //#382261 - Added support url's already using data URI schemes data: cid: mid:
            Regex regex = ScriptableEmailFunctions.GetRegex("([^\\(]\\s+src|\\s+href)=['\"]((data:|cid:|mid:)?[^#][^'\"]*)['\"]", RegexOptions.IgnoreCase);
            int   originalHTMLoffsetDifference = 0;

            foreach (Match match in regex.Matches(html))
            {
                bool dataUriSchemeFound = match.Groups[3].Success;
                if (dataUriSchemeFound)
                {
                    continue;
                }

                string g1     = match.Groups[1].Value;
                string imgUrl = match.Groups[2].Value;

                Uri absUri = null;
                try {
                    absUri = new Uri(new Uri(url), imgUrl);
                } catch { }
                if (absUri != null)
                {
                    string absoluteUrl = absUri.AbsoluteUri;
                    string newurl      = absoluteUrl;

                    if (!uris.Contains(absoluteUrl))
                    {
                        if ((calcCIDs) && (g1.ToLower().Substring(g1.Length - 3, 3) == "src"))
                        {
                            string cid = Guid.NewGuid().ToString();
                            uri2cidMap.Add(absoluteUrl, cid);
                            newurl = string.Concat("cid:", cid);
                        }
                        uris.Add(absoluteUrl);
                    }
                    else
                    {
                        string cid = (string)uri2cidMap[absoluteUrl];
                        if (cid != null)
                        {
                            newurl = string.Concat("cid:", cid);
                        }
                    }

                    if (newurl != imgUrl)
                    {
                        if (replaceByCIDs)
                        {
                            sb.Replace(imgUrl,
                                       newurl,
                                       match.Groups[2].Index + originalHTMLoffsetDifference,
                                       match.Groups[2].Length);

                            originalHTMLoffsetDifference += newurl.Length - imgUrl.Length;
                        }
                        else
                        {
                            sb.Replace(imgUrl,
                                       absoluteUrl,
                                       match.Groups[2].Index + originalHTMLoffsetDifference,
                                       match.Groups[2].Length);

                            originalHTMLoffsetDifference += absoluteUrl.Length - imgUrl.Length;
                        }
                    }
                    //html = html.Substring(0,mat.Groups[2].Index) + absoluteUrl + html.Substring(mat.Groups[2].Index+mat.Groups[2].Length);
                }
            }
            result = ScriptableEmailFunctions.GetRegex("/\\(........................\\)/").Replace(sb.ToString(), "/");
        }
Пример #11
0
 private static string ReplaceHtmlEntities(string html)
 {
     return(ScriptableEmailFunctions.GetRegex(@"&[^;]{2,7};").Replace(html, new MatchEvaluator(HTMLDecode)));
 }
Пример #12
0
        /// <summary>
        /// Initializes the production of an email message, creating its headers and main body. Note that this
        /// action does not immediately send the message, as you may want to add futher parts (attachments) to
        /// it (using <see cref="AddPart" />). To finalize message and send it you should then call RichMailSend
        /// </summary>
        /// <remarks>
        /// Older emails clients (such as some versions of Lotus and Outlook 2000) do not correctly support the MIME encoding used to send HTML emails. To enable HTML emails to be delivered correctly to these clients you can add &quot;lotus/compatible&quot; (without the quotes) to the ContentType. This will change how the whole email is created and allows those clients to shows the message properly at the expense of more recent email clients (such as Yahoo! Mail) that will not display the message correctly.
        /// </remarks>
        /// <param name="processAddresses">Pre-process the email addresses?</param>
        /// <param name="ssFrom">Email address of the sender</param>
        /// <param name="ssTo">Email addresses to send the email to (comma separated)</param>
        /// <param name="headers">Email header information</param>
        /// <param name="ssCc">Email addresses to carbon-copy the email to (comma separated)</param>
        /// <param name="ssBcc">Email addresses to blind carbon-copy the email to (comma separated)</param>
        /// <param name="ssContentType">MIME type of the message.</param>
        /// <param name="ssCharset">Character used in the message text</param>
        /// <param name="ssSubject">Subject of the message</param>
        /// <param name="ssBody">Text content of the message</param>
        /// <param name="ssBodyIsHtml">TRUE if content of the message is HTML rather than plain text</param>
        /// <param name="ssUrl">Base URL to use in case the Body is HTML. This allows any relative paths that may exist in the Body to be expanded to full blown URL's</param>
        /// <param name="ssIncludeImages">If TRUE, any images referenced via an URL in the Body are attached to the message</param>
        /// <param name="ssInReplyTo">Alternate reply-to email address</param>
        /// <param name="userAgent">User agent to use to request the email messages.</param>
        /// <param name="realHostname">The hostname to use when building links in the email body.</param>
        /// <param name="zoneAddress">Deploymentzoneadress of the running espace</param>
        /// <param name="ssBoundary">System marker that should be passed in to any further parts that are added to this message (see <see cref="AddPart" />).</param>
        /// <param name="ssMail">The full message text produced by the call</param>
        /// <param name="emailId">The created email id.</param>
        public static void CreateEmail(bool processAddresses, string ssFrom, string ssTo, List <String> headers, string ssCc, string ssBcc, string ssContentType, string ssCharset, string ssSubject, string ssBody, bool ssBodyIsHtml, string ssUrl, bool ssIncludeImages, string ssInReplyTo, string userAgent, string realHostname, string zoneAddress, out string ssBoundary, out string ssMail, out string emailId)
        {
            bool prepareMimeEncoding = true;
            //string base64 = null;
            bool use_multipart_related = true;

            ssBoundary = "";
            System.Text.StringBuilder sbMail = new System.Text.StringBuilder();

            if (realHostname == null)
            {
                throw new InvalidOperationException("The 'Default DNS Name' must be set in Service Center's Environment Configuration to send emails.");
            }

            // Cleanup the content type
            ssContentType = EmailHelper.TrimHeaderLine(ssContentType);

            // This is a hack to support Outlook 2000 and other clients
            // that do not support multipart/related.
            int tpos = ssContentType.ToUpper().IndexOf("LOTUS/COMPATIBLE");

            if (tpos >= 0)
            {
                ssContentType         = ssContentType.Remove(tpos, 16);
                use_multipart_related = false;
            }

            // If no Content Type defined, set it to "multipart/mixed"
            if (ssContentType == "")
            {
                ssContentType = "multipart/mixed";
            }

            if (!ssContentType.ToLower().StartsWith("multipart"))
            {
                // If it's not a multipart message then don't encase in MIME containers
                prepareMimeEncoding = false;
            }

            if (ssBodyIsHtml)
            {
                prepareMimeEncoding = true;
            }

            // If no Content Type defined, set it to "multipart/mixed"
            if (ssCharset == "")
            {
                ssCharset = "iso-8859-1";
            }
            else
            {
                ssCharset = EmailHelper.TrimHeaderLine(ssCharset);
            }

            // Get a correct encoder
            System.Text.Encoding mailEncoding = System.Text.Encoding.GetEncoding(ssCharset);

            if (prepareMimeEncoding)
            {
                // Get a random boundary
                ssBoundary = EmailHelper.CreateRandomBoundary();
            }
            else
            {
                ssBoundary = "";
            }

            // Add date to email header
            sbMail.Append("Date: ");
            sbMail.Append(EmailHelper.GetEmailDate(System.DateTime.Now));
            sbMail.Append("\r\n");

            if (processAddresses)
            {
                ssFrom = EmailHelper.ProcessEmailAddresses(mailEncoding, ssFrom);
            }

            emailId = System.Guid.NewGuid().ToString().Replace("-", "") + "@" + RuntimePlatformSettings.EMail.ServerHost.GetValue();
            // Add the EmailID
            sbMail.Append("Message-ID: <" + emailId + ">\r\n");


            // Add from to email header
            sbMail.Append("From: ");
            sbMail.Append(ssFrom);
            sbMail.Append("\r\n");

            if (processAddresses)
            {
                // If any of the email addresses in the To field are in the format
                // "description <email address>", then encode with iso-8859-1 the description.
                ssTo = EmailHelper.ProcessEmailAddresses(mailEncoding, ssTo);
            }

            // Add to to email header
            sbMail.Append("To: ");
            sbMail.Append(ssTo);
            sbMail.Append("\r\n");

            // Add headers

            if (headers != null)
            {
                foreach (String header in headers)
                {
                    sbMail.Append(header);
                    sbMail.Append("\r\n");
                }
            }

            // If cc not empty, add it to email header
            if (ssCc != "")
            {
                if (processAddresses)
                {
                    // If any of the email addresses in the Cc field are in the format
                    // "description <email address>", then encode with iso-8859-1 the description.
                    ssCc = EmailHelper.ProcessEmailAddresses(mailEncoding, ssCc);
                }

                // Add it to the email header
                sbMail.Append("Cc: ");
                sbMail.Append(ssCc);
                sbMail.Append("\r\n");
            }

            ssInReplyTo = EmailHelper.TrimHeaderLine(ssInReplyTo);

            // Add In-Reply-To to email header
            if (ssInReplyTo != "")
            {
                sbMail.Append("In-Reply-To:");
                sbMail.Append(ssInReplyTo);
                sbMail.Append("\r\n");
            }

            ssSubject = EmailHelper.TrimHeaderLine(ssSubject);

            EncodeFlags headerEncodeFlags = EncodeFlags.SingleLine | EncodeFlags.QuotedPrintable;

            // Encode the subject
            if (EmailEncoding.NeedsEncoding(mailEncoding, ssSubject, headerEncodeFlags))
            {
                ssSubject = EmailEncoding.EncodeString(mailEncoding, ssSubject, headerEncodeFlags);
            }

            // Add subject to email header
            sbMail.Append("Subject: ");
            sbMail.Append(ssSubject);
            sbMail.Append("\r\n");

            // Add content type to email header
            if (prepareMimeEncoding)
            {
                sbMail.Append("MIME-Version: 1.0\r\n");
            }
            if (prepareMimeEncoding)
            {
                sbMail.Append("Content-Type: " + ssContentType + "; boundary=\"" + ssBoundary + "\"\r\n");
            }
            else
            {
                sbMail.Append("Content-Type: " + ssContentType + "; charset=\"" + ssCharset + "\"\r\n");
                sbMail.Append("Content-Transfer-Encoding: base64\r\n");
            }

            //sbMail += "Content-Transfer-Encoding: base64\r\n";
            if (prepareMimeEncoding)
            {
                sbMail.Append("\r\n");

                // For older clients to display something
                sbMail.Append("This is a multi-part message in MIME format.\r\n");

                // Dump the starting boundary
                sbMail.Append("--" + ssBoundary + "\r\n");
            }

            // Add body header to email
            //System.Text.Encoding bodyEncoding = System.Text.Encoding.GetEncoding(ssCharset);
            if (ssBodyIsHtml)
            {
                // Outlook 2000 is too old by now and treats emails using MULTIPART/RELATED as
                // MULTIPART/MIXED (which is standards compliant).
                // Thus if a tree like the following is used it will show an empty email
                // with two attachments. The first attachment is an email and a second one is the attachment file.
                //   Begin Message
                //     Begin Mixed Content
                //       Begin Related Contnt
                //         Begin Alternative Content
                //           Plain text message
                //           HTML Message message
                //         End Alternative Content
                //         Image
                //       End Related Content
                //       Attachment
                //     End Mixed Content
                //   End Message
                //
                // To avoid this we now have a flag that disables the use of MULTIPART/RELATED
                // and uses a tree like this :
                //   Begin Message
                //     Begin Mixed Content
                //       Begin Alternative Content
                //         Plain text message
                //         HTML Message message
                //       End Alternative Content
                //       Image
                //       Attachment
                //     End Mixed Content
                //   End Message

                string relatedBoundary = null;
                if (use_multipart_related)
                {
                    relatedBoundary = EmailHelper.CreateRandomBoundary();
                }

                string           alternateBoundary = EmailHelper.CreateRandomBoundary();
                string           normBody;
                Hashtable        uri2cidMap;
                StringCollection uris;

                // remove meta content type
                normBody = ScriptableEmailFunctions.GetRegex("<meta +http-equiv='?\"?content-type[^>]+>", RegexOptions.IgnoreCase).Replace(ssBody, "");

                // Place stylesheet inline
                var match = ScriptableEmailFunctions.GetRegex("<link [^>]*href=\"([^\"]+\\.css)(\\?[0-9_]+)?\"[^>]*>", RegexOptions.IgnoreCase).Match(normBody);
                if (match.Success)
                {
                    string css;
                    Uri    absUri = null;
                    try {
                        absUri = new Uri(new Uri(ssUrl), match.Groups[1].Value);
                    } catch { }
                    if (absUri != null)
                    {
                        string cssEncoding;
                        EmailHelper.HttpGet(absUri.AbsoluteUri, MailUA, null, out css, out cssEncoding);
                        css      = EmailHelper.NormalizeCSS(css);
                        normBody = normBody.Substring(0, match.Index) + "<style>" + css + "</style>" + normBody.Substring(match.Index + match.Length, normBody.Length - match.Index - match.Length);
                    }
                }

                string returnBody;
                EmailHelper.HtmlProcessPaths(normBody, ssUrl, ssIncludeImages, use_multipart_related, out returnBody, out uris, out uri2cidMap);
                normBody = returnBody;

                // Replace localhost with the real name for any unescaped link that occurred (normal destinations are already ok)
                if (realHostname != null)   //just for sanity check
                {
                    normBody = ReplaceLinksWithEnvAddress(realHostname, zoneAddress, normBody);
                }

                string images = EmailHelper.HtmlFetchImages(ssIncludeImages, ssBoundary, use_multipart_related, relatedBoundary, uri2cidMap, userAgent);
                EmailHelper.HtmlAppendImages(ssCharset, EmailEncoding.MaxEncodedLength, use_multipart_related, sbMail, mailEncoding, relatedBoundary, alternateBoundary, normBody, images);
            }
            else if (ssBody != "")
            {
                if (prepareMimeEncoding)
                {
                    sbMail.Append("Content-Type: text/plain; charset=\"" + ssCharset + "\"\r\n");
                    sbMail.Append("Content-Transfer-Encoding: base64\r\n");
                }
                sbMail.Append("\r\n");

                // Encode body and add it to the email
                sbMail.Append(EmailEncoding.GetBase64TextBlock(mailEncoding.GetBytes(ssBody), EmailEncoding.MaxEncodedLength));
            }
            else
            {
                sbMail.Append("\r\n");
            }

            ssMail = sbMail.ToString();
        } // CreateEmail
Пример #13
0
        public static int CreateEmail(string bodyUrl, string emailSubject, string emailBody,
                                      string from, string to, string cc, string bcc,
                                      int activityId, int tenantId, int eSpaceId, string emailDefSSKey, bool storeContent,
                                      List <String> headers, List <EmailAttachment> attachments, string realHostname, string zoneAddress)
        {
            NormalizeFields(ref from, ref to, ref cc, ref bcc);

            string subject = emailSubject;
            string charset = "UTF-8";

            Regex titleRe    = ScriptableEmailFunctions.GetRegex("<title>([^<]*)</title>", RegexOptions.IgnoreCase);
            Match titleMatch = titleRe.Match(emailBody);

            if (titleMatch.Success)
            {
                subject = HttpUtility.HtmlDecode(titleMatch.Groups[1].Value.Trim());
            }

            emailBody = CleanEmailBody(emailBody);

            // #122347 TODO: process obtained emailBody to separate attachments from body

            string emailBoundary;
            string pathUrl = bodyUrl.Substring(0, bodyUrl.LastIndexOf('/') + 1);
            string messageId;
            string content;

            CreateEmail(false, // the email addresses need to be correctly formated already (using the provided functions), processing them would re-encode them
                               //multipart/related
                        from, to, headers, cc, bcc, "", charset, subject, emailBody, true, pathUrl, true, "", MailUA, realHostname,
                        zoneAddress, out emailBoundary, out content, out messageId);

            StringBuilder emailContent = new StringBuilder();

            emailContent.Append(content);

            if (attachments != null)
            {
                foreach (EmailAttachment att in attachments)
                {
                    string newPart;
                    string encodedFilename = att.FileName;
                    if (EmailEncoding.NeedsEncoding(Encoding.UTF8, att.FileName, EncodeFlags.QuotedPrintable))
                    {
                        encodedFilename = EmailEncoding.EncodeString(Encoding.UTF8, att.FileName, EncodeFlags.QuotedPrintable);
                    }
                    AddPart(HeaderFlags.ContentType | HeaderFlags.ContentDisposition, att.MimeType, null, emailBoundary, encodedFilename, null, att.FileContent, "base64", out newPart);
                    emailContent.Append(newPart);
                }
            }

            // Close email
            emailContent.Append("--" + emailBoundary + "--\r\n");
            emailContent.Append("\r\n");

            string       finalContent = emailContent.ToString();
            int          contentLen   = finalContent.Length;
            UTF8Encoding encoder      = new UTF8Encoding();

            byte[] byteContent = encoder.GetBytes(finalContent);

            using (Transaction trans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                return(DBRuntimePlatform.Instance.SaveEmail(trans,
                                                            EmailHelper.GetCleanEmailAddress(from),
                                                            EmailHelper.GetCleanEmailAddresses(to),
                                                            EmailHelper.GetCleanEmailAddresses(cc),
                                                            EmailHelper.GetCleanEmailAddresses(bcc),
                                                            subject, byteContent, contentLen, activityId, tenantId, eSpaceId, emailDefSSKey, storeContent, messageId,
                                                            AppInfo.GetAppInfo().Properties.EnableEmails,
                                                            AppInfo.GetAppInfo().Properties.TestEmails));
            }
        }