private static MimePart GetMimePart(AttachmentBase item)
        {
            var      mimeType    = item.ContentType.ToString();
            var      contentType = ContentType.Parse(mimeType);
            var      attachment  = item as Attachment;
            MimePart part;

            if (contentType.MediaType.Equals("text", StringComparison.OrdinalIgnoreCase))
            {
                // Original: part = new TextPart(contentType);
                // Due to constructor of TextPart(ContentType contentType) being internal,
                // mimic the instantiation by using MimePart(ContentType contentType)
                part = new MimePart(contentType);
            }
            else
            {
                part = new MimePart(contentType);
            }

            if (attachment != null)
            {
                var disposition = attachment.ContentDisposition.ToString();
                part.ContentDisposition = ContentDisposition.Parse(disposition);
            }

            switch (item.TransferEncoding)
            {
            case System.Net.Mime.TransferEncoding.QuotedPrintable:
                part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
                break;

            case System.Net.Mime.TransferEncoding.Base64:
                part.ContentTransferEncoding = ContentEncoding.Base64;
                break;

            case System.Net.Mime.TransferEncoding.SevenBit:
                part.ContentTransferEncoding = ContentEncoding.SevenBit;
                break;

            case System.Net.Mime.TransferEncoding.EightBit:
                part.ContentTransferEncoding = ContentEncoding.EightBit;
                break;
            }

            if (item.ContentId != null)
            {
                part.ContentId = item.ContentId;
            }

            var stream = new MemoryBlockStream();

            item.ContentStream.CopyTo(stream);
            stream.Position = 0;

#pragma warning disable CS0618 // Type or member is obsolete, this line will be removed once the ContentObject property is fully removed
            part.ContentObject = new ContentObject(stream);
#pragma warning restore CS0618 // Type or member is obsolete, this line will be removed once the ContentObject property is fully removed

            return(part);
        }
        public async Task TrySendDocumentBackAsync(Uri @from)
        {
            this.Log($"Started {nameof(this.TrySendDocumentBackAsync)} for {@from.LocalPath}");

            var webClient = new WebClient();

            string ExtractFromContentDisposition(string key) =>
            ContentDisposition.Parse(webClient.ResponseHeaders["content-disposition"])?[key];

            try
            {
                await using var stream = await webClient.OpenReadTaskAsync(@from);

                await this.botClient.SendDocumentAsync(
                    this.message.Chat,
                    new InputOnlineFile(stream, ExtractFromContentDisposition("filename")))
                .ContinueWith(task => this.Log(
                                  $"{nameof(this.TrySendDocumentBackAsync)} is {task.Status}. "
                                  + $"{nameof(task.Result.Document.FileName)}={task.Result.Document.FileName}"));
            }
            catch (Exception e)
            {
                var customMessage = $"{nameof(this.TrySendDocumentBackAsync)} is Failed";

                this.Text(e.GetShortDescription(customMessage));
                this.Log(e.GetFullDescription(customMessage));
            }
        }
Esempio n. 3
0
        static void AssertParse(string text, ContentDisposition expected, bool result = true, int tokenIndex = -1, int errorIndex = -1)
        {
            var buffer  = Encoding.UTF8.GetBytes(text);
            var options = ParserOptions.Default;
            ContentDisposition disposition;

            Assert.AreEqual(result, ContentDisposition.TryParse(text, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(options, text, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(buffer, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(options, buffer, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(buffer, 0, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(options, buffer, 0, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(buffer, 0, buffer.Length, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            Assert.AreEqual(result, ContentDisposition.TryParse(options, buffer, 0, buffer.Length, out disposition), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(disposition, expected);

            try {
                disposition = ContentDisposition.Parse(text);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(options, text);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(buffer);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(options, buffer);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(buffer, 0);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(options, buffer, 0);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(buffer, 0, buffer.Length);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                disposition = ContentDisposition.Parse(options, buffer, 0, buffer.Length);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(disposition, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }
        }
Esempio n. 4
0
        public void TestDispositionParameters()
        {
            const string expected = "Content-Disposition: attachment; filename=document.doc;\n" +
                                    "\tcreation-date=\"Sat, 04 Jan 1997 15:22:17 -0400\";\n" +
                                    "\tmodification-date=\"Thu, 04 Jan 2007 15:22:17 -0400\";\n" +
                                    "\tread-date=\"Wed, 04 Jan 2012 15:22:17 -0400\"; size=37001";
            var        ctime       = new DateTimeOffset(1997, 1, 4, 15, 22, 17, new TimeSpan(-4, 0, 0));
            var        mtime       = new DateTimeOffset(2007, 1, 4, 15, 22, 17, new TimeSpan(-4, 0, 0));
            var        atime       = new DateTimeOffset(2012, 1, 4, 15, 22, 17, new TimeSpan(-4, 0, 0));
            var        disposition = new ContentDisposition();
            var        format      = FormatOptions.Default.Clone();
            const long size        = 37001;
            Parameter  param;
            string     encoded;

            format.NewLineFormat = NewLineFormat.Unix;

            Assert.AreEqual(ContentDisposition.Attachment, disposition.Disposition, "The disposition should be 'attachment'.");
            Assert.IsTrue(disposition.IsAttachment, "IsAttachment should be true by default.");

            Assert.IsNull(disposition.FileName, "The filename should default to null.");
            Assert.IsNull(disposition.CreationDate, "The creation-date should default to null.");
            Assert.IsNull(disposition.ModificationDate, "The modification-date should default to null.");
            Assert.IsNull(disposition.ReadDate, "The read-date should default to null.");
            Assert.IsNull(disposition.Size, "The size should default to null.");

            disposition.FileName         = "document.doc";
            disposition.CreationDate     = ctime;
            disposition.ModificationDate = mtime;
            disposition.ReadDate         = atime;
            disposition.Size             = size;

            encoded = disposition.ToString(format, Encoding.UTF8, true);

            Assert.AreEqual(expected, encoded, "The encoded Content-Disposition does not match.");

            disposition = ContentDisposition.Parse(encoded.Substring("Content-Disposition:".Length));

            Assert.AreEqual("document.doc", disposition.FileName, "The filename parameter does not match.");
            Assert.AreEqual(ctime, disposition.CreationDate, "The creation-date parameter does not match.");
            Assert.AreEqual(mtime, disposition.ModificationDate, "The modification-date parameter does not match.");
            Assert.AreEqual(atime, disposition.ReadDate, "The read-date parameter does not match.");
            Assert.AreEqual(size, disposition.Size, "The size parameter does not match.");

            disposition.CreationDate = null;
            Assert.IsFalse(disposition.Parameters.TryGetValue("creation-date", out param), "The creation-date parameter should have been removed.");

            disposition.ModificationDate = null;
            Assert.IsFalse(disposition.Parameters.TryGetValue("modification-date", out param), "The modification-date parameter should have been removed.");

            disposition.ReadDate = null;
            Assert.IsFalse(disposition.Parameters.TryGetValue("read-date", out param), "The read-date parameter should have been removed.");

            disposition.FileName = null;
            Assert.IsFalse(disposition.Parameters.TryGetValue("filename", out param), "The filename parameter should have been removed.");

            disposition.Size = null;
            Assert.IsFalse(disposition.Parameters.TryGetValue("size", out param), "The size parameter should have been removed.");

            disposition.IsAttachment = false;
            Assert.AreEqual(ContentDisposition.Inline, disposition.Disposition, "The disposition should be 'inline'.");
            Assert.IsFalse(disposition.IsAttachment, "IsAttachment should be false.");
        }
 public string Parse(string contentDisposition, string key)
 {
     return(ContentDisposition.Parse(contentDisposition)?[key]);
 }
        protected override async Task SendEmailInternalAsync(EmailModel emailModel)
        {
            var mimeMessage = new MimeMessage
            {
                Subject = emailModel.Subject
            };

            mimeMessage.From.Add(emailModel.From != null
                ? new MailboxAddress(Encoding.UTF8, emailModel.From.Name, emailModel.From.Email)
                : new MailboxAddress(_smtpConfig.From));

            mimeMessage.To.AddRange(emailModel.Recipients.Select(a => new MailboxAddress(Encoding.UTF8, a.Name, a.Email)));

            if (emailModel.Cc?.Any() == true)
            {
                mimeMessage.Cc.AddRange(emailModel.Cc.Select(a => new MailboxAddress(Encoding.UTF8, a.Name, a.Email)));
            }

            if (emailModel.Bcc?.Any() == true)
            {
                mimeMessage.Bcc.AddRange(emailModel.Bcc.Select(a => new MailboxAddress(Encoding.UTF8, a.Name, a.Email)));
            }

            var bodyBuilder = new BodyBuilder
            {
                TextBody = emailModel.TextBody,
                HtmlBody = emailModel.HtmlBody
            };

            if (emailModel.Attachments != null)
            {
                foreach (var attachment in emailModel.Attachments)
                {
                    var mimeEntity = bodyBuilder.Attachments.Add(
                        attachment.Filename,
                        attachment.Bytes,
                        ContentType.Parse(attachment.ContentType));

                    if (!string.IsNullOrEmpty(attachment.ContentDisposition))
                    {
                        mimeEntity.ContentDisposition = ContentDisposition.Parse(attachment.ContentDisposition);
                    }

                    if (!string.IsNullOrEmpty(attachment.ContentId))
                    {
                        mimeEntity.ContentId = attachment.ContentId;
                    }
                }
            }

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using var emailClient = new SmtpClient();

            try
            {
                _logger.LogInformation($"*** START SEND EMAIL BY SMTP - Smtp host: {_smtpConfig.Host} - Port: {_smtpConfig.Port}***");

                await emailClient.ConnectAsync(_smtpConfig.Host, _smtpConfig.Port, SecureSocketOptions.StartTls);

                if (!string.IsNullOrEmpty(_smtpConfig.Username) &&
                    !string.IsNullOrEmpty(_smtpConfig.Password))
                {
                    await emailClient.AuthenticateAsync(_smtpConfig.Username, _smtpConfig.Password);
                }
                await emailClient.SendAsync(mimeMessage);

                await emailClient.DisconnectAsync(true);

                _logger.LogInformation("*** END SEND EMAIL ***");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw new EmailSenderException(ex.Message, ex);
            }
        }