/// <summary>
 /// Generate and add a MimePart to the embedded objects collection, using the specified file.
 /// </summary>
 /// <param name="path">The file containing the MimePart's content.</param>
 /// <param name="contentId">The Content-ID Header field will be used for the part.</param>
 /// <param name="charset">The charset of the text contained in the file.</param>
 public virtual string Add(string path, string contentId, string charset)
 {
     MimePart part = new MimePart(path, contentId, charset);
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
     return part.EmbeddedObjectContentId;
 }
 /// <summary>
 /// Generate and add a MimePart to the embedded objects collection, using the specified file.
 /// </summary>
 /// <param name="path">The file containing the MimePart's content.</param>
 /// <param name="generateContentId">If true, a Content-ID Header field will be generated for the part.</param>
 public new string Add(string path, bool generateContentId)
 {
     MimePart part = new MimePart(path, generateContentId);
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
     return part.EmbeddedObjectContentId;
 }
 protected override void Dispose(bool disposing)
 {
     if (disposing && _mimePart != null) {
         using (ThreadAccessGuard.EnterPublic(_mimePart.AccessToken)) {
             Internal.ReadableDataStorage readableDataStorage = this.ReadableWritableStorage;
             readableDataStorage.AddRef();
             base.Dispose(true);
             if (!_mimePart._isDisposed)
                 _mimePart.SetStorage(readableDataStorage, 0L, readableDataStorage.Length, 0L, _contentTransferEncoding, LineTerminationState.Unknown);
             readableDataStorage.Release();
         }
         _mimePart = null;
     } else
         base.Dispose(disposing);
 }
Beispiel #4
0
        public void TestMimePartContentObject()
        {
            byte[] data = Encoding.ASCII.GetBytes("abcd");

            // Checksum will be wrong if content is encoded in any way.
            string checksum;

            using (var md5 = MD5.Create())
                checksum = Convert.ToBase64String(md5.ComputeHash(data));

            var msg = new MimePart("application", "octet-stream",
                                   new MimeContent(new MemoryStream(data), ContentEncoding.Binary)
                                   );

            Assert.AreEqual(checksum, msg.ComputeContentMd5(), "Content MD5 is wrong");
            Assert.AreEqual(ContentEncoding.Binary, msg.Content.Encoding, "ContentEncoding is wrong");
        }
Beispiel #5
0
        public void TestMimePartStream()
        {
            byte[] data = Encoding.ASCII.GetBytes("abcd");


            var msg = new MimePart("application", "octet-stream",
                                   new MemoryStream(data)
                                   );

            var buffer = new MemoryStream();

            msg.ContentObject.DecodeTo(buffer);
            buffer.Seek(0, SeekOrigin.Begin);

            Assert.AreEqual(ContentEncoding.Default, msg.ContentObject.Encoding, "ContentEncoding is wrong");
            Assert.AreEqual(data, buffer.ToArray(), "ContentEncoding is wrong");
        }
 /*
  * Returns true if part should be treated like an attachment, otherwise false
  */
 private bool TreatAsAttachment(MimePart part)
 {
     if (string.IsNullOrEmpty(_attachmentFolder))
     {
         return(false); // We cannot store attachments, unless caller supplies an [attachment-folder] argument
     }
     if (part.IsAttachment)
     {
         // Still we are not 100% certain, since we do not want to store ALL actual attachments as attachments
         if (part.ContentType.MediaType == "application" && part.ContentType.MediaSubtype == "pgp-encrypted")
         {
             return(false); // No need to save these parts to disc
         }
         return(true);
     }
     return(false);
 }
Beispiel #7
0
        public async Task TestTranscodingAsync()
        {
            var path     = Path.Combine("..", "..", "TestData", "images", "girl.jpg");
            var expected = File.ReadAllBytes(path);

            var part = new MimePart("image", "jpeg")
            {
                Content = new MimeContent(new MemoryStream(expected, false)),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = "girl.jpg"
            };

            // encode in base64
            using (var output = new MemoryStream()) {
                await part.WriteToAsync(output);

                output.Position = 0;

                part = (MimePart)await MimeEntity.LoadAsync(output);
            }

            // transcode to uuencode
            part.ContentTransferEncoding = ContentEncoding.UUEncode;
            using (var output = new MemoryStream()) {
                await part.WriteToAsync(output);

                output.Position = 0;

                part = (MimePart)await MimeEntity.LoadAsync(output);
            }

            // verify decoded content
            using (var output = new MemoryStream()) {
                await part.Content.DecodeToAsync(output);

                output.Position = 0;

                var actual = output.ToArray();

                Assert.AreEqual(expected.Length, actual.Length);
                for (int i = 0; i < expected.Length; i++)
                {
                    Assert.AreEqual(expected[i], actual[i], "Image content differs at index {0}", i);
                }
            }
        }
Beispiel #8
0
        bool TryGetImage(string url, out MimePart image)
        {
            image = null;

            UriKind kind;
            Uri     uri;

            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                kind = UriKind.Absolute;
            }
            else if (Uri.IsWellFormedUriString(url, UriKind.Relative))
            {
                kind = UriKind.Relative;
            }
            else
            {
                kind = UriKind.RelativeOrAbsolute;
            }

            try
            {
                uri = new Uri(url, kind);
            }
            catch (UriFormatException)
            {
                return(false);
            }

            foreach (var item in this._stack.ToArray().Reverse())
            {
                int index = item.IndexOf(uri);

                if (index == IndexNotFound)
                {
                    continue;
                }

                image = item[index] as MimePart;

                return(image != null);
            }

            return(false);
        }
Beispiel #9
0
        private static bool TryGetFileNameFromAppleDouble(MimePart part, ref string fileName)
        {
            MimePart mimePart;
            MimePart part2;

            if (Utility.TryGetAppleDoubleParts(part, out mimePart, out part2))
            {
                if (Utility.TryGetFileNameFromHeader(mimePart, HeaderId.ContentDisposition, "filename", ref fileName) || Utility.TryGetFileNameFromHeader(mimePart, HeaderId.ContentType, "name", ref fileName))
                {
                    return(true);
                }
                if (Utility.TryGetFileNameFromAppleFile(part2, ref fileName))
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #10
0
        internal static MimePart GetStartChild(MimePart part)
        {
            string parameterValue = Utility.GetParameterValue(part, HeaderId.ContentType, "start");

            foreach (MimePart mimePart in part)
            {
                if (string.IsNullOrEmpty(parameterValue))
                {
                    return(mimePart);
                }
                Header header = mimePart.Headers.FindFirst(HeaderId.ContentId);
                if (header != null && Utility.CompareIdentifiers(header.Value, parameterValue))
                {
                    return(mimePart);
                }
            }
            return(part.FirstChild as MimePart);
        }
Beispiel #11
0
        public Mail Attachment(Stream stream, string fileName)
        {
            if (stream is null)
            {
                return(this);
            }
            GetAttachments ??= new List <MimePart>();
            var attachment = new MimePart
            {
                Content                 = new MimeContent(stream),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = fileName
            };

            GetAttachments.Add(attachment);
            return(this);
        }
Beispiel #12
0
        static TnefPart PromoteToTnefPart(MimePart part)
        {
            var tnef = new TnefPart();

            foreach (var param in part.ContentType.Parameters)
            {
                tnef.ContentType.Parameters[param.Name] = param.Value;
            }

            if (part.ContentDisposition != null)
            {
                tnef.ContentDisposition = part.ContentDisposition;
            }

            tnef.ContentTransferEncoding = part.ContentTransferEncoding;

            return(tnef);
        }
Beispiel #13
0
        private AttachmentCollection BuildAttachmentCollection(List <Attachment> attachments)
        {
            var attachmentCollection = new AttachmentCollection();

            foreach (var attachment in attachments)
            {
                var mimePart = new MimePart(attachment.Type, attachment.SubType)
                {
                    Content                 = new MimeContent(attachment.Content, ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = attachment.Name
                };
                attachmentCollection.Add(mimePart);
            }

            return(attachmentCollection);
        }
Beispiel #14
0
        /*
         * Processes a MimePart (leaf entity).
         */
        private void ProcessLeafPart(MimePart part, Node args)
        {
            Node entityNode = args.Add(part.ContentType.MediaType, part.ContentType.MediaSubtype).LastChild;

            ProcessHeaders(part, entityNode);

            // Figuring out if this is an inline element or an attachment.
            if (TreatAsAttachment(part))
            {
                // This is an attachment, and caller supplied an attachment folder to serialise attachments to.
                SaveMimePartToDisc(part, entityNode);
            }
            else
            {
                // This is not an attachment, or caller did not supply an attachment folder.
                ProcessMimePartInline(part, entityNode);
            }
        }
Beispiel #15
0
        public async Task GetStream_CreateMimePart_WriteMimePart_LoadMimePart_CompareMimeParts(string fileName)
        {
            var stream = await GetAssetStreamAsync(fileName);

            var m1 = new MimePart
            {
                Content = new MimeContent(stream)
            };

            await m1.WriteToAsync(GetAssetFilePath($"{fileName}__m1.txt"));

            var entity = await MimeEntity.LoadAsync(GetAssetFilePath($"{fileName}__m1.txt"));

            var m2 = (MimePart)entity;

            FileAssert.AreEqual(stream, m1.Content.Stream);
            FileAssert.AreEqual(m1.Content.Stream, m2.Content.Stream);
        }
        private async Task <Boolean> ProcessAsync(String caseRef, MimeMessage message, IAmazonS3 client, String bucketName)
        {
            int currentBodyPart = 1;

            foreach (MimeEntity bodyPart in message.BodyParts)
            {
                if (bodyPart.ContentType.IsMimeType("image", "*") ||
                    bodyPart.ContentType.IsMimeType("application", "pdf"))
                {
                    numOfAttachments++;
                    MimePart part = (MimePart)bodyPart;
                    Console.WriteLine(caseRef + " : Processing Attachment " + numOfAttachments);
                    await SaveAttachment(caseRef, message, currentBodyPart, part, client, bucketName);
                }
            }

            return(true);
        }
Beispiel #17
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (true)
            {
                await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);

                var attachment = new MimePart("text", "txt")
                {
                    Content                 = new MimeContent(File.OpenRead("logs.txt")),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = Path.GetFileName("logs.txt")
                };
                //var admins = await _userManager.GetUsersInRoleAsync("admin");
                //var email = GenerateLogMessage(admins, attachment);
                //await _emailService.SendEmailAsync(email, _config);
            }
        }
        public void SendEmail(string content, string email, string subject, string path = null)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("WebStore", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Me", email));
            message.Subject = subject;

            var body = new TextPart("html")
            {
                Text = content
            };

            if (path != null)
            {
                var attachment = new MimePart("image", "jpg")
                {
                    Content                 = new MimeContent(File.OpenRead(path)),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = Path.GetFileName(path)
                };


                var multipart = new Multipart("mixed");
                multipart.Add(body);
                multipart.Add(attachment);

                // now set the multipart/mixed as the message body
                message.Body = multipart;
            }
            else
            {
                message.Body = body;
            }

            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587, false);
                client.Authenticate("*****@*****.**", "203216395");
                client.Send(message);
                client.Disconnect(true);
            }
        }
Beispiel #19
0
        public override void WriteMessage(Message message, System.IO.Stream stream)
        {
            try
            {
                VerifyOperationContext();

                message.Properties.Encoder = this._InnerEncoder;

                List <SwaAttachment> attachmentList = null;
                if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(SwaEncoderConstants.AttachmentProperty))
                {
                    attachmentList = OperationContext.Current.OutgoingMessageProperties[SwaEncoderConstants.AttachmentProperty] as List <SwaAttachment>;
                }

                if (attachmentList == null)
                {
                    _InnerEncoder.WriteMessage(message, stream);
                }
                else
                {
                    // Associate the contents to the mime-part
                    _SoapMimeContent.Content = Encoding.UTF8.GetBytes(message.GetBody <string>());
                    //_AttachmentMimeContent.Content = (byte[])OperationContext.Current.OutgoingMessageProperties[SwaEncoderConstants.AttachmentProperty];

                    foreach (SwaAttachment attachment in attachmentList)
                    {
                        MimePart attachmentPart = new MimePart();
                        attachmentPart.Content          = GetBase64EncodingContent(attachment.ContentBinary);
                        attachmentPart.ContentType      = attachment.ContentType;
                        attachmentPart.ContentId        = attachment.ContentId;
                        attachmentPart.TransferEncoding = "base64";
                        _MyContent.Parts.Add(attachmentPart);
                    }

                    // Now create the message content for the stream
                    _MimeParser.SerializeMimeContent(_MyContent, stream);
                }
            }
            catch (Exception e)
            {
                SwaLogMgt.SetLog(this, e);
                //Console.WriteLine(e.ToString());
            }
        }
Beispiel #20
0
    public void sendMailwithAttachments(String subject, String text)
    {
        var message = new MimeMessage();

        message.From.Add(new MailboxAddress("username", login));
        message.To.Add(new MailboxAddress("receiver", "receiverremail"));
        message.Subject = subject;

        var body = new TextPart("plain")
        {
            Text = text
        };

        var attachment = new MimePart("image", "gif")
        {
            Content                 = new MimeContent(File.OpenRead("E:\\Wallpapers"), ContentEncoding.Default),
            ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
            ContentTransferEncoding = ContentEncoding.Base64,
            FileName                = Path.GetFileName("E:\\Wallpapers")
        };

        var multipart = new Multipart("mixed");

        multipart.Add(body);
        multipart.Add(attachment);
        // now set the multipart/mixed as the message body
        message.Body = multipart;

        using (var client = new SmtpClient())
        {
            client.Connect(smtpServer, 587, false);


            // Note: since we don't have an OAuth2 token, disable
            // the XOAUTH2 authentication mechanism.
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            // Note: only needed if the SMTP server requires authentication
            client.Authenticate(login, password);

            client.Send(message);
            client.Disconnect(true);
        }
    }
        // look up the image based on the img src url within our multipart/related stack
        bool TryGetImage(string url, out MimePart image)
        {
            UriKind kind;
            int     index;
            Uri     uri;

            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                kind = UriKind.Absolute;
            }
            else if (Uri.IsWellFormedUriString(url, UriKind.Relative))
            {
                kind = UriKind.Relative;
            }
            else
            {
                kind = UriKind.RelativeOrAbsolute;
            }

            try
            {
                uri = new Uri(url, kind);
            }
            catch
            {
                image = null;
                return(false);
            }

            for (int i = stack.Count - 1; i >= 0; i--)
            {
                if ((index = stack[i].IndexOf(uri)) == -1)
                {
                    continue;
                }

                image = stack[i][index] as MimePart;
                return(image != null);
            }

            image = null;

            return(false);
        }
Beispiel #22
0
        protected override async Task <IResourceInfo> PostAsyncInternal(UriString uri, Stream value, IImmutableSession session)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(session.Get(Use <IMailNamespace> .Namespace, x => x.From)));
            message.To.AddRange(session.Get(Use <IMailNamespace> .Namespace, x => x.To).Where(Conditional.IsNotNullOrEmpty).Select(x => new MailboxAddress(x)));
            message.Cc.AddRange(session.Get(Use <IMailNamespace> .Namespace, x => x.CC, Enumerable.Empty <string>().ToList()).Where(Conditional.IsNotNullOrEmpty).Select(x => new MailboxAddress(x)));
            message.Subject = session.Get(Use <IMailNamespace> .Namespace, x => x.Subject);
            var multipart = new Multipart("mixed")
            {
                new TextPart(session.Get(Use <IMailNamespace> .Namespace, x => x.IsHtml) ? TextFormat.Html : TextFormat.Plain)
                {
                    Text = await ReadBodyAsync(value, session)
                }
            };

            foreach (var attachment in session.Get(Use <IMailNamespace> .Namespace, x => x.Attachments, new Dictionary <string, byte[]>()).Where(i => i.Key.IsNotNullOrEmpty() && i.Value.IsNotNull()))
            {
                var attachmentPart = new MimePart(MediaTypeNames.Application.Octet)
                {
                    Content                 = new MimeContent(new MemoryStream(attachment.Value).Rewind()),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = attachment.Key
                };
                multipart.Add(attachmentPart);
            }

            message.Body = multipart;

            using (var smtpClient = new SmtpClient())
            {
                await smtpClient.ConnectAsync
                (
                    session.Get(Use <ISmtpNamespace> .Namespace, x => x.Host),
                    session.Get(Use <ISmtpNamespace> .Namespace, x => x.Port),
                    session.Get(Use <ISmtpNamespace> .Namespace, x => x.UseSsl, false)
                );

                await smtpClient.SendAsync(message);
            }

            return(new InMemoryResourceInfo(uri, session));
        }
Beispiel #23
0
        public static async Task SendMailWithFile(string Message, string email, string subject, string path)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Automation Generate TestCase Web Service", "*****@*****.**"));
            message.To.Add(new MailboxAddress(email));
            message.Subject = subject;

            var body = new TextPart("html")
            {
                Text = Message
            };

            var attachment = new MimePart("application", "gif")
            {
                Content                 = new MimeContent(File.OpenRead(path)),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(path)
            };

            // now create the multipart/mixed container to hold the message text and the

            var multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(attachment);

            // now set the multipart/mixed as the message body
            message.Body = multipart;
            using (var client = new SmtpClient())
            {
                await Task.Run(() =>
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    client.Authenticate("", "");

                    client.Send(message);

                    client.Disconnect(true);
                    Console.WriteLine("Send Mail successfully");
                });
            }
        }
Beispiel #24
0
        internal static void StoreFileNameInHeader(MimePart attachmentPart, HeaderId headerId, GetDefaultValue getDefaultValue, string parameterName, string value)
        {
            ComplexHeader complexHeader = attachmentPart.Headers.FindFirst(headerId) as ComplexHeader;

            if (complexHeader == null)
            {
                complexHeader       = (Header.Create(headerId) as ComplexHeader);
                complexHeader.Value = getDefaultValue();
                attachmentPart.Headers.AppendChild(complexHeader);
            }
            MimeParameter mimeParameter = complexHeader[parameterName];

            if (mimeParameter == null)
            {
                mimeParameter = new MimeParameter(parameterName);
                complexHeader.AppendChild(mimeParameter);
            }
            mimeParameter.Value = value;
        }
        private void AddAttachmentToMessage(MimeMessage mime, MemoryStream msData, string fileName = "text.sst")
        {
            var attachment = new MimePart("text", "plain")
            {
                ContentObject           = new ContentObject(msData),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = fileName
            };

            var multipart = new Multipart("mixed");

            multipart.Add(attachment);
            foreach (var item in mime.BodyParts)
            {
                multipart.Add(item);
            }
            mime.Body = multipart;
        }
Beispiel #26
0
        internal static Charset GetCharsetFromMime(MimePart part)
        {
            Charset result = Charset.ASCII;
            Header  header = part.Headers.FindFirst(HeaderId.ContentType);

            if (header != null)
            {
                MimeParameter mimeParameter = (header as ComplexHeader)["charset"];
                if (mimeParameter != null)
                {
                    Charset charset = null;
                    if (Charset.TryGetCharset(mimeParameter.Value, out charset))
                    {
                        result = charset;
                    }
                }
            }
            return(result);
        }
Beispiel #27
0
        public void TestArgumentExceptions()
        {
            var part = new MimePart();

            Assert.Throws <ArgumentNullException> (() => new MimePart((string)null));
            Assert.Throws <ArgumentNullException> (() => new MimePart((ContentType)null));
            Assert.Throws <ArgumentNullException> (() => new MimePart(null, "octet-stream"));
            Assert.Throws <ArgumentNullException> (() => new MimePart("application", null));

            Assert.Throws <ArgumentOutOfRangeException> (() => part.ContentDuration = -1);
            Assert.Throws <ArgumentOutOfRangeException> (() => part.Prepare(EncodingConstraint.SevenBit, 1));

            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((Stream)null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((Stream)null, true));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((ParserOptions)null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, (Stream)null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(null, Stream.Null, true));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, (Stream)null, true));

            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((ContentType)null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(new ContentType("application", "octet-stream"), null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(null, new ContentType("application", "octet-stream"), Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, new ContentType("application", "octet-stream"), null));

            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((string)null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(null, "fileName"));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, (string)null));

            Assert.Throws <ArgumentNullException> (() => part.Accept(null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((string)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((Stream)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((string)null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((Stream)null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (Stream)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, "fileName"));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (string)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, Stream.Null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (Stream)null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, "fileName", false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (string)null, false));
        }
Beispiel #28
0
        private static async Task TestClientConnectionAsync(MailDemonService demon, string server, string to, string file)
        {
            SmtpClient client = new SmtpClient()
            {
                SslProtocols = System.Security.Authentication.SslProtocols.None,
                Timeout      = 60000 // 60 secs
            };
            await client.ConnectAsync(server, 25, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);

            await client.AuthenticateAsync(new NetworkCredential(demon.Users.First().UserName, demon.Users.First().Password));

            MimeMessage msg = new MimeMessage();

            msg.From.Add(demon.Users.First().MailAddress);
            foreach (string toAddress in to.Split(',', ';'))
            {
                msg.To.Add(new MailboxAddress(toAddress));
            }
            msg.Subject = "Test Subject";
            BodyBuilder bodyBuilder = new BodyBuilder();
            Multipart   multipart   = new Multipart("mixed");

            bodyBuilder.HtmlBody = "<html><body><b>Test Email Html Body Which is Bold 12345</b></body></html>";
            multipart.Add(bodyBuilder.ToMessageBody());
            if (file != null && File.Exists(file))
            {
                byte[] bytes      = System.IO.File.ReadAllBytes(file);
                var    attachment = new MimePart("binary", "bin")
                {
                    Content                 = new MimeContent(new MemoryStream(bytes), ContentEncoding.Binary),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Binary, // Base64 for DATA test, Binary for BINARYMIME test
                    FileName                = Path.GetFileName(file)
                };
                multipart.Add(attachment);
            }
            msg.Body = multipart;
            await client.SendAsync(msg);

            await client.DisconnectAsync(true);

            Console.WriteLine("Test message sent");
        }
 public IComposedMessage Attach(string name, string base64)
 {
     if (_multipart == null)
     {
         _multipart = new Multipart("mixed");
     }
     using (var stream = new MemoryStream(Convert.FromBase64String(base64)))
     {
         var attachment = new MimePart("image", "jpg")
         {
             Content                 = new MimeContent(stream, ContentEncoding.Default),
             ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
             ContentTransferEncoding = ContentEncoding.Base64,
             FileName                = $"{name}.jpg"
         };
         _multipart.Add(attachment);
     };
     return(this);
 }
        public static void EmailTo(this IDbConnection conn, string sql, string fileName, string subject, List <string> emailTo, string emailHost, int port, string account, string password, string displayName = "DotnetSpider Alert")
        {
            var path    = Export(conn, sql, $"{fileName}_{DateTime.Now:yyyyMMddhhmmss}", true);
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(displayName, account));
            foreach (var email in emailTo)
            {
                message.To.Add(new MailboxAddress(email, email));
            }

            message.Subject = subject;

            var attachment = new MimePart("excel", "xlsx")
            {
                ContentObject           = new ContentObject(File.OpenRead(path)),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = Path.GetFileName(path)
            };

            var text = new TextPart {
                Text = subject
            };


            var multipart = new Multipart("mixed")
            {
                text, attachment
            };

            message.Body = multipart;

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(emailHost, port);

                client.Authenticate(account, password);

                client.Send(message);
                client.Disconnect(true);
            }
        }
    public static void Main()
    {
        ServiceDescription myServiceDescription =
            ServiceDescription.Read("MimePart_3_Input_cs.wsdl");
        ServiceDescriptionCollection myServiceDescriptionCol =
            new ServiceDescriptionCollection();

        myServiceDescriptionCol.Add(myServiceDescription);
        XmlQualifiedName myXmlQualifiedName =
            new XmlQualifiedName("MimeServiceHttpPost", "http://tempuri.org/");

        // Create the Binding.
        Binding myBinding =
            myServiceDescriptionCol.GetBinding(myXmlQualifiedName);
        OperationBinding myOperationBinding = null;

        for (int i = 0; i < myBinding.Operations.Count; i++)
        {
            if (myBinding.Operations[i].Name.Equals("AddNumbers"))
            {
                myOperationBinding = myBinding.Operations[i];
            }
        }
        // Create the OutputBinding.
        OutputBinding  myOutputBinding  = myOperationBinding.Output;
        MimeXmlBinding myMimeXmlBinding = new MimeXmlBinding();

        myMimeXmlBinding.Part = "body";

        // Create the MimePart.
        MimePart myMimePart = new MimePart();

        myMimePart.Extensions.Add(myMimeXmlBinding);
        MimeMultipartRelatedBinding myMimePartRelatedBinding =
            new MimeMultipartRelatedBinding();

        // Add the MimePart to the MimePartRelatedBinding.
        myMimePartRelatedBinding.Parts.Add(myMimePart);
        myOutputBinding.Extensions.Add(myMimePartRelatedBinding);
        myServiceDescription.Write("MimePart_3_Output_CS.wsdl");
        Console.WriteLine(
            "MimePart_3_Output_CS.wsdl has been generated successfully.");
    }
        public void should_initialize_from_file(bool generateContentId)
        {
            var fileBytes = File.ReadAllBytes(_imagefilePath);

            var mimePart = new MimePart(_imagefilePath, generateContentId);

            mimePart.BinaryContent.ShouldEqual(fileBytes);
            mimePart.ContentType.MimeType.ShouldEqual("image/gif");
            mimePart.ContentDisposition.FileName.ShouldEqual("\"test_picture.gif\"");
            mimePart.ContentName.ShouldEqual("test_picture.gif");
            if (generateContentId)
            {
                mimePart.ContentId.ShouldNotBeNull();
            }
            else
            {
                mimePart.ContentId.ShouldBeNull();
            }
        }
Beispiel #33
0
        public static void SendMail(string recipients)
        {
            try
            {
                string path       = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\Test1.html";
                var    attachment = new MimePart("image", "gif")
                {
                    ContentObject           = new ContentObject(File.OpenRead(path), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = Path.GetFileName(path)
                };
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Chetan Khalkar", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Chetan Khalkar", recipients));
                message.Subject = "Test Mail for Mail Module With attachment";

                var multipart = new Multipart("mixed");
                multipart.Add(new TextPart("html")
                {
                    Text = @"Test mail to send generated reports as an attachments."
                });
                multipart.Add(attachment);

                message.Body = multipart;

                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect("smtp.gmail.com", 587, false);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate("*****@*****.**", "Skadoosh!");

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                Console.Write("Error : " + e.Message);
            }
        }
Beispiel #34
0
 /// <summary>
 /// Parses the sub parts.
 /// </summary>
 /// <param name="part">The part.</param>
 /// <param name="original_content"></param>
 /// <param name="message">The message.</param>
 private static void ParseSubParts(ref MimePart part, ref string original_content, Message message)
 {
     var boundary = part.ContentType.Parameters["boundary"];
     Logger.AddEntry("boundary : " + boundary);
     var arrpart = Regex.Split(original_content, @"\r?\n?" + Regex.Escape("--" + boundary));
     for (var i = 1; i < arrpart.Length; i++)
     {
         var strpart = arrpart[i];
         if (!strpart.StartsWith("--") && !string.IsNullOrEmpty(strpart))
         {
             var newpart = ParseMimePart(ref strpart, message);
             //newpart.ParentMessage = message;
             newpart.Container = part;
             part.SubParts.Add(newpart);
         }
     }
 }
	public int IndexOf(MimePart mimePart) {}
        public void Write_Single_Plain_Text_Test()
        {
            var part = new MimePart(new MemoryStream(Encoding.UTF8.GetBytes("plain text")));
            string result;

            using (var message = new MimeMessage(part) {Boundary = "abc123"})
            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            const string expected = @"--abc123
            Content-Length: 10

            plain text
            --abc123--";
            Assert.That(result, Is.EqualTo(expected));
        }
	// Methods
	public int Add(MimePart mimePart) {}
 public PartContentWriteStream(MimePart mimePart, ContentTransferEncoding contentTransferEncoding)
     : base(new Internal.TemporaryDataStorage())
 {
     _mimePart = mimePart;
     _contentTransferEncoding = contentTransferEncoding;
 }
Beispiel #39
0
        /// <summary>
        /// Decodes the part body.
        /// </summary>
        /// <param name="part">The part.</param>
        private static void DecodePartBody(ref MimePart part)
        {
            if (part.ContentType.Type.ToLower().Equals("multipart") && part.Charset == null)
                return;
            
            // Let's see if a charset is specified. Otherwise we default to "iso-8859-1".
            var charset = (!string.IsNullOrEmpty(part.Charset) ? part.Charset : "iso-8859-1");

#if PocketPC
            if (charset.ToLower() == "iso-8859-1")
                charset = "windows-1252";
#endif
            // This is a Base64 encoded part body.
            if (part.ContentTransferEncoding.Equals(ContentTransferEncoding.Base64))
            {
                var skip_decode = false;
                var text = RemoveNewLines(RemoveWhiteSpaces(part.TextContent));
#if !PocketPC
                try
                {
#endif
                    //We have the Base64 string so we can decode it.
                    part.BinaryContent = Convert.FromBase64String(text);
#if !PocketPC
                }
                catch (FormatException)
                {
                     // remove whitespaces and new lines
                    /*sText = sText.Replace("=", "");
                    sText = sText.Replace("\0", "");
                    sText += "==";

                    part.TextContent = 
                        regx_base64.Replace(sText, new MatchEvaluator(m =>
                        {

                            try
                            {
                                var bytes = Convert.FromBase64String(m.Value);

                                return System.Text.Encoding.GetEncoding(charset).GetString(bytes, 0, bytes.Length);
                            }
                            catch (Exception)
                            {
                                return m.Value;
                            }
                        }));*/

                    part.BinaryContent = Encoding.GetEncoding(charset).GetBytes(part.TextContent);

                    skip_decode = true;
                }
#endif

                if (part.ContentDisposition != ContentDisposition.Attachment && !skip_decode)
                    part.TextContent = Encoding.GetEncoding(charset).GetString(part.BinaryContent, 0, part.BinaryContent.Length);
            }
            // This is a quoted-printable encoded part body.
            else if (part.ContentTransferEncoding.Equals(ContentTransferEncoding.QuotedPrintable))
            {
                // Let's decode.
                part.TextContent = Codec.FromQuotedPrintable(part.TextContent, charset);
                // Knowing the charset, we can provide a binary version of this body data.
                part.BinaryContent = Encoding.GetEncoding(charset).GetBytes(part.TextContent);
            }
            // Otherwise, this is an unencoded part body and we keep the text version as it is.
            else
            {
                // Knowing the charset, we can provide a binary version of this body data.
                part.BinaryContent = Encoding.GetEncoding("iso-8859-1").GetBytes(part.TextContent);

                var charset_detector = new CharsetDetector();
                charset_detector.Feed(part.BinaryContent, 0, part.BinaryContent.Length);
                charset_detector.DataEnd();
                charset = charset_detector.Charset ?? charset;

                var encoding = Encoding.GetEncoding(charset);
                part.TextContent = encoding.GetString(part.BinaryContent);
            }
        }
	public void CopyTo(MimePart[] array, int index) {}
        private static MimePart CreateAttachment(MailAttachment attachment, bool load_attachments)
        {
            var ret_val = new MimePart();

            var s3_key = MailStoragePathCombiner.GerStoredFilePath(attachment);
            var file_name = attachment.fileName ?? Path.GetFileName(s3_key);

            if (load_attachments)
            {
                var byte_array = attachment.data;

                if (byte_array == null || byte_array.Length == 0)
                {
                    using (var stream = StorageManager.GetDataStoreForAttachments(attachment.tenant).GetReadStream(s3_key))
                    {
                        byte_array = stream.GetCorrectBuffer();
                    }
                }

                ret_val = new MimePart(byte_array, file_name);

                if (attachment.contentId != null) ret_val.ContentId = attachment.contentId;
            }
            else
            {
                var conent_type = Common.Web.MimeMapping.GetMimeMapping(s3_key);
                ret_val.ContentType = new ContentType {Type = conent_type};
                ret_val.Filename = file_name;
                if (attachment.contentId != null) ret_val.ContentId = attachment.contentId;
                ret_val.TextContent = "";
            }

            return ret_val;
        }
Beispiel #42
0
 /// <summary>
 /// Dispatches the parts.
 /// </summary>
 /// <param name="root">The root.</param>
 /// <param name="message">The message.</param>
 private static void DispatchParts(MimePart root, ref Message message)
 {
     foreach (MimePart entity in root.SubParts)
     {
         DispatchPart(entity, ref message);
     }
 }
Beispiel #43
0
        private static void DispatchPart(MimePart part, ref Message message)
        {
            if (part.SubParts.Count > 0) // This is a container part.
            {
                _parentContentType = part.ContentType; // saveing right content-type of message
                DispatchParts(part, ref message);
            }
            else // This is a leaf part.
            {
                // We will consider the highest-level text parts that are not attachments to be the intended for display.
                // We know the highest-level parts will be set, because the parser first goes to the deepest level and returns top-level parts last.
                if (part.ContentType.Type.ToLower().Equals("text") && !part.ContentDisposition.Disposition.ToLower().Equals("attachment"))
                {
                    if (part.ContentType.SubType.ToLower().Equals("plain"))
                    {
                        message.BodyText.Charset = part.Charset;
                        message.BodyText.Text = part.TextContent;
                    }
                    else if (part.ContentType.SubType.ToLower().Equals("html"))
                    {
                        message.IsHtml = true;
                        message.BodyHtml.Charset = part.Charset;
                        message.BodyHtml.Text = part.TextContent;
                    }

                    if (_parentContentType != null)
                        message.ContentType = _parentContentType;
                }
                // If this part has to be displayed has an attachment, add it to the appropriate collection.
                else if (part.ContentDisposition.Disposition.ToLower().Equals("attachment"))
                {
                    message.Attachments.Add(part);
                }
                // If this part has to be displayed at the same time as the main body, add it to the appropriate collection.
                else if (part.ContentDisposition.Disposition.ToLower().Equals("inline"))
                {
                    message.EmbeddedObjects.Add(part);
                }
                // If we have image isn't marked as "Content-Disposition: inline", we will add it to EmbededObjects
                else if (part.ContentType.Type.ToLower().Equals("image"))
                {
                    message.EmbeddedObjects.Add(part);
                }

                // Parse message/rfc822 parts as Message objects and place them in the appropriate collection.
                else if (part.ContentType.MimeType.ToLower().Equals("message/rfc822"))
                {
                    var msg = part.TextContent;
                    message.SubMessages.Add(ParseMessage(ref msg)); //.BinaryContent));
                }

                else if (part.ContentType.MimeType.ToLower().Equals("application/pkcs7-signature")
                    || part.ContentType.MimeType.ToLower().Equals("application/x-pkcs7-signature"))
                {
                    var to_digest = part.Container.TextContent;
                    to_digest = Regex.Split(to_digest, "\r\n--" + part.Container.ContentType.Parameters["boundary"])[1];
                    to_digest = to_digest.TrimStart('\r', '\n');
                    //Match endDelimiter = Regex.Match(toDigest, "(?<=[^\r\n]\r\n)\r\n", RegexOptions.RightToLeft);
                    //int lastNonNewLine = Regex.Match(toDigest, "[^\r\n]", RegexOptions.RightToLeft).Index;
                    //if (endDelimiter.Index != -1 && endDelimiter.Index > lastNonNewLine) toDigest = toDigest.Remove(endDelimiter.Index);

                    //TODO: What should be done in PPC ?
#if !PocketPC
                    message.Signatures.Smime = new SignedCms(new ContentInfo(Encoding.ASCII.GetBytes(to_digest)), true);
                    message.Signatures.Smime.Decode(part.BinaryContent);
#endif
                }
                else if (message.IsMultipartReport && part.ContentType.MimeType.ToLower().Equals("message/delivery-status"))
                {
                    message.BodyText.Text += String.Format("\r\nDelivery status:\r\n{0}", part.TextContent);
                }
                else
                {
                    message.UnknownDispositionMimeParts.Add(part);
                }

                // Anyway, this is a leaf part of the message.
                message.LeafMimeParts.Add(part);
            }
        }
 public override bool Read()
 {
     bool flag = this.xmlReader.Read();
     if (this.xmlReader.NodeType == XmlNodeType.Element)
     {
         XopIncludeReader reader = null;
         if (this.xmlReader.IsStartElement(MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace))
         {
             string uri = null;
             while (this.xmlReader.MoveToNextAttribute())
             {
                 if ((this.xmlReader.LocalName == MtomGlobals.XopIncludeHrefLocalName) && (this.xmlReader.NamespaceURI == MtomGlobals.XopIncludeHrefNamespace))
                 {
                     uri = this.xmlReader.Value;
                 }
                 else if (this.xmlReader.NamespaceURI == MtomGlobals.XopIncludeNamespace)
                 {
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomXopIncludeInvalidXopAttributes", new object[] { this.xmlReader.LocalName, MtomGlobals.XopIncludeNamespace })));
                 }
             }
             if (uri == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomXopIncludeHrefNotSpecified", new object[] { MtomGlobals.XopIncludeHrefLocalName })));
             }
             MimePart part = this.ReadMimePart(uri);
             this.CheckContentTransferEncodingOnBinaryPart(part.Headers.ContentTransferEncoding);
             this.part = part;
             reader = new XopIncludeReader(part, this.xmlReader);
             reader.Read();
             this.xmlReader.MoveToElement();
             if (this.xmlReader.IsEmptyElement)
             {
                 this.xmlReader.Read();
             }
             else
             {
                 int depth = this.xmlReader.Depth;
                 this.xmlReader.ReadStartElement();
                 while (this.xmlReader.Depth > depth)
                 {
                     if (this.xmlReader.IsStartElement() && (this.xmlReader.NamespaceURI == MtomGlobals.XopIncludeNamespace))
                     {
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomXopIncludeInvalidXopElement", new object[] { this.xmlReader.LocalName, MtomGlobals.XopIncludeNamespace })));
                     }
                     this.xmlReader.Skip();
                 }
                 this.xmlReader.ReadEndElement();
             }
         }
         if (reader != null)
         {
             this.xmlReader.MoveToContent();
             this.infosetReader = this.xmlReader;
             this.xmlReader = reader;
             reader = null;
         }
     }
     if ((this.xmlReader.ReadState == System.Xml.ReadState.EndOfFile) && (this.infosetReader != null))
     {
         if (!flag)
         {
             flag = this.infosetReader.Read();
         }
         this.part.Release(this.maxBufferSize, ref this.bufferRemaining);
         this.xmlReader = this.infosetReader;
         this.infosetReader = null;
     }
     return flag;
 }
Beispiel #45
0
        /// <summary>
        /// Parses the MIME part.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public static MimePart ParseMimePart(ref string data, Message message)
        {
            var part = new MimePart();
            //part.ParentMessage = message;
            //part.OriginalContent = data;

            try
            {
                // Separate header and body.
                var headerEnd = _regxHeaderEnd.Match(data).Index + 1;
                var bodyStart = _regxBodyStart.Match(data).Index; 

                //TODO: remove this workaround
                if (bodyStart == 0)
                {
                    //bodyStart = data.IndexOf("\r\n\r\n");
                    // Fix for a bug - the bodyStart was -1 (Invalid), MCALADO: 04/07/2008
                    var indexBody = data.IndexOf("\r\n\r\n", StringComparison.Ordinal);
                    if (indexBody > 0)
                    {
                        bodyStart = indexBody;
                    }
                }

                if (data.Length >= headerEnd)
                {
                    var header = data.Substring(0, headerEnd);

                    header = Unfold(header);

                    // Parse header fields and their parameters.
                    var m = _regxHeaderFieldsParams.Match(header); 
                    while (m.Success)
                    {
                        if (m.Value.ToLower().StartsWith("content-type:"))
                        {
                            part.ContentType = GetContentType(m.Value);

                            if (m.Value.ToLower().IndexOf("charset", StringComparison.Ordinal) != -1)
                                part.Charset = GetCharset(m.Value);
                        }
                        else if (m.Value.ToLower().StartsWith("content-disposition:"))
                        {
                            part.ContentDisposition = GetContentDisposition(m.Value);
                        }

                        var commaIndex = m.Value.IndexOf(':');
                        var name = FormatFieldName(m.Value.Substring(0, commaIndex));
                        var value = Codec.RFC2047Decode(m.Value.Substring(commaIndex + 1).Trim(' ', '\r', '\n')).Trim('\n');

                        part.HeaderFields.Add(name, value);
                        part.HeaderFieldNames.Add(name, value);

                        m = m.NextMatch();
                    }

                    var isMultipart = part.ContentType.Type.ToLower().Equals("multipart");

                    // Store the (maybe still encoded) body.
                    part.TextContent = isMultipart ? 
                        string.Empty :
                        (bodyStart < data.Length ? data.Substring(bodyStart) : string.Empty);

                    // Build the part tree.

                    // This is a container part.
                    if (isMultipart)
                    {
                        ParseSubParts(ref part, ref data, message);
                    }
                    // This is a nested message.
                    else if (part.ContentType.Type.ToLower().Equals("message"))
                    {
                        // TODO
                    }
                    // This is a leaf of the part tree
                    // Check necessary for single part emails (fix from alex294 on CodePlex)
                    // Why would we consider the body only to the first string?  Doesn't make sense - and fails
                    //else if (part.ContentType.Type.ToLower().Equals("text"))
                    //{
                    //    int BodyEnd = body.IndexOf(' ');
                    //    if (BodyEnd > 0)
                    //    {
                    //        part.TextContent = body.Substring(0, BodyEnd);
                    //    }
                    //}

                    if (!isMultipart) 
                        DecodePartBody(ref part);

                    try
                    {
                        if (BodyParsed != null)
                            BodyParsed(null, message);
                    }
                    catch (Exception)
                    {
                        // event is not supported.
                    }
                }

            }
            catch (Exception ex)
            {
                throw new ParsingException(ex.Message);
            }

            return part;
        }
	public void Remove(MimePart mimePart) {}
		/// <summary>
		/// Adds the MimePart object to the collection.
		/// </summary>
		/// <param name="part">The MimePart to be added.</param>
		public void Add(MimePart part)
		{
			this.List.Add(part);
		}
        public void Write_Binary_Test()
        {
            var bytes = Enumerable.Range(0, 256).Select(i => (byte) i).ToArray();
            var part = new MimePart(new MemoryStream(bytes));
            string result;

            using (var message = new MimeMessage(part) {Boundary = "abc123"})
            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            var expected = @"--abc123
            Content-Length: 256

            " + Encoding.UTF8.GetString(bytes) + @"
            --abc123--";
            Assert.That(result, Is.EqualTo(expected));
        }
 internal MimePartThreadAccessToken(MimePart parent)
 {
 }
 private void WriteXOPInclude()
 {
     if (this.binaryDataChunks != null)
     {
         bool flag = true;
         long num = 0L;
         foreach (MtomBinaryData data in this.binaryDataChunks)
         {
             long length = data.Length;
             if ((length < 0L) || (length > (0x2ffL - num)))
             {
                 flag = false;
                 break;
             }
             num += length;
         }
         if (flag)
         {
             this.WriteBase64Inline();
         }
         else
         {
             if (this.mimeParts == null)
             {
                 this.mimeParts = new List<MimePart>();
             }
             MimePart item = new MimePart(this.binaryDataChunks, this.contentID, this.contentType, MimeGlobals.EncodingBinary, this.sizeOfBufferedBinaryData, this.maxSizeInBytes);
             this.mimeParts.Add(item);
             this.totalSizeOfMimeParts += ValidateSizeOfMessage(this.maxSizeInBytes, this.totalSizeOfMimeParts, item.sizeInBytes);
             this.totalSizeOfMimeParts += ValidateSizeOfMessage(this.maxSizeInBytes, this.totalSizeOfMimeParts, this.mimeWriter.GetBoundarySize());
             this.Writer.WriteStartElement(MtomGlobals.XopIncludePrefix, MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace);
             this.Writer.WriteStartAttribute(MtomGlobals.XopIncludeHrefLocalName, MtomGlobals.XopIncludeHrefNamespace);
             this.Writer.WriteValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { MimeGlobals.ContentIDScheme, Uri.EscapeDataString(this.contentID) }));
             this.Writer.WriteEndAttribute();
             this.Writer.WriteEndElement();
             this.binaryDataChunks = null;
             this.sizeOfBufferedBinaryData = 0;
             this.contentType = null;
             this.contentID = null;
         }
     }
 }
	public bool Contains(MimePart mimePart) {}
        private WebRequest CreateRequest(string uri, RequestOperation op)
        {
            var request = WebRequest.Create(uri);
            request.Method = op.Method.ToString().ToUpper();
            request.Timeout = Timeout;
            request.PreAuthenticate = true;

            if (_proxySet)
            {
                request.Proxy = _proxy;
            }

            var httpRequest = request as HttpWebRequest;
            if (httpRequest != null)
            {
                httpRequest.AllowAutoRedirect = false;
                httpRequest.ReadWriteTimeout = Timeout;
                httpRequest.KeepAlive = false;
                httpRequest.ProtocolVersion = HttpVersion.Version10;

                if (Accept != null)
                {
                    httpRequest.Accept = string.Join(",", Array.ConvertAll(Accept, type => MediaTypeNames.GetMediaType(type)));
                }

                if (Cookies != null)
                {
                    httpRequest.CookieContainer = Cookies;
                }

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    httpRequest.UserAgent = UserAgent;
                }
            }

            if (Credentials != null)
            {
                request.Credentials = Credentials;
            }
            else if (!string.IsNullOrEmpty(UserName) || !string.IsNullOrEmpty(Password))
            {
                var uriPrefix = new Uri(uri);
                var cred = new NetworkCredential(UserName, Password);
                request.Credentials = new CredentialCache
                                      {
                                          {uriPrefix, "Basic", cred},
                                          {uriPrefix, "Digest", cred},
                                          {uriPrefix, "NTLM", cred},
                                          {uriPrefix, "Kerberos", cred},
                                          {uriPrefix, "Negotiate", cred}
                                      };
            }
            else
            {
                request.Credentials = CredentialCache.DefaultCredentials;
            }

            if (!string.IsNullOrEmpty(op.ETag))
            {
                var header = op.Method == HttpMethod.Get
                                 ? HttpRequestHeader.IfNoneMatch
                                 : HttpRequestHeader.IfMatch;
                request.Headers[header] = op.ETag;
            }

            if (op.Resource != null)
            {
                using (var stream = request.GetRequestStream())
                {
                    var requestStream = op.Files.Count > 0 ? new MemoryStream() : stream;
                    MediaType mediaType;

                    if (op.Resource is ISyndicationResource)
                    {
                        mediaType = op.Resource is AtomFeed ? MediaType.Atom : MediaType.AtomEntry;
                        ((ISyndicationResource) op.Resource).Save(requestStream);
                    }
                    else if (op.Resource is IXmlSerializable)
                    {
                        mediaType = MediaType.Xml;

                        using (var xmlWriter = XmlWriter.Create(requestStream))
                        {
                            ((IXmlSerializable) op.Resource).WriteXml(xmlWriter);
                        }
                    }
                    else if (op.Resource is string)
                    {
                        mediaType = MediaType.Text;

                        using (var writer = new StreamWriter(requestStream))
                        {
                            writer.Write((string) op.Resource);
                        }
                    }
                    else
                    {
                        throw new Exception();
                    }

                    if (op.ContentType != null)
                    {
                        mediaType = op.ContentType.Value;
                    }

                    var contentType = MediaTypeNames.GetMediaType(mediaType);

                    if (op.Files.Count > 0)
                    {
                        requestStream.Seek(0, SeekOrigin.Begin);
                        var part = new MimePart(requestStream) {ContentType = contentType};

                        using (var multipart = new MimeMessage(part))
                        {
                            contentType = new ContentType("multipart/related") {Boundary = multipart.Boundary}.ToString();

                            foreach (var file in op.Files)
                            {
                                var type = !string.IsNullOrEmpty(file.ContentType) ? file.ContentType : "application/octet-stream";
                                var disposition = new ContentDisposition(DispositionTypeNames.Attachment) {FileName = file.FileName};
                                part = new MimePart(file.Stream)
                                       {
                                           ContentType = type,
                                           ContentTransferEncoding = "binary",
                                           ContentDisposition = disposition
                                       };
                                multipart.Add(part);
                            }

                            multipart.WriteTo(stream);
                        }
                    }

                    request.ContentType = contentType;
                }
            }

            return request;
        }
        public void Write_Headers_Test()
        {
            string result;
            var part = new MimePart(null)
                       {
                           ContentType = "plain/xml",
                           ContentLength = 20,
                           ContentTransferEncoding = "binary",
                           ContentDisposition = new ContentDisposition(DispositionTypeNames.Attachment)
                       };

            var message = new MimeMessage(part) {Boundary = "abc123"};

            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            const string expected = @"--abc123
            Content-Type: plain/xml
            Content-Length: 20
            Content-Transfer-Encoding: binary
            Content-Disposition: attachment

            --abc123--";
            Assert.That(result, Is.EqualTo(expected));
        }
 /// <summary>
 /// Add a MimePart to the embedded objects collection.
 /// </summary>
 /// <param name="part"></param>
 public new void Add(MimePart part)
 {
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
 }
        /*
         * extracts attachments from message
         */
        private static void ExtractAttachments(
            MimePart entity,
            MimeMessage msg,
            Node node,
            string basePath,
            string attachmentDirectory,
            string linkedAttachmentDirectory)
        {
            if (entity is ApplicationPkcs7Mime)
                return; // don't bother about p7m attachments

            string fileName;
            if (entity.Headers.Contains("Content-Location"))
            {
                // this is a linked resource, replacing references inside html with local filename
                fileName = linkedAttachmentDirectory + msg.MessageId + "_" + entity.FileName;
                if (node.Contains("body") && node["body"].ContainsValue("html"))
                    node["body"]["html"].Value =
                        node["body"]["html"].Get<string>().Replace(entity.Headers["Content-Location"], fileName);
            }
            else if (entity.Headers.Contains("Content-ID"))
            {
                fileName = linkedAttachmentDirectory + msg.MessageId + "_" + entity.FileName;
                string contentId = entity.Headers["Content-ID"].Trim('<').Trim('>');
                if (node.Contains("body") && node["body"].ContainsValue("html"))
                    node["body"]["html"].Value =
                        node["body"]["html"].Get<string>().Replace("cid:" + contentId, fileName);
            }
            else
            {
                fileName = attachmentDirectory + msg.MessageId + "_" + entity.FileName;
                Node attNode = new Node("", entity.FileName ?? "");
                attNode["local-file-name"].Value = fileName;
                node["attachments"].Add(attNode);
            }

            using (Stream stream = File.Create(basePath + fileName))
            {
                entity.ContentObject.DecodeTo(stream);
            }
        }
	public void Insert(int index, MimePart mimePart) {}
Beispiel #57
0
        private HttpWebResponse UploadFiles(Dictionary<string, string> files, Dictionary<string, string> otherValues)
        {
            var req = (HttpWebRequest)WebRequest.Create(this.Url);

            req.Timeout = 10000 * 1000;
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            req.AllowAutoRedirect = false;

            var mimeParts = new List<MimePart>();
            //try {
                if (otherValues != null) {
                    foreach (var fieldName in otherValues.Keys) {
                        var part = new MimePart();

                        part.Headers["Content-Disposition"] = "form-data; name=\"" + fieldName + "\"";
                        part.Data = new MemoryStream(Encoding.UTF8.GetBytes(otherValues[fieldName]));

                        mimeParts.Add(part);
                    }
                }

                if (files != null) {
                    foreach (var fieldName in files.Keys) {
                        var part = new MimePart();
                        string ctype;
                        part.Headers["Content-Disposition"] = "form-data; name=\"" + fieldName + "\"; filename=\"" + files[fieldName] + "\"";
                        part.Headers["Content-Type"] = TryGetContentType(files[fieldName], out ctype) ? ctype : "application/octet-stream";
                        part.Data = File.OpenRead(files[fieldName]);

                        mimeParts.Add(part);
                    }
                }

                string boundary = "----------" + DateTime.Now.Ticks.ToString("x");

                req.ContentType = "multipart/form-data; boundary=" + boundary;
                req.Method = this.Method;

                long contentLength = 0;

                byte[] _footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");

                foreach (MimePart part in mimeParts) {
                    contentLength += part.GenerateHeaderFooterData(boundary);
                }

                req.ContentLength = contentLength + _footer.Length;

                byte[] buffer = new byte[8192];
                byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");
                int read;

                using (Stream s = req.GetRequestStream()) {
                    foreach (MimePart part in mimeParts) {
                        s.Write(part.Header, 0, part.Header.Length);

                        while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)
                            s.Write(buffer, 0, read);

                        part.Data.Dispose();

                        s.Write(afterFile, 0, afterFile.Length);
                    }

                    s.Write(_footer, 0, _footer.Length);
                }

                var res = (HttpWebResponse)req.GetResponse();

                return res;
            /*} catch (Exception ex) {
                Console.WriteLine(ex.Message);
                foreach (MimePart part in mimeParts)
                    if (part.Data != null)
                        part.Data.Dispose();

                return (HttpWebResponse)req.GetResponse();
            }*/
        }
Beispiel #58
0
		static void ExtractAttachments (TnefReader reader, BodyBuilder builder)
		{
			var filter = new BestEncodingFilter ();
			var prop = reader.TnefPropertyReader;
			MimePart attachment = null;
			int outIndex, outLength;
			byte[] attachData;
			string text;

			do {
				if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
					break;

				switch (reader.AttributeTag) {
				case TnefAttributeTag.AttachRenderData:
					attachment = new MimePart ();
					builder.Attachments.Add (attachment);
					break;
				case TnefAttributeTag.Attachment:
					if (attachment == null)
						break;

					while (prop.ReadNextProperty ()) {
						switch (prop.PropertyTag.Id) {
						case TnefPropertyId.AttachLongFilename:
							attachment.FileName = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachFilename:
							if (attachment.FileName == null)
								attachment.FileName = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachContentLocation:
							text = prop.ReadValueAsString ();
							if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
								attachment.ContentLocation = new Uri (text, UriKind.Absolute);
							else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
								attachment.ContentLocation = new Uri (text, UriKind.Relative);
							break;
						case TnefPropertyId.AttachContentBase:
							text = prop.ReadValueAsString ();
							attachment.ContentBase = new Uri (text, UriKind.Absolute);
							break;
						case TnefPropertyId.AttachContentId:
							attachment.ContentId = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachDisposition:
							text = prop.ReadValueAsString ();
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition (text);
							else
								attachment.ContentDisposition.Disposition = text;
							break;
						case TnefPropertyId.AttachData:
							// TODO: implement this...
							break;
						}
					}
					break;
				case TnefAttributeTag.AttachData:
					if (attachment == null)
						break;

					attachData = prop.ReadValueAsBytes ();
					filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
					attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.EightBit);
					attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
					filter.Reset ();
					break;
				}
			} while (reader.ReadNextAttribute ());
		}
 private MimePart ReadMimePart(string uri)
 {
     MimePart part = null;
     if ((uri == null) || (uri.Length == 0))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomInvalidEmptyURI")));
     }
     string key = null;
     if (uri.StartsWith(MimeGlobals.ContentIDScheme, StringComparison.Ordinal))
     {
         key = string.Format(CultureInfo.InvariantCulture, "<{0}>", new object[] { Uri.UnescapeDataString(uri.Substring(MimeGlobals.ContentIDScheme.Length)) });
     }
     else if (uri.StartsWith("<", StringComparison.Ordinal))
     {
         key = uri;
     }
     if (key == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomInvalidCIDUri", new object[] { uri })));
     }
     if ((this.mimeParts == null) || !this.mimeParts.TryGetValue(key, out part))
     {
         while ((part == null) && this.mimeReader.ReadNextPart())
         {
             MimeHeaders headers = this.mimeReader.ReadHeaders(this.maxBufferSize, ref this.bufferRemaining);
             Stream contentStream = this.mimeReader.GetContentStream();
             if (contentStream == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomMessageInvalidContentInMimePart")));
             }
             ContentIDHeader header = (headers == null) ? null : headers.ContentID;
             if ((header == null) || (header.Value == null))
             {
                 int count = 0x100;
                 byte[] buffer = new byte[count];
                 while (contentStream.Read(buffer, 0, count) > 0)
                 {
                 }
             }
             else
             {
                 string str2 = headers.ContentID.Value;
                 MimePart part2 = new MimePart(contentStream, headers);
                 if (this.mimeParts == null)
                 {
                     this.mimeParts = new Dictionary<string, MimePart>();
                 }
                 this.mimeParts.Add(str2, part2);
                 if (str2.Equals(key))
                 {
                     part = part2;
                 }
                 else
                 {
                     part2.GetBuffer(this.maxBufferSize, ref this.bufferRemaining);
                 }
             }
         }
         if (part == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomPartNotFound", new object[] { uri })));
         }
     }
     else if (part.ReferencedFromInfoset)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MtomMimePartReferencedMoreThanOnce", new object[] { key })));
     }
     part.ReferencedFromInfoset = true;
     return part;
 }
 /// <summary>
 /// Generate and add a MimePart to the embedded objects collection, using the specified file.
 /// </summary>
 /// <param name="path">The file containing the MimePart's content.</param>
 /// <param name="generateContentId">If true, a Content-ID Header field will be generated for the part.</param>
 /// <param name="charset">The charset of the text contained in the file.</param>
 /// <remarks>This method is to be used with text files to ensure data integrity using the correct charset.</remarks>
 public new string Add(string path, bool generateContentId, string charset)
 {
     MimePart part = new MimePart(path, generateContentId, charset);
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
     return part.ContentId;
 }