Exemple #1
0
        private ObjectWHeaders GetView(string contentTypeCategory, string contentTypeSpecific)
        {
            // Full match
            string contentType = contentTypeCategory + "/" + contentTypeSpecific;

            if (ContentType.Equals(contentType, StringComparison.OrdinalIgnoreCase) ||
                ContentType.StartsWith(contentType + ";", StringComparison.OrdinalIgnoreCase))
            {
                return(this);
            }

            ObjectWHeaders match = AlternateViews.Where(view =>
                                                        view.ContentType.Equals(contentType, StringComparison.OrdinalIgnoreCase) ||
                                                        ContentType.StartsWith(contentType + ";", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            if (match != null)
            {
                return(match);
            }

            // partial match
            if (ContentType.StartsWith(contentTypeCategory + "/", StringComparison.OrdinalIgnoreCase))
            {
                return(this);
            }
            return(AlternateViews.Where(view =>
                                        view.ContentType.StartsWith(contentTypeCategory + "/", StringComparison.OrdinalIgnoreCase)).FirstOrDefault());
        }
Exemple #2
0
        public void Load(Stream reader, bool headersOnly = false, int maxLength = 0)
        {
            _HeadersOnly = headersOnly;
            Headers      = null;
            Body         = null;

            if (headersOnly)
            {
                RawHeaders = reader.ReadToEnd(maxLength, _DefaultEncoding);
            }
            else
            {
                var entireMessage = reader.ReadToEnd(maxLength, _DefaultEncoding).Split('\n');
                var index         = 0;
                var headers       = entireMessage
                                    .TakeWhile((x, i) => x.Trim().Length > 0 && (index = i) >= 0);
                RawHeaders = String.Join(Environment.NewLine, headers);

                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    //else this is a multipart Mime Message
                    //using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
                    ParseMime(String.Join(Environment.NewLine, entireMessage.SkipWhile((x, i) => i <= index || x.Trim().Length == 0)), boundary);
                }
                else
                {
                    SetBody(String.Join(Environment.NewLine, entireMessage.SkipWhile((x, i) => i <= index || x.Trim().Length == 0)));
                }
            }

            if (string.IsNullOrWhiteSpace(Body) && AlternateViews.Count > 0)
            {
                var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain"));
                if (att == null)
                {
                    att = AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));
                }

                if (att != null)
                {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType             = att.Headers["Content-Type"].RawValue;
                }
            }

            Date      = Headers.GetDate();
            To        = Headers.GetAddresses("To").ToList();
            Cc        = Headers.GetAddresses("Cc").ToList();
            Bcc       = Headers.GetAddresses("Bcc").ToList();
            Sender    = Headers.GetAddresses("Sender").FirstOrDefault();
            ReplyTo   = Headers.GetAddresses("Reply-To").ToList();
            From      = Headers.GetAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }
Exemple #3
0
        //////////////////////////////////////////////////
        /// @brief Change la vue du mail en html ou plaintext
        //////////////////////////////////////////////////
        private void ChargeAlternateView(string text, string charset)
        {
            var View = AlternateView.CreateAlternateViewFromString(text);

            View.ContentType      = new System.Net.Mime.ContentType(charset);
            View.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            AlternateViews.Add(View);
        }
Exemple #4
0
        /// <summary>
        /// Build an email conteining the link to the private form.
        /// </summary>
        /// <param name="receiverMail">the recipient mail address</param>
        /// <param name="publication">the publication</param>
        /// <param name="compilationRequest">the compilation request</param>
        public MailForPublicForm(MailAddress receiverMail, Storage.Publication publication, Storage.CompilationRequest compilationRequest)
        {
            From = senderAdd;
            To.Add(receiverMail);

            //Subject = "Floading - Form pubblica creata!";
            Subject = _Subject;

            Object[] parameters = new Object[4];
            parameters[0] = publication.namePublication;
            parameters[1] = Token.ToLink(publication, compilationRequest);
            if (compilationRequest == null)
            {
                parameters[2] = "CompilationRequestID: " + "-1";
                parameters[3] = "CompilationRequestID: " + "-1";
            }
            else
            {
                parameters[2] = "CompilationRequestID: " + compilationRequest.compilReqID;
                parameters[3] = "CompilationRequestID: " + compilationRequest.compilReqID;
            }
            //Metto caratteri speciali giusti. Il db li codifica diversamenti, qui li rimetto a posto.
            string message = String.Format(_bodyPlainTextFormat, parameters);
            int    index;
            string sub;

            index = message.IndexOf("\\n");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\n");
            }
            index = message.IndexOf("\\r");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\n");
            }
            index = message.IndexOf("\\t");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\t");
            }
            AlternateView alternatePLAIN = AlternateView.CreateAlternateViewFromString(message, new System.Net.Mime.ContentType("text/plain"));

            alternatePLAIN.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
            //if (alternatePLAIN==null || alternateHTML==null) return;
            if (alternatePLAIN == null)
            {
                return;
            }
            //AlternateViews.Add(alternateHTML);
            AlternateViews.Add(alternatePLAIN);
        }
Exemple #5
0
 public virtual void Add(Attachment viewOrAttachment)
 {
     if (viewOrAttachment.IsAttachment)
     {
         Attachments.Add(viewOrAttachment);
     }
     else
     {
         AlternateViews.Add(viewOrAttachment);
     }
 }
        private MailMimeMessage AddAlternateView(MimeReader reader)
        {
            var alternateView = new AlternateView(new MemoryStream(reader.GetContent(), false), reader.ContentType);
            var te            = reader.GetTransferEncoding();

            if (te != TransferEncoding.Unknown)
            {
                alternateView.TransferEncoding = te;                                 //fix bug for Content-Type: text/html;
            }
            try { alternateView.ContentId = TrimBrackets(Headers["content-id"] + ""); }
            catch { } //refactor
            AlternateViews.Add(alternateView);
            return(this);
        }
Exemple #7
0
        private MailMessage ConstructEmail(IdentityMessage message)
        {
            var mailMessage = new MailMessage {
                Subject = message.Subject
            };

            mailMessage.IsBodyHtml = IsHtml;

            if (AlternateViews.Any())
            {
                foreach (var view in AlternateViews)
                {
                    mailMessage.AlternateViews.Add(view);
                }
            }
            else
            {
                mailMessage.Body = message.Body;
            }

            if (!string.IsNullOrEmpty(From))
            {
                mailMessage.From = new MailAddress(From);
            }

            mailMessage.To.Add(new MailAddress(message.Destination));

            foreach (var attachedFileInformation in Attachments)
            {
                var mimeType = DocumentExtensions.GetMimeTypeForFile(attachedFileInformation.Key);
                mailMessage.Attachments.Add(new Attachment(attachedFileInformation.Value, mimeType)
                {
                    Name = attachedFileInformation.Key
                });
            }

            mailMessage.IsBodyHtml = IsHtml;

            return(mailMessage);
        }
Exemple #8
0
        private string ParseBody()
        {
            var body = String.Join(Environment.NewLine, _message
                                   // skip the headers
                                   .SkipWhile((x, i) => x.Trim().Length > 0 && i >= 0)
                                   // skip the blanks after the headers
                                   .SkipWhile((x, i) => x.Trim().Length == 0));

            if (!string.IsNullOrEmpty(Boundary))
            {
                ParseMime(body, Boundary);
                if (AlternateViews.Count > 0)
                {
                    var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain")) ??
                              AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));

                    if (att != null)
                    {
                        return(att.Body);
                    }
                }
            }
            else
            {
                if (ContentTransferEncoding.Is("quoted-printable"))
                {
                    return(Utilities.DecodeQuotedPrintable(body, _encoding));
                }
                if (ContentTransferEncoding.Is("base64")
                    //only decode the content if it is a text document
                    && ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase))
                {
                    return(_encoding.GetString(Convert.FromBase64String(body)));
                }
                return(body);
            }
            return(String.Empty);
        }
        public virtual void Save(System.IO.TextWriter txt)
        {
            txt.WriteLine("Date: {0}", (Date == DateTime.MinValue ? LocalTime.Now : Date).GetRFC2060Date());
            txt.WriteLine("To: {0}", string.Join("; ", To.Select(x => x.ToString())));
            txt.WriteLine("Cc: {0}", string.Join("; ", Cc.Select(x => x.ToString())));
            txt.WriteLine("Reply-To: {0}", string.Join("; ", ReplyTo.Select(x => x.ToString())));
            txt.WriteLine("Bcc: {0}", string.Join("; ", Bcc.Select(x => x.ToString())));
            if (Sender != null)
            {
                txt.WriteLine("Sender: {0}", Sender);
            }
            if (From != null)
            {
                txt.WriteLine("From: {0}", From);
            }
            if (!string.IsNullOrEmpty(MessageID))
            {
                txt.WriteLine("Message-ID: {0}", MessageID);
            }

            var otherHeaders = Headers.Where(x => !SpecialHeaders.Contains(x.Key, StringComparer.InvariantCultureIgnoreCase));

            foreach (var header in otherHeaders)
            {
                txt.WriteLine("{0}: {1}", header.Key, header.Value);
            }

            if (Importance != MailPriority.Normal)
            {
                txt.WriteLine("Importance: {0}", (int)Importance);
            }
            txt.WriteLine("Subject: {0}", Subject);

            string boundary = null;

            if (Attachments.Any() || AlternateViews.Any())
            {
                boundary = $"--boundary_{Guid.NewGuid()}";
                txt.WriteLine("Content-Type: multipart/mixed; boundary={0}", boundary);
            }

            // signal end of headers
            txt.WriteLine();

            if (boundary != null)
            {
                txt.WriteLine("--" + boundary);
                txt.WriteLine();
            }

            txt.WriteLine(Body);

            AlternateViews.Union(Attachments).ToList().ForEach(att =>
            {
                txt.WriteLine("--" + boundary);
                txt.WriteLine(string.Join("\n", att.Headers.Select(h => $"{h.Key}: {h.Value}")));
                txt.WriteLine();
                txt.WriteLine(att.Body);
            });

            if (boundary != null)
            {
                txt.WriteLine("--" + boundary + "--");
            }
        }
Exemple #10
0
 /// <summary>
 /// 添加一个电子邮件不同格式的副本。
 /// </summary>
 /// <param name="alternateView">电子邮件视图</param>
 public void AddAlternateView(AlternateView alternateView)
 {
     MailValidatorHelper.ValideArgumentNull <AlternateView>(alternateView, "alternateView");
     AlternateViews.Add(alternateView);
 }
        public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char?termChar = null)
        {
            HeadersOnly = headersOnly;
            Headers     = null;
            Body        = null;
            if (maxLength == 0)
            {
                return;
            }

            var    headers = new StringBuilder();
            string line;

            while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null)
            {
                if (line.Length == 0)
                {
                    if (headers.Length == 0)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                headers.AppendLine(line);
            }

            RawHeaders = headers.ToString();

            if (!headersOnly)
            {
                var boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    var atts = new List <Attachment>();
                    var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
                    if (!string.IsNullOrEmpty(body))
                    {
                        SetBody(body);
                    }

                    foreach (var att in atts)
                    {
                        (att.IsAttachment ? Attachments : AlternateViews).Add(att);
                    }

                    if (maxLength > 0)
                    {
                        reader.ReadToEnd(maxLength, Encoding);
                    }
                }
                else
                {
                    //  sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
                    var body = string.Empty;
                    if (maxLength > 0)
                    {
                        body = reader.ReadToEnd(maxLength, Encoding);
                    }

                    SetBody(body);
                }
            }
            else if (maxLength > 0)
            {
                reader.ReadToEnd(maxLength, Encoding);
            }

            if ((string.IsNullOrWhiteSpace(Body) || ContentType.StartsWith("multipart/")) && AlternateViews.Count > 0)
            {
                var att = AlternateViews.GetTextView() ?? AlternateViews.GetHtmlView();
                if (att != null)
                {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType             = att.Headers["Content-Type"].RawValue;
                }
            }

            Date = Headers.GetDate();
            try { To = Headers.GetMailAddresses("To").ToList(); } catch { }
            try { Cc = Headers.GetMailAddresses("Cc").ToList(); } catch { }
            try { Bcc = Headers.GetMailAddresses("Bcc").ToList(); } catch { }
            try { Sender = Headers.GetMailAddresses("Sender").FirstOrDefault(); } catch { }
            try { ReplyTo = Headers.GetMailAddresses("Reply-To").ToList(); } catch { }
            try { From = Headers.GetMailAddresses("From").FirstOrDefault(); } catch { }
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }
Exemple #12
0
 /// <summary>
 /// 添加一个电子邮件不同格式的副本。
 /// </summary>
 /// <param name="mailContent">电子邮件内容</param>
 public void AddAlterViewContent(string mailContent)
 {
     MailValidatorHelper.ValideStrNullOrEmpty(mailContent, "mailContent");
     AlternateViews.Add(AlternateView.CreateAlternateViewFromString(mailContent));
 }
Exemple #13
0
 /// <summary>
 /// 添加一个电子邮件不同格式的副本。
 /// </summary>
 /// <param name="contentStream">电子邮件内容流</param>
 public void AddAlterViewStream(Stream contentStream)
 {
     MailValidatorHelper.ValideArgumentNull <Stream>(contentStream, "contentStream");
     AlternateViews.Add(new AlternateView(contentStream));
 }
Exemple #14
0
        public virtual void Save(TextWriter txt)
        {
            txt.WriteLine("Date: {0}", Date.GetRFC2060Date());
            txt.WriteLine("To: {0}", string.Join("; ", To.Select(x => x.ToString())));
            txt.WriteLine("Cc: {0}", string.Join("; ", Cc.Select(x => x.ToString())));
            txt.WriteLine("Reply-To: {0}", string.Join("; ", ReplyTo.Select(x => x.ToString())));
            txt.WriteLine("Bcc: {0}", string.Join("; ", Bcc.Select(x => x.ToString())));
            if (Sender != null)
            {
                txt.WriteLine("Sender: {0}", Sender);
            }
            if (From != null)
            {
                txt.WriteLine("From: {0}", From);
            }
            if (!string.IsNullOrEmpty(MessageID))
            {
                txt.WriteLine("Message-ID: {0}", MessageID);
            }

            var otherHeaders = Headers.Where(x => !SpecialHeaders.Contains(x.Key, StringComparer.InvariantCultureIgnoreCase));

            foreach (var header in otherHeaders)
            {
                txt.WriteLine("{0}: {1}", header.Key, header.Value);
            }
            if (Importance != MailPriority.Normal)
            {
                txt.WriteLine("Importance: {0}", (int)Importance);
            }
            txt.WriteLine("Subject: {0}", Subject);

            string boundary = null;

            if (Attachments.Any() || AlternateViews.Any())
            {
                boundary = string.Format("--boundary_{0}", Guid.NewGuid());
                txt.WriteLine("Content-Type: multipart/mixed; boundary={0}", boundary);
            }

            // signal end of headers
            txt.WriteLine();

            if (!string.IsNullOrWhiteSpace(Body))
            {
                if (boundary != null)
                {
                    txt.WriteLine("--" + boundary);
                    txt.WriteLine();
                }

                txt.Write(Body);
            }

            AlternateViews.ToList().ForEach(view =>
            {
                txt.WriteLine();
                txt.WriteLine("--" + boundary);
                txt.WriteLine(string.Join("\r\n", view.Headers.Select(h => string.Format("{0}: {1}", h.Key, h.Value))));
                txt.WriteLine();
                if (view.Scope >= Scope.HeadersAndBodySnyppit)
                {
                    txt.WriteLine(view.Body);
                }
            });


            this.Attachments.ToList().ForEach(att =>
            {
                txt.WriteLine();
                txt.WriteLine("--" + boundary);
                txt.WriteLine(string.Join("\r\n", att.Headers.Select(h => string.Format("{0}: {1}", h.Key, h.Value))));
                txt.WriteLine();
                if (att.Scope >= Scope.HeadersAndBodySnyppit)
                {
                    txt.WriteLine(att.Body);
                }
            });

            if (boundary != null)
            {
                txt.WriteLine("--" + boundary + "--");
            }
        }
Exemple #15
0
        // 指定一个电子邮件不同格式的副本。
        //(eg:发送HTML格式的邮件,可能希望同时提供邮件的纯文本格式,以防止一些收件人使用的电子邮件阅读程序无法显示html内容)

        /// <summary>
        /// 添加一个电子邮件不同格式的副本。
        /// </summary>
        /// <param name="filePath">包含电子邮件内容的文件路径</param>
        public void AddAlterViewPath(string filePath)
        {
            MailValidatorHelper.ValideStrNullOrEmpty(filePath, "filePath");
            AlternateViews.Add(new AlternateView(filePath));
        }
Exemple #16
0
        public void Load(TextReader reader, bool headersOnly = false)
        {
            _HeadersOnly = headersOnly;
            Headers      = null;
            Body         = null;

            if (headersOnly)
            {
                RawHeaders = reader.ReadToEnd();
            }
            else
            {
                var    headers = new StringBuilder();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Trim().Length == 0)
                    {
                        if (headers.Length == 0)
                        {
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                    headers.AppendLine(line);
                }
                RawHeaders = headers.ToString();

                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    //else this is a multipart Mime Message
                    using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
                        ParseMime(subreader, boundary);
                }
                else
                {
                    SetBody((line + Environment.NewLine + reader.ReadToEnd()).Trim());
                }
            }

            if (string.IsNullOrWhiteSpace(Body) && AlternateViews.Count > 0)
            {
                var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain"));
                if (att == null)
                {
                    att = AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));
                }

                if (att != null)
                {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType             = att.Headers["Content-Type"].RawValue;
                }
            }

            Date      = Headers.GetDate();
            To        = Headers.GetAddresses("To").ToList();
            Cc        = Headers.GetAddresses("Cc").ToList();
            Bcc       = Headers.GetAddresses("Bcc").ToList();
            Sender    = Headers.GetAddresses("Sender").FirstOrDefault();
            ReplyTo   = Headers.GetAddresses("Reply-To").ToList();
            From      = Headers.GetAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }
Exemple #17
0
        private static string _bodyHTMLFormat      = StorageManager.getEnvValue("loaMailBodyHTMLFormat");      //DANYTODO


        //private static string _bodyPlainTextFormat = "Ciao,\n"
        //    + "sei stato/a invitato/a a compilare il questionario \"{0}\" raggiungibile attraverso questo link:\n"
        //    + "{1}\">{1}\n\n"
        //    + "Per compilarlo tramite l'applicazione dedicata ai dispositivi mobili,\n"
        //    + "utilizza i seguenti parametri:\n{2}\n\n"
        //    + "Questa mail è generata automaticamente, non rispondere direttamente.";

        //private static string _bodyHTMLFormat = "<html><head></head><body>"
        //    + "Ciao,<br/>"
        //    + "sei stato/a invitato/a a compilare il questionario \"{0}\" raggiungibile attraverso questo link:<br/>"
        //    + "<a href=\"{1}\">{1}</a><br/><br/>"
        //    + "Per compilarlo tramite l'applicazione dedicata ai dispositivi mobili,<br/>"
        //    + "utilizza i seguenti parametri:<br/>{3}<br/><br/>"
        //    + "Questa mail &egrave; generata automaticamente, non rispondere direttamente."
        //    + "</body></html>";


        /// <summary>
        /// Build an email conteining the link to the private form.
        /// </summary>
        /// <param name="receiverMail">the recipient mail address</param>
        /// <param name="questionnaireName">the name of the questionnaire</param>
        /// <param name="compilationRequest">the compilation request</param>
        public LoaMail(MailAddress receiverMail, string questionnaireName, Storage.CompilationRequest compilationRequest)
        {
            if (webServerAddress == null)
            {
                webServerAddress = StorageManager.getEnvValue("webServerAddress");
            }

            From = senderAdd;
            To.Add(receiverMail);

            Subject = StorageManager.getEnvValue("mailSubject");
            //Subject = "Floading - Un nuovo questionario da compilare!";

            Object[] parameters = new Object[4];
            parameters[0] = questionnaireName;
            StorageManager manager  = new StorageManager();
            bool           isPublic = compilationRequest.Publication.isPublic;

            parameters[1] = "http://"
                            + webServerAddress + fillerpage
                            + "?WorkflowID=" + compilationRequest.publicationID
                            + "&CompilationRequestID=" + compilationRequest.compilReqID;
            parameters[2] = "CompilationRequestID: " + compilationRequest.compilReqID;
            parameters[3] = "CompilationRequestID: " + compilationRequest.compilReqID;
            if (!isPublic)
            {
                Storage.Contact con = compilationRequest.Contact;
                parameters[1] += "&Username="******"&Service=" + con.Service.nameService
                                 + "&Token=" + compilationRequest.token;
                parameters[2] += "\nUsername: "******"\nService: " + con.Service.nameService
                                 + "\nToken: " + compilationRequest.token;
                parameters[3] += "<br/>Username: "******"<br/>Service: " + con.Service.nameService
                                 + "<br/>Token: " + compilationRequest.token;
            }

            /*try
             * {
             *  IsBodyHtml = true;
             *  Body =String.Format(_bodyHTMLFormat, parameters);
             *
             * }
             * catch (Exception) { return; }*/

            // Add the alternate body to the message.
            //AlternateView alternateHTML = AlternateView.CreateAlternateViewFromString(String.Format(_bodyHTMLFormat, parameters), null,System.Net.Mime.MediaTypeNames.Text.Html);
            //Metto caratteri speciali giusti. Il db li codifica diversamenti, qui li rimetto a posto.
            string message = String.Format(_bodyPlainTextFormat, parameters);
            int    index;
            string sub;

            index = message.IndexOf("\\n");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\n");
            }
            index = message.IndexOf("\\r");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\n");
            }
            index = message.IndexOf("\\t");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\t");
            }
            AlternateView alternatePLAIN = AlternateView.CreateAlternateViewFromString(message, new System.Net.Mime.ContentType("text/plain"));

            alternatePLAIN.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
            //if (alternatePLAIN==null || alternateHTML==null) return;
            //if (alternatePLAIN == null) return;
            //AlternateViews.Add(alternateHTML);
            AlternateViews.Add(alternatePLAIN);
        }
Exemple #18
0
        /// <summary>
        /// Build an email to send to the form creator conteining the link to the form and all contacts name that the system couldn't contact automatically.
        /// </summary>
        /// <param name="receiverMail">the recipient mail address</param>
        /// <param name="questionnaireName">the name of the questionnaire</param>
        /// <param name="compilationRequest">the compilation request</param>
        public MailToFormCreator(MailAddress receiverMail, string questionnaireName, int publicationID, List <Security.Contact> contacts)
        {
            if (webServerAddress == null)
            {
                webServerAddress = StorageManager.getEnvValue("webServerAddress");
            }

            From = senderAdd;
            To.Add(receiverMail);

            //Subject = StorageManager.getEnvValue("mailTFCSubject"); //DANYTODO
            Subject = "Floading - non siamo riusciti a contattare alcune persone!";

            Object[] parametersPlain = new Object[3];
            Object[] parametersHTML  = new Object[3];

            parametersHTML[0] = parametersPlain[0] = questionnaireName;

            String allContactsPlain = "";
            String allContactsHTML  = "";
            Dictionary <int, Service> usedServices = new Dictionary <int, Service>();

            contacts.OrderBy(Contact => Contact.Service).ThenBy(Contact => Contact.Name);
            foreach (Security.Contact contact in contacts)
            {
                if (contact == null)
                {
                    continue;
                }
                Service service = contact.Service;
                if (service == null)
                {
                    continue;
                }
                allContactsPlain += service.ServiceName + " - " + contact.Name + "\n";
                allContactsHTML  += service.ServiceName + " - " + contact.Name + "<br/>";

                if (!usedServices.ContainsKey(service.ServiceId))
                {
                    usedServices.Add(service.ServiceId, service);
                }
            }

            parametersPlain[2] = allContactsPlain;
            parametersHTML[2]  = allContactsHTML;

            string baseUrl = "http://"
                             + webServerAddress + fillerpage
                             + "?WorkflowID=" + publicationID
                             + "&CompilationRequestID=" + "-1";

            string urlsHTML      = "";
            string urlsPlainText = "";

            foreach (KeyValuePair <int, Service> pair in usedServices)
            {
                string serviceParameter = "&Service=" + pair.Value.ServiceId;
                urlsHTML      += pair.Value.ServiceName + " - " + String.Format(urlHTMLFormat, baseUrl + serviceParameter);
                urlsPlainText += pair.Value.ServiceName + " - " + String.Format(urlPlainTextFormat, baseUrl + serviceParameter);
            }

            parametersHTML[1]  = urlsHTML;
            parametersPlain[1] = urlsPlainText;

            //Metto caratteri speciali giusti. Il db li codifica diversamenti, qui li rimetto a posto.
            string message = String.Format(_bodyPlainTextFormat, parametersPlain);
            int    index;
            string sub;

            index = message.IndexOf("\\n");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\n");
            }
            index = message.IndexOf("\\r");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\n");
            }
            index = message.IndexOf("\\t");
            if (index != -1 && index < message.Length - 2)
            {
                sub     = message.Substring(index, 2);
                message = message.Replace(sub, "\t");
            }
            AlternateView alternatePLAIN = AlternateView.CreateAlternateViewFromString(message, new System.Net.Mime.ContentType("text/plain"));

            alternatePLAIN.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;            //if (alternatePLAIN==null || alternateHTML==null) return;

            if (alternatePLAIN == null)
            {
                return;
            }
            //AlternateViews.Add(alternateHTML);
            AlternateViews.Add(alternatePLAIN);
        }
Exemple #19
0
        /// <summary>
        /// Initializes a populated instance of the OpaqueMail.ReadOnlyMailMessage class representing the message text passed in with attachments procesed according to the attachment filter flags.
        /// </summary>
        /// <param name="messageText">The raw contents of the e-mail message.</param>
        /// <param name="processingFlags">Flags determining whether specialized properties are returned with a ReadOnlyMailMessage.</param>
        /// <param name="parseExtendedHeaders">Whether to populate the ExtendedHeaders object.</param>
        public ReadOnlyMailMessage(string messageText, ReadOnlyMailMessageProcessingFlags processingFlags, bool parseExtendedHeaders)
        {
            if (((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawHeaders) > 0) &&
                (processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawBody) > 0)
            {
                RawMessage = messageText;
            }

            // Remember which specialized attachments to include.
            ProcessingFlags = processingFlags;

            // Fix messages whose carriage returns have been stripped.
            if (messageText.IndexOf("\r") < 0)
            {
                messageText = messageText.Replace("\n", "\r\n");
            }

            // Separate the headers for processing.
            string headers;
            int    cutoff = messageText.IndexOf("\r\n\r\n");

            if (cutoff > -1)
            {
                headers = messageText.Substring(0, cutoff);
            }
            else
            {
                headers = messageText;
            }

            // Set the raw headers property if requested.
            if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawHeaders) > 0)
            {
                RawHeaders = headers;
            }

            // Calculate the size of the message.
            Size = messageText.Length;

            // Temporary header variables to be processed by Functions.FromMailAddressString() later.
            string fromText    = "";
            string toText      = "";
            string ccText      = "";
            string bccText     = "";
            string replyToText = "";
            string subjectText = "";

            // Temporary header variables to be processed later.
            List <string> receivedChain = new List <string>();
            string        receivedText  = "";

            // Unfold any unneeded whitespace, then loop through each line of the headers.
            string[] headersList = Functions.UnfoldWhitespace(headers).Replace("\r", "").Split('\n');
            foreach (string header in headersList)
            {
                // Split header {name:value} pairs by the first colon found.
                int colonPos = header.IndexOf(":");
                if (colonPos > -1 && colonPos < header.Length - 1)
                {
                    string[] headerParts = new string[] { header.Substring(0, colonPos), header.Substring(colonPos + 1).TrimStart(new char[] { ' ' }) };
                    string   headerType  = headerParts[0].ToLower();
                    string   headerValue = headerParts[1];

                    // Set header variables for common headers.
                    if (!string.IsNullOrEmpty(headerType) && !string.IsNullOrEmpty(headerValue))
                    {
                        Headers[headerParts[0]] = headerValue;
                    }

                    switch (headerType)
                    {
                    case "cc":
                        if (ccText.Length > 0)
                        {
                            ccText += ", ";
                        }
                        ccText = headerValue;
                        break;

                    case "content-transfer-encoding":
                        ContentTransferEncoding = headerValue;
                        switch (headerValue.ToLower())
                        {
                        case "base64":
                            BodyTransferEncoding = TransferEncoding.Base64;
                            break;

                        case "quoted-printable":
                            BodyTransferEncoding = TransferEncoding.QuotedPrintable;
                            break;

                        case "7bit":
                            BodyTransferEncoding = TransferEncoding.SevenBit;
                            break;

                        case "8bit":
                            BodyTransferEncoding = TransferEncoding.EightBit;
                            break;

                        default:
                            BodyTransferEncoding = TransferEncoding.Unknown;
                            break;
                        }
                        break;

                    case "content-language":
                        ContentLanguage = headerValue;
                        break;

                    case "content-type":
                        // If multiple content-types are passed, only process the first.
                        if (string.IsNullOrEmpty(ContentType))
                        {
                            ContentType = headerValue.Trim();
                            CharSet     = Functions.ExtractMimeParameter(ContentType, "charset");
                        }
                        break;

                    case "date":
                        string dateString = headerValue;

                        // Ignore extraneous datetime information.
                        int dateStringParenthesis = dateString.IndexOf("(");
                        if (dateStringParenthesis > -1)
                        {
                            dateString = dateString.Substring(0, dateStringParenthesis - 1);
                        }

                        // Remove timezone suffix.
                        if (dateString.Substring(dateString.Length - 4, 1) == " ")
                        {
                            dateString = dateString.Substring(0, dateString.Length - 4);
                        }

                        DateTime.TryParse(dateString, out Date);
                        break;

                    case "delivered-to":
                        DeliveredTo = headerValue;
                        break;

                    case "from":
                        fromText = headerValue;
                        break;

                    case "importance":
                        Importance = headerValue;
                        break;

                    case "in-reply-to":
                        // Ignore opening and closing <> characters.
                        InReplyTo = headerValue;
                        if (InReplyTo.StartsWith("<"))
                        {
                            InReplyTo = InReplyTo.Substring(1);
                        }
                        if (InReplyTo.EndsWith(">"))
                        {
                            InReplyTo = InReplyTo.Substring(0, InReplyTo.Length - 1);
                        }
                        break;

                    case "message-id":
                        // Ignore opening and closing <> characters.
                        MessageId = headerValue;
                        if (MessageId.StartsWith("<"))
                        {
                            MessageId = MessageId.Substring(1);
                        }
                        if (MessageId.EndsWith(">"))
                        {
                            MessageId = MessageId.Substring(0, MessageId.Length - 1);
                        }
                        break;

                    case "received":
                    case "x-received":
                        if (!string.IsNullOrEmpty(receivedText))
                        {
                            receivedChain.Add(receivedText);
                        }

                        receivedText = headerValue;
                        break;

                    case "replyto":
                    case "reply-to":
                        replyToText = headerValue;
                        break;

                    case "return-path":
                        // Ignore opening and closing <> characters.
                        ReturnPath = headerValue;
                        if (ReturnPath.StartsWith("<"))
                        {
                            ReturnPath = ReturnPath.Substring(1);
                        }
                        if (ReturnPath.EndsWith(">"))
                        {
                            ReturnPath = ReturnPath.Substring(0, ReturnPath.Length - 1);
                        }
                        break;

                    case "sender":
                    case "x-sender":
                        if (headerValue.Length > 0)
                        {
                            MailAddressCollection senderCollection = Functions.FromMailAddressString(headerValue);
                            if (senderCollection.Count > 0)
                            {
                                this.Sender = senderCollection[0];
                            }
                        }
                        break;

                    case "subject":
                        subjectText = headerValue;
                        break;

                    case "to":
                        if (toText.Length > 0)
                        {
                            toText += ", ";
                        }
                        toText += headerValue;
                        break;

                    case "x-priority":
                        switch (headerValue.ToUpper())
                        {
                        case "LOW":
                            Priority = MailPriority.Low;
                            break;

                        case "NORMAL":
                            Priority = MailPriority.Normal;
                            break;

                        case "HIGH":
                            Priority = MailPriority.High;
                            break;
                        }
                        break;

                    case "x-subject-encryption":
                        bool.TryParse(headerValue, out SubjectEncryption);
                        break;

                    default:
                        break;
                    }

                    // Set header variables for advanced headers.
                    if (parseExtendedHeaders)
                    {
                        ExtendedProperties = new ExtendedProperties();

                        switch (headerType)
                        {
                        case "acceptlanguage":
                        case "accept-language":
                            ExtendedProperties.AcceptLanguage = headerValue;
                            break;

                        case "authentication-results":
                            ExtendedProperties.AuthenticationResults = headerValue;
                            break;

                        case "bounces-to":
                        case "bounces_to":
                            ExtendedProperties.BouncesTo = headerValue;
                            break;

                        case "content-description":
                            ExtendedProperties.ContentDescription = headerValue;
                            break;

                        case "dispositionnotificationto":
                        case "disposition-notification-to":
                            ExtendedProperties.DispositionNotificationTo = headerValue;
                            break;

                        case "dkim-signature":
                        case "domainkey-signature":
                        case "x-google-dkim-signature":
                            ExtendedProperties.DomainKeySignature = headerValue;
                            break;

                        case "domainkey-status":
                            ExtendedProperties.DomainKeyStatus = headerValue;
                            break;

                        case "errors-to":
                            ExtendedProperties.ErrorsTo = headerValue;
                            break;

                        case "list-unsubscribe":
                        case "x-list-unsubscribe":
                            ExtendedProperties.ListUnsubscribe = headerValue;
                            break;

                        case "mailer":
                        case "x-mailer":
                            ExtendedProperties.Mailer = headerValue;
                            break;

                        case "organization":
                        case "x-originator-org":
                        case "x-originatororg":
                        case "x-organization":
                            ExtendedProperties.OriginatorOrg = headerValue;
                            break;

                        case "original-messageid":
                        case "x-original-messageid":
                            ExtendedProperties.OriginalMessageId = headerValue;
                            break;

                        case "originating-email":
                        case "x-originating-email":
                            ExtendedProperties.OriginatingEmail = headerValue;
                            break;

                        case "precedence":
                            ExtendedProperties.Precedence = headerValue;
                            break;

                        case "received-spf":
                            ExtendedProperties.ReceivedSPF = headerValue;
                            break;

                        case "references":
                            ExtendedProperties.References = headerValue;
                            break;

                        case "resent-date":
                            string dateString = headerValue;

                            // Ignore extraneous datetime information.
                            int dateStringParenthesis = dateString.IndexOf("(");
                            if (dateStringParenthesis > -1)
                            {
                                dateString = dateString.Substring(0, dateStringParenthesis - 1);
                            }

                            // Remove timezone suffix.
                            if (dateString.Substring(dateString.Length - 4) == " ")
                            {
                                dateString = dateString.Substring(0, dateString.Length - 4);
                            }

                            DateTime.TryParse(dateString, out ExtendedProperties.ResentDate);
                            break;

                        case "resent-from":
                            ExtendedProperties.ResentFrom = headerValue;
                            break;

                        case "resent-message-id":
                            ExtendedProperties.ResentMessageID = headerValue;
                            break;

                        case "thread-index":
                            ExtendedProperties.ThreadIndex = headerValue;
                            break;

                        case "thread-topic":
                            ExtendedProperties.ThreadTopic = headerValue;
                            break;

                        case "user-agent":
                        case "useragent":
                            ExtendedProperties.UserAgent = headerValue;
                            break;

                        case "x-auto-response-suppress":
                            ExtendedProperties.AutoResponseSuppress = headerValue;
                            break;

                        case "x-campaign":
                        case "x-campaign-id":
                        case "x-campaignid":
                        case "x-mllistcampaign":
                        case "x-rpcampaign":
                            ExtendedProperties.CampaignID = headerValue;
                            break;

                        case "x-delivery-context":
                            ExtendedProperties.DeliveryContext = headerValue;
                            break;

                        case "x-maillist-id":
                            ExtendedProperties.MailListId = headerValue;
                            break;

                        case "x-msmail-priority":
                            ExtendedProperties.MSMailPriority = headerValue;
                            break;

                        case "x-originalarrivaltime":
                        case "x-original-arrival-time":
                            dateString = headerValue;

                            // Ignore extraneous datetime information.
                            dateStringParenthesis = dateString.IndexOf("(");
                            if (dateStringParenthesis > -1)
                            {
                                dateString = dateString.Substring(0, dateStringParenthesis - 1);
                            }

                            // Remove timezone suffix.
                            if (dateString.Substring(dateString.Length - 4) == " ")
                            {
                                dateString = dateString.Substring(0, dateString.Length - 4);
                            }

                            DateTime.TryParse(dateString, out ExtendedProperties.OriginalArrivalTime);
                            break;

                        case "x-originating-ip":
                            ExtendedProperties.OriginatingIP = headerValue;
                            break;

                        case "x-rcpt-to":
                            if (headerValue.Length > 1)
                            {
                                ExtendedProperties.RcptTo = headerValue.Substring(1, headerValue.Length - 2);
                            }
                            break;

                        case "x-csa-complaints":
                        case "x-complaints-to":
                        case "x-reportabuse":
                        case "x-report-abuse":
                        case "x-mail_abuse_inquiries":
                            ExtendedProperties.ReportAbuse = headerValue;
                            break;

                        case "x-spam-score":
                            ExtendedProperties.SpamScore = headerValue;
                            break;

                        default:
                            break;
                        }
                    }
                }
            }

            // Track all Received and X-Received headers.
            if (!string.IsNullOrEmpty(receivedText))
            {
                receivedChain.Add(receivedText);
            }
            ReceivedChain = receivedChain.ToArray();

            // Process the body if it's passed in.
            string body = "";

            if (cutoff > -1)
            {
                body = messageText.Substring(cutoff + 2);
            }
            if (!string.IsNullOrEmpty(body))
            {
                // Set the raw body property if requested.
                if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawBody) > 0)
                {
                    RawBody = body;
                }

                // Parse body into MIME parts.
                List <MimePart> mimeParts = MimePart.ExtractMIMEParts(ContentType, CharSet, ContentTransferEncoding, body, ProcessingFlags);

                // Process each MIME part.
                if (mimeParts.Count > 0)
                {
                    // Keep track of S/MIME signing and envelope encryption.
                    bool allMimePartsSigned = true, allMimePartsEncrypted = true, allMimePartsTripleWrapped = true;

                    // Process each MIME part.
                    for (int j = 0; j < mimeParts.Count; j++)
                    {
                        MimePart mimePart = mimeParts[j];

                        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;
                                CharSet     = mimePart.CharSet;
                                ContentType = mimePart.ContentType;
                                if (mimePart.ContentTransferEncoding != TransferEncoding.Unknown)
                                {
                                    BodyTransferEncoding = mimePart.ContentTransferEncoding;
                                }
                            }
                            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);
                            }
                        }
                        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, ContentType);
                                if (BodyTransferEncoding != TransferEncoding.Unknown)
                                {
                                    alternateView.TransferEncoding = BodyTransferEncoding;
                                }
                                AlternateViews.Add(alternateView);

                                IsBodyHtml  = true;
                                Body        = mimePart.Body;
                                CharSet     = mimePart.CharSet;
                                ContentType = mimePart.ContentType;
                                if (mimePart.ContentTransferEncoding != TransferEncoding.Unknown)
                                {
                                    BodyTransferEncoding = mimePart.ContentTransferEncoding;
                                }
                            }
                            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);
                            }
                        }
                    }

                    // OpaqueMail optional setting for protecting the subject.
                    if (SubjectEncryption && Body.StartsWith("Subject: "))
                    {
                        int linebreakPosition = Body.IndexOf("\r\n");
                        if (linebreakPosition > -1)
                        {
                            subjectText = Body.Substring(9, linebreakPosition - 9);
                            Body        = Body.Substring(linebreakPosition + 2);
                        }
                    }

                    // Set the message's S/MIME attributes.
                    SmimeSigned            = allMimePartsSigned;
                    SmimeEncryptedEnvelope = allMimePartsEncrypted;
                    SmimeTripleWrapped     = allMimePartsTripleWrapped;
                }
                else
                {
                    // Process non-MIME messages.
                    Body = body;
                }
            }

            // Parse String representations of addresses into MailAddress objects.
            if (fromText.Length > 0)
            {
                MailAddressCollection fromAddresses = Functions.FromMailAddressString(fromText);
                if (fromAddresses.Count > 0)
                {
                    From = fromAddresses[0];
                }
            }

            if (toText.Length > 0)
            {
                To.Clear();
                MailAddressCollection toAddresses = Functions.FromMailAddressString(toText);
                foreach (MailAddress toAddress in toAddresses)
                {
                    To.Add(toAddress);
                }

                // Add the address to the AllRecipients collection.
                foreach (MailAddress toAddress in toAddresses)
                {
                    if (!AllRecipients.Contains(toAddress.Address))
                    {
                        AllRecipients.Add(toAddress.Address);
                    }
                }
            }

            if (ccText.Length > 0)
            {
                CC.Clear();
                MailAddressCollection ccAddresses = Functions.FromMailAddressString(ccText);
                foreach (MailAddress ccAddress in ccAddresses)
                {
                    CC.Add(ccAddress);
                }

                // Add the address to the AllRecipients collection.
                foreach (MailAddress ccAddress in ccAddresses)
                {
                    if (!AllRecipients.Contains(ccAddress.Address))
                    {
                        AllRecipients.Add(ccAddress.Address);
                    }
                }
            }

            if (bccText.Length > 0)
            {
                Bcc.Clear();
                MailAddressCollection bccAddresses = Functions.FromMailAddressString(bccText);
                foreach (MailAddress bccAddress in bccAddresses)
                {
                    Bcc.Add(bccAddress);
                }

                // Add the address to the AllRecipients collection.
                foreach (MailAddress bccAddress in bccAddresses)
                {
                    if (!AllRecipients.Contains(bccAddress.Address))
                    {
                        AllRecipients.Add(bccAddress.Address);
                    }
                }
            }

            if (replyToText.Length > 0)
            {
                ReplyToList.Clear();
                MailAddressCollection replyToAddresses = Functions.FromMailAddressString(replyToText);
                foreach (MailAddress replyToAddress in replyToAddresses)
                {
                    ReplyToList.Add(replyToAddress);
                }
            }

            // Decode international strings and remove escaped linebreaks.
            Subject = Functions.DecodeMailHeader(subjectText).Replace("\r", "").Replace("\n", "");
        }
Exemple #20
0
        public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char?termChar = null)
        {
            _HeadersOnly = headersOnly;
            Headers      = null;
            Body         = null;


            var    headers = new StringBuilder();
            string line;

            while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null)
            {
                if (line.Trim().Length == 0)
                {
                    if (headers.Length == 0)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                headers.AppendLine(line);
            }
            RawHeaders = headers.ToString();

            if (!headersOnly)
            {
                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    var atts = new List <Attachment>();
                    var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
                    if (!string.IsNullOrEmpty(body))
                    {
                        SetBody(body);
                    }

                    foreach (var att in atts)
                    {
                        (att.IsAttachment ? Attachments : AlternateViews).Add(att);
                    }

                    if (maxLength > 0)
                    {
                        reader.ReadToEnd(maxLength, Encoding);
                    }
                }
                else
                {
                    SetBody(reader.ReadToEnd(maxLength, Encoding));
                }
            }

            if ((string.IsNullOrWhiteSpace(Body) || ContentType.MediaType.StartsWith("multipart/")) && AlternateViews.Count > 0)
            {
                var att = AlternateViews.GetTextView() ?? AlternateViews.GetHtmlView();
                if (att != null)
                {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    SetContentType(att.Headers["Content-Type"].RawValue);
                }
            }

            Date      = Headers.GetDate();
            To        = Headers.GetMailAddresses("To").ToList();
            Cc        = Headers.GetMailAddresses("Cc").ToList();
            Bcc       = Headers.GetMailAddresses("Bcc").ToList();
            Sender    = Headers.GetMailAddresses("Sender").FirstOrDefault();
            ReplyTo   = Headers.GetMailAddresses("Reply-To").ToList();
            From      = Headers.GetMailAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }