Example #1
0
        public void AddHeader(string field, string value)
        {
            switch (field.ToLowerInvariant())
            {
            case "content-type": ContentType = new ContentType(value); break;

            case "transfer-encoding":
                switch (value.ToLowerInvariant())
                {
                case "chunked":
                    TransferEncoding = TransferEncoding.Chunked;
                    break;
                }
                break;

            case "content-length":
                int len;
                if (int.TryParse(value, out len))
                {
                    if (len < 0)
                    {
                        throw new HttpException("ContentLength was negative.");
                    }

                    ContentLength = len;
                }
                else
                {
                    throw new HttpException("ContentLength was in an invalid format.");
                }
                break;
            }
        }
Example #2
0
 /// <summary>
 ///     Send mail to client
 /// </summary>
 /// <param name="sendTo"></param>
 /// <param name="subject"></param>
 /// <param name="body"></param>
 /// <param name="replyTo"></param>
 /// <param name="attachments"></param>
 /// <param name="isBodyHtml"></param>
 /// <param name="encoding"></param>
 /// <param name="sendAsync"></param>
 /// <param name="additionalInlineFiles"></param>
 public static void SendMail(
     string sendTo,
     string subject,
     string body,
     string replyTo = null,
     IEnumerable <Attachment> attachments = null,
     bool isBodyHtml   = true,
     Encoding encoding = null,
     TransferEncoding transferEncoding = TransferEncoding.Base64,
     bool sendAsync = false,
     bool isBcc     = false,
     string[] additionalInlineFiles = null)
 {
     SendMails(
         !string.IsNullOrWhiteSpace(sendTo) && sendTo.Contains(";")
             ? sendTo.Split(';').Select(x => x.Trim())
             : new[]
     {
         sendTo
     },
         subject,
         body,
         replyTo,
         attachments,
         isBodyHtml,
         encoding,
         transferEncoding,
         sendAsync,
         null,
         isBcc,
         additionalInlineFiles);
 }
Example #3
0
        private void WriteEncodedBodyText(Stream stream, String value, TransferEncoding encodeType, Encoding encoding, Int32 maxCharCount)
        {
            Stream str = stream;

            Byte[] bb = null;

            if (maxCharCount > MaxCharCountPerRow)
            {
                throw new ArgumentException("maxCharCount must less than MimeWriter.MaxCharCountPerRow.");
            }

            switch (encodeType)
            {
            case TransferEncoding.None: bb = GetAsciiBytes(value); break;

            case TransferEncoding.SevenBit: bb = GetAsciiBytes(value); break;

            case TransferEncoding.EightBit: bb = encoding.GetBytes(value); break;

            case TransferEncoding.Binary: bb = Encoding.UTF8.GetBytes(value); break;

            case TransferEncoding.Base64: bb = _Base64BodyConverter.Encode(encoding.GetBytes(value)); break;

            case TransferEncoding.QuotedPrintable: bb = _QuotedPrintableBodyConverter.Encode(encoding.GetBytes(value)); break;

            default: throw new InvalidOperationException();
            }
            stream.Write(bb);
            stream.Write(ByteData.NewLine);
        }
Example #4
0
 private void StartSection(string section, ContentType sectionContentType, TransferEncoding transferEncoding)
 {
     SendData(String.Format("--{0}", section));
     SendHeader("content-type", sectionContentType.ToString());
     SendHeader("content-transfer-encoding", GetTransferEncodingName(transferEncoding));
     SendData(string.Empty);
 }
Example #5
0
        static StringSegment DecodeBody(Message message)
        {
            StringSegment    innerMessageText = message.Body.SourceText;
            TransferEncoding encoding         = message.GetTransferEncoding();

            switch (encoding)
            {
            default:
                throw new MimeException(MimeError.TransferEncodingNotSupported);

            case TransferEncoding.SevenBit:
                break;     // Nothing to do

            case TransferEncoding.QuotedPrintable:
                string decodedText = QuotedPrintableDecoder.Decode(innerMessageText);
                innerMessageText = new StringSegment(decodedText);
                break;

            case TransferEncoding.Base64:
                byte[] bytes         = Convert.FromBase64String(innerMessageText.ToString());
                string textFromBytes = Encoding.ASCII.GetString(bytes);
                innerMessageText = new StringSegment(textFromBytes);
                break;
            }

            return(innerMessageText);
        }
Example #6
0
 // Метод получения альтернативного способа просмотра письма
 private void GetView(string text)
 {
     if (text.Contains("\r\n\r\n"))
     {
         // Заголовок альтернативного способа просмотра письма
         string header = text.Substring(0, text.IndexOf("\r\n\r\n"));
         // Тело альтернативного способа просмотра письма
         string body = text.Substring(text.IndexOf("\r\n\r\n") + 4);
         // Тип контента альтернативного способа просмотра письма
         ContentType ct = ParserMessage.GetContentType(header);
         // Получение транспортной кодировки
         TransferEncoding transEncode = ParserMessage.GetBodyTransfer(header);
         // Получение текста письма в формате html-страницы
         if (ct.MediaType == MediaTypeNames.Text.Html)
         {
             BodyEncoding         = ParserMessage.MyGetEncoding(ct.CharSet);
             BodyTransferEncoding = transEncode;
             Body       = body;
             IsBodyHtml = true;
         }
         // Получение текста письма в виде обычного текста
         else if (ct.MediaType == MediaTypeNames.Text.Plain && !IsBodyHtml)
         {
             BodyEncoding         = ParserMessage.MyGetEncoding(ct.CharSet);
             BodyTransferEncoding = transEncode;
             Body = body;
         }
     }
 }
Example #7
0
        /// <summary>
        /// converts TransferEncoding as defined in the RFC into a .NET TransferEncoding
        /// .NET doesn't know the type "bit8". It is translated here into "bit7", which
        /// requires the same kind of processing (none).
        /// </summary>
        /// <param name="transferEncodingString">string to be converted into TransferEncoding</param>
        /// <returns>TransferEncoded string</returns>
        private static TransferEncoding ConvertToTransferEncoding(string transferEncodingString)
        {
            TransferEncoding result = TransferEncoding.Unknown;

            switch (transferEncodingString.Trim().ToUpperInvariant())
            {
            case ServiceConstants.MailAttributes.BIT_7:
            case ServiceConstants.MailAttributes.BIT_8:
                result = TransferEncoding.SevenBit;
                break;

            case ServiceConstants.MailAttributes.QUOTED_PRINTABLE:
                result = TransferEncoding.QuotedPrintable;
                break;

            case ServiceConstants.MailAttributes.BASE64:
                result = TransferEncoding.Base64;
                break;

            default:
                result = TransferEncoding.Unknown;
                break;
            }
            return(result);
        }
Example #8
0
        public AttachmentBuilder(StreamAttachment streamAtt, Encoding characterEncoding, TransferEncoding textTransferEncoding,
                                 TransferEncoding binaryTransferEncoding)
        {
            _attachment = new Attachment(streamAtt.Stream, streamAtt.DisplayName, streamAtt.MimeType)
            {
                ContentType = { MediaType = streamAtt.MimeType }
            };
            _attachment.ContentDisposition.Inline           = false;
            _attachment.ContentDisposition.FileName         = streamAtt.DisplayName.Trim(new[] { '\\', '/', ':' });
            _attachment.ContentDisposition.CreationDate     = DateTime.Now;
            _attachment.ContentDisposition.ModificationDate = _attachment.ContentDisposition.CreationDate;
            _attachment.ContentDisposition.ReadDate         = _attachment.ContentDisposition.CreationDate;
            _attachment.NameEncoding = characterEncoding;

            // Take care of correct encoding for the file name, otherwise
            // _attachment.TransferEncoding will throw FormatException 'MailHeaderFieldInvalidCharacter'
            // This also encodes spaces in the attachment name, because otherwise they would not be displayed correctly (RFC2047)
            Bugfixer.CorrectAttachmentFileNameEncoding(_attachment, characterEncoding);

            if (_attachment.ContentType.MediaType.ToLower().StartsWith("text/"))
            {
                _attachment.ContentType.CharSet = characterEncoding.HeaderName;
                _attachment.TransferEncoding    = textTransferEncoding;
            }
            else
            {
                _attachment.ContentType.CharSet = null;
                _attachment.TransferEncoding    = binaryTransferEncoding;
            }
        }
 /// <summary>
 /// バイトデータを元にデータをセットします。
 /// Allows to set ContentDisposition type for embedding mail images
 /// </summary>
 /// <param name="contentType"></param>
 /// <param name="bytes"></param>
 /// <param name="contentDisposition"></param>
 public void LoadData(Byte[] data, String contentType, String contentDisposition)
 {
     this.ContentType.Value        = contentType;
     this.ContentDisposition.Value = contentDisposition;
     this.ContentTransferEncoding  = TransferEncoding.Base64;
     this.BodyData = data;
 }
Example #10
0
        public AttachmentBuilder(StringAttachment stringAtt, Encoding characterEncoding, TransferEncoding textTransferEncoding,
                                 TransferEncoding binaryTransferEncoding)
        {
            string displayName = ShortNameFromFile(stringAtt.DisplayName);

            _attachment = Attachment.CreateAttachmentFromString(stringAtt.Content, displayName, characterEncoding,
                                                                stringAtt.MimeType);
            _attachment.ContentType.MediaType               = stringAtt.MimeType;
            _attachment.ContentDisposition.Inline           = false;
            _attachment.ContentDisposition.FileName         = displayName;
            _attachment.ContentDisposition.CreationDate     = DateTime.Now;
            _attachment.ContentDisposition.ModificationDate = DateTime.Now;
            _attachment.ContentDisposition.ReadDate         = DateTime.Now;
            // Use predefined att.ContentId
            _attachment.NameEncoding = characterEncoding;

            // Take care of correct encoding for the file name, otherwise
            // _attachment.TransferEncoding will throw FormatException 'MailHeaderFieldInvalidCharacter'
            Bugfixer.CorrectAttachmentFileNameEncoding(_attachment, characterEncoding);

            if (_attachment.ContentType.MediaType.ToLower().StartsWith("text/"))
            {
                _attachment.ContentType.CharSet = characterEncoding.HeaderName;
                _attachment.TransferEncoding    = Tools.IsSevenBit(_attachment.ContentStream, characterEncoding)
                                                                ? TransferEncoding.SevenBit
                                                                : textTransferEncoding;
            }
            else
            {
                _attachment.ContentType.CharSet = null;
                _attachment.TransferEncoding    = binaryTransferEncoding;
            }
        }
        public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType,
                                          TransferEncoding transferEncoding, CultureInfo culture = null)
        {
            Contract.Requires <ArgumentNullException>(helper != null);
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(path));
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(contentId));
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(mediaType));

            var resource = helper.Get(path, culture);

            if (resource == null)
            {
                var message = string.Format("Resource [{0}] was not found.", contentId);
                throw new TemplateHelperException(message);
            }
            var linkedResource = new LinkedResource(resource, mediaType)
            {
                TransferEncoding = transferEncoding
            };

            helper.AddLinkedResource(linkedResource);
            var renderedResult = new RawString(string.Format("cid:{0}", contentId));

            return(renderedResult);
        }
Example #12
0
        /// <summary>
        /// Instantiate a MIME part based on its body's byte array.
        /// </summary>
        /// <param name="name">Filename of the MIME part.</param>
        /// <param name="contentType">Content Type of the MIME part.</param>
        /// <param name="charset">Character Set used to encode the MIME part.</param>
        /// <param name="contentID">ID of the MIME part.</param>
        /// <param name="contentTransferEncoding">Content Transfer Encoding string of the MIME part.</param>
        /// <param name="bodyBytes">The MIME part's raw bytes.</param>
        public MimePart(string name, string contentType, string charset, string contentID, string contentTransferEncoding, byte[] bodyBytes)
        {
            BodyBytes   = bodyBytes;
            ContentType = contentType;
            ContentID   = contentID;
            CharSet     = charset;
            Name        = Functions.DecodeMailHeader(name).Replace("\r", "").Replace("\n", "");

            switch (contentTransferEncoding.ToLower())
            {
            case "base64":
                ContentTransferEncoding = TransferEncoding.Base64;
                break;

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

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

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

            default:
                ContentTransferEncoding = TransferEncoding.Unknown;
                break;
            }
        }
Example #13
0
        /// <summary>
        /// Decode body of a MimeEntity
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="MimeException"></exception>
        public static StringSegment DecodeBody(MimeEntity message)
        {
            StringSegment    innerMessageText = message.Body.SourceText;
            TransferEncoding encoding         = message.GetTransferEncoding();

            switch (encoding)
            {
            case TransferEncoding.QuotedPrintable:
                string decodedText = QuotedPrintableDecoder.Decode(innerMessageText);
                innerMessageText = new StringSegment(decodedText);
                break;

            case TransferEncoding.Base64:
                byte[] bytes         = Convert.FromBase64String(innerMessageText.ToString());
                string textFromBytes = Encoding.ASCII.GetString(bytes);
                innerMessageText = new StringSegment(textFromBytes);
                break;

                //
                // Case UUEncoding
                // Not supported.
                // TransferEncoding is a System.Net.Mime type without support for UUEncoding
                // Code would need to be refactored to accomodate.
                //
            }

            return(innerMessageText);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object" /> class.
 /// </summary>
 /// <param name="contentType">Type of the content.</param>
 /// <param name="encoding">The encoding.</param>
 /// <param name="source">The source.</param>
 public MessageContent(ContentType contentType, TransferEncoding encoding, Stream source)
 {
     ContentType = contentType;
     Encoding = encoding;
     source.Position = 0;
     source.CopyTo(_content);
     _content.Position = 0;
 }
Example #15
0
 private void InitializeProperty()
 {
     if (CultureInfo.CurrentCulture.Name.StartsWith("ja") == true)
     {
         this.Encoding         = Encoding.GetEncoding("iso-2022-jp");
         this.TransferEncoding = TransferEncoding.Base64;
     }
 }
 /// <summary>
 /// Initializes an instance of the Attachment class
 /// </summary>
 /// <param name="content">Content of attachment</param>
 /// <param name="contentType">ContentType of attachment</param>
 /// <param name="contentTransferEncoding">Content Transfer Encoding of attachment</param>
 /// <param name="fileName">File name of attachment</param>
 public Attachment(string content, string contentType, TransferEncoding contentTransferEncoding, string fileName = null)
     : base(content, contentType, contentTransferEncoding)
 {
     if (!string.IsNullOrEmpty(fileName))
     {
         this.FileName = fileName;
     }
 }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object" /> class.
 /// </summary>
 /// <param name="contentType">Type of the content.</param>
 /// <param name="encoding">The encoding.</param>
 /// <param name="source">The source.</param>
 public MessageContent(ContentType contentType, TransferEncoding encoding, Stream source)
 {
     ContentType     = contentType;
     Encoding        = encoding;
     source.Position = 0;
     source.CopyTo(content);
     content.Position = 0;
 }
        void send2(MailAddress from, MailAddress to, string subject, string body)
        {
            Encoding         encoding = this.encoding;
            TransferEncoding tranEnc  = System.Net.Mime.TransferEncoding.SevenBit;

            if (Str.IsSuitableEncodingForString(subject, Str.AsciiEncoding) &&
                Str.IsSuitableEncodingForString(body, Str.AsciiEncoding))
            {
                encoding = Str.AsciiEncoding;
                tranEnc  = System.Net.Mime.TransferEncoding.SevenBit;
            }
            else
            {
                if (!Str.IsSuitableEncodingForString(subject, encoding) || !Str.IsSuitableEncodingForString(body, encoding))
                {
                    encoding = Str.Utf8Encoding;
                    tranEnc  = System.Net.Mime.TransferEncoding.Base64;
                }
            }

            SmtpClient c = new SmtpClient(this.smtpServer);

            c.DeliveryMethod = SmtpDeliveryMethod.Network;
            c.EnableSsl      = false;
            c.Port           = this.SmtpPort;

            if (Str.IsEmptyStr(this.Username) == false && Str.IsEmptyStr(this.Password) == false)
            {
                c.UseDefaultCredentials = false;
                c.Credentials           = new System.Net.NetworkCredential(this.Username, this.Password);
            }

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(from, to);

            byte[] buffer = encoding.GetBytes(body);

            MemoryStream mem = new MemoryStream(buffer);

            AlternateView alt = new AlternateView(mem, new System.Net.Mime.ContentType("text/plain; charset=" + encoding.WebName));

            alt.TransferEncoding = tranEnc;

            mail.AlternateViews.Add(alt);
            mail.Body = "";

            byte[] sub         = encoding.GetBytes(subject);
            string subjectText = string.Format("=?{0}?B?{1}?=", encoding.WebName.ToUpper(),
                                               Convert.ToBase64String(sub, Base64FormattingOptions.None));

            mail.Subject = subjectText;

            mail.Headers.Add("X-Mailer", this.header_mailer);
            mail.Headers.Add("X-MSMail-Priority", this.header_msmail_priority);
            mail.Headers.Add("X-Priority", this.header_priority);
            mail.Headers.Add("X-MimeOLE", this.header_mimeole);

            c.Send(mail);
        }
        /// <summary>
        /// Creates secure message content container
        /// </summary>
        /// <param name="body">Body byte array</param>
        /// <param name="contentType">Body content type</param>
        /// <param name="encoding">Transfer encoding</param>
        /// <param name="encodeBody">Encode body</param>
        public SecureMessageContent(byte[] body, SecureContentType contentType, TransferEncoding encoding,
                                    bool encodeBody)
        {
            Body = encodeBody && encoding == TransferEncoding.Base64
                ? Encoding.UTF8.GetBytes(body.ToBase64String())
                : body;

            TransferEncoding = encoding;
            ContentType      = contentType;
        }
Example #20
0
        /// <summary>
        /// Parses the ContentTransferEncoding header, if any.
        /// If no header specified, returns SevenBit, the default
        /// If transfer encoding not recognized, returns TransferEncoding.Unknown
        /// </summary>
        /// <returns>The transfer encoding for this Mime Entity</returns>
        public TransferEncoding GetTransferEncoding()
        {
            TransferEncoding encoding = TransferEncoding.SevenBit;
            string           transferEncodingHeader = this.ContentTransferEncoding;

            if (!string.IsNullOrEmpty(transferEncodingHeader))
            {
                encoding = MimeStandard.ToTransferEncoding(transferEncodingHeader);
            }
            return(encoding);
        }
        /// <summary>
        ///
        /// </summary>
        public SmtpContent()
            : base()
        {
            this.Headers   = new SmtpMailHeaderCollection();
            this._Contents = new List <SmtpContent>();

            this.ContentType = new ContentType("application/octet-stream");
            this.ContentType.CharsetEncoding = Default.ContentTypeCharsetEncoding;
            this.ContentTransferEncoding     = Default.ContentTransferEncoding;
            this.ContentDisposition          = new ContentDisposition();
        }
Example #22
0
 ////////////////////////////////////////////////////////////////////
 // Constructor helper
 ////////////////////////////////////////////////////////////////////
 private void ConstructorHelper(ContentType type)
 {
     if (string.IsNullOrWhiteSpace(_contentString))
     {
         throw new ApplicationException("Content string is empty.");
     }
     this._type = type;
     MediaType  = type == ContentType.Html ? "text/html" : "text/plain";
     CharSet    = "utf-8";
     ContentTransferEncoding = TransferEncoding.QuotedPrintable;
     return;
 }
Example #23
0
 private void SetProperty()
 {
     if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "ja")
     {
         this.ContentTypeCharsetEncoding = Encoding.GetEncoding("iso-2022-jp");
     }
     else
     {
         this.ContentTypeCharsetEncoding = Encoding.UTF8;
     }
     this.ContentTransferEncoding = TransferEncoding.Base64;
 }
Example #24
0
        /// TransferEncodingから文字列を取得します。
        /// <summary>
        /// TransferEncodingから文字列を取得します。
        /// </summary>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static String ToTransferEncoding(TransferEncoding encoding)
        {
            switch (encoding)
            {
            case TransferEncoding.SevenBit: return("7bit");

            case TransferEncoding.Base64: return("Base64");

            case TransferEncoding.QuotedPrintable: return("Quoted-Printable");
            }
            return("7bit");
        }
Example #25
0
        public static Attachment CreateAttachment(Stream attachmentFile, string displayName,
                                                  TransferEncoding transferEncoding)
        {
            Attachment attachment = new Attachment(attachmentFile, MediaTypeNames.Application.Octet);

            attachment.TransferEncoding = transferEncoding;

            string tranferEncodingMarker = String.Empty;
            string encodingMarker        = String.Empty;
            int    maxChunkLength        = 0;

            switch (transferEncoding)
            {
            case TransferEncoding.Base64:
                tranferEncodingMarker = "B";
                encodingMarker        = "UTF-8";
                maxChunkLength        = 30;
                break;

            case TransferEncoding.QuotedPrintable:
                tranferEncodingMarker = "Q";
                encodingMarker        = "ISO-8859-1";
                maxChunkLength        = 76;
                break;

            default:
                throw (new ArgumentException(String.Format("The specified TransferEncoding is not supported: {0}",
                                                           transferEncoding), "transferEncoding"));
            }

            attachment.NameEncoding = Encoding.GetEncoding(encodingMarker);

            string encodingtoken         = String.Format("=?{0}?{1}?", encodingMarker, tranferEncodingMarker);
            string softbreak             = "?=";
            string encodedAttachmentName = encodingtoken;

            if (attachment.TransferEncoding == TransferEncoding.QuotedPrintable)
            {
                encodedAttachmentName =
                    HttpUtility.UrlEncode(displayName, Encoding.Default).Replace("+", " ").Replace("%", "=");
            }
            else
            {
                encodedAttachmentName = Convert.ToBase64String(Encoding.UTF8.GetBytes(displayName));
            }

            encodedAttachmentName = SplitEncodedAttachmentName(encodingtoken, softbreak, maxChunkLength,
                                                               encodedAttachmentName);
            attachment.Name = encodedAttachmentName;

            return(attachment);
        }
Example #26
0
        private void StartSection(string section, ContentType sectionContentType, TransferEncoding transferEncoding, LinkedResource lr)
        {
            SendData(String.Format("--{0}", section));
            SendHeader("content-type", sectionContentType.ToString());
            SendHeader("content-transfer-encoding", GetTransferEncodingName(transferEncoding));

            if (lr.ContentId != null && lr.ContentId.Length > 0)
            {
                SendHeader("content-ID", "<" + lr.ContentId + ">");
            }

            SendData(string.Empty);
        }
Example #27
0
 /// メール本文の文字列をメールの仕様に従ってエンコードします。
 /// <summary>
 /// メール本文の文字列をメールの仕様に従ってエンコードします。
 /// </summary>
 /// <param name="text"></param>
 /// <param name="encodeType"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static String EncodeToMailBody(String text, TransferEncoding encodeType, Encoding encoding)
 {
     Byte[] bb = encoding.GetBytes(text);
     if (encodeType == TransferEncoding.Base64)
     {
         return(Convert.ToBase64String(bb));
     }
     else if (encodeType == TransferEncoding.QuotedPrintable)
     {
         return(MailParser.ToQuotedPrintable(encoding.GetString(bb)));
     }
     return(encoding.GetString(bb));
 }
        /// 指定したファイルパスのファイルデータを元にデータをセットします。
        /// <summary>
        /// 指定したファイルパスのファイルデータを元にデータをセットします。
        /// </summary>
        /// <param name="filePath"></param>
        public void LoadFileData(String filePath)
        {
            FileInfo fi = null;

            fi = new FileInfo(filePath);

            this.ContentType.Value           = ContentType.GetContentType(Path.GetExtension(filePath));
            this.ContentType.Name            = fi.Name;
            this.ContentDisposition.FileName = fi.Name;
            this.ContentDisposition.Value    = "attachment";
            this.ContentTransferEncoding     = TransferEncoding.Base64;
            this.BodyData = System.IO.File.ReadAllBytes(filePath);
        }
Example #29
0
        public static string Encode(string input, TransferEncoding transferEncoding)
        {
            if (transferEncoding == TransferEncoding.QuotedPrintable)
            {
                return(Kooboo.Mail.Smtp.QuotedPrintable.Encode(input));
            }
            else if (transferEncoding == TransferEncoding.Base64)
            {
                var bytes = System.Text.Encoding.UTF8.GetBytes(input);
                return(Convert.ToBase64String(bytes));
            }

            return(input);
        }
Example #30
0
        public SerializeableLinkedResource(LinkedResource linkedResource)
        {
            ContentId        = linkedResource.ContentId;
            ContentLink      = linkedResource.ContentLink;
            ContentType      = new SerializeableContentType(linkedResource.ContentType);
            TransferEncoding = linkedResource.TransferEncoding;

            if (linkedResource.ContentStream != null)
            {
                var bytes = new byte[linkedResource.ContentStream.Length];
                linkedResource.ContentStream.Read(bytes, 0, bytes.Length);
                ContentStream = new MemoryStream(bytes);
            }
        }
		public SerializableLinkedResource(LinkedResource linkedResource)
		{
			ContentId = linkedResource.ContentId;
			ContentLink = linkedResource.ContentLink;
			ContentType = new SerializableContentType(linkedResource.ContentType);
			TransferEncoding = linkedResource.TransferEncoding;

			if (linkedResource.ContentStream != null)
			{
				var bytes = new byte[linkedResource.ContentStream.Length];
				linkedResource.ContentStream.Read(bytes, 0, bytes.Length);
				ContentStream = new MemoryStream(bytes);
			}
		}
Example #32
0
        private static string GetTransferEncodingName(TransferEncoding encoding)
        {
            switch (encoding)
            {
            case TransferEncoding.QuotedPrintable:
                return("quoted-printable");

            case TransferEncoding.SevenBit:
                return("7bit");

            case TransferEncoding.Base64:
                return("base64");
            }
            return("unknown");
        }
        //get a raw encoder, not for use with header encoding
        internal IEncodableStream GetEncoder(TransferEncoding encoding, Stream stream)
        {
            //raw encoder
            if (encoding == TransferEncoding.Base64)
                return new Base64Stream(stream, new Base64WriteStateInfo());

            //return a QuotedPrintable stream because this is not being used for header encoding
            if (encoding == TransferEncoding.QuotedPrintable)
                return new QuotedPrintableStream(stream, true);

            if (encoding == TransferEncoding.SevenBit || encoding == TransferEncoding.EightBit)
                return new EightBitStream(stream);

            throw new NotSupportedException("Encoding Stream");
        }
Example #34
0
        /// <summary>
        /// Transfer encoding to text
        /// </summary>
        /// <param name="transEncoding">Transfer encoding code</param>
        /// <returns>Transfer encoding text</returns>
        protected string TransferEncodingText(TransferEncoding transEncoding)
        {
            switch (transEncoding)
            {
            case TransferEncoding.QuotedPrintable: return("quoted-printable");

            case TransferEncoding.Base64: return("base64");

            case TransferEncoding.SevenBit: return("7bit");

            case TransferEncoding.EightBit: return("8bit");
            }

            throw new ApplicationException("Unknown transfer encoding.");
        }
 internal IEncodableStream GetEncoder(TransferEncoding encoding, Stream stream)
 {
     if (encoding == TransferEncoding.Base64)
     {
         return new Base64Stream(stream, new Base64WriteStateInfo(0x400, new byte[0], new byte[0], DefaultMaxLineLength));
     }
     if (encoding == TransferEncoding.QuotedPrintable)
     {
         return new QuotedPrintableStream(stream, true);
     }
     if (encoding != TransferEncoding.SevenBit)
     {
         throw new NotSupportedException("Encoding Stream");
     }
     return new SevenBitStream(stream);
 }
Example #36
0
        public SerializableAttachment(Attachment attachment)
        {
            ContentId = attachment.ContentId;
            ContentDisposition = new SerializableContentDisposition(attachment.ContentDisposition);
            ContentType = new SerializableContentType(attachment.ContentType);
            Name = attachment.Name;
            TransferEncoding = attachment.TransferEncoding;
            NameEncoding = attachment.NameEncoding;

            if (attachment.ContentStream != null)
            {
                byte[] bytes = new byte[attachment.ContentStream.Length];
                attachment.ContentStream.Read(bytes, 0, bytes.Length);

                ContentStream = new MemoryStream(bytes);
            }
        }
		public SerializableAlternateView(AlternateView alternativeView)
		{
			BaseUri = alternativeView.BaseUri;
			ContentId = alternativeView.ContentId;
			ContentType = new SerializableContentType(alternativeView.ContentType);
			TransferEncoding = alternativeView.TransferEncoding;

			if (alternativeView.ContentStream != null)
			{
				byte[] bytes = new byte[alternativeView.ContentStream.Length];
				alternativeView.ContentStream.Read(bytes, 0, bytes.Length);
				ContentStream = new MemoryStream(bytes);
			}

			foreach (var lr in alternativeView.LinkedResources)
				LinkedResources.Add(new SerializableLinkedResource(lr));
		}
        public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType,
            TransferEncoding transferEncoding, CultureInfo culture = null)
        {
            Contract.Requires<ArgumentNullException>(helper != null);
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType));

            var resource = helper.Get(path, culture);
            if (resource == null)
            {
                var message = string.Format("Resource [{0}] was not found.", contentId);
                throw new TemplateHelperException(message);
            }
            var linkedResource = new LinkedResource(resource, mediaType)
            {
                TransferEncoding = transferEncoding,
                ContentId = contentId
            };
            helper.AddLinkedResource(linkedResource);
            var renderedResult = new RawString(string.Format("cid:{0}", contentId));
            return renderedResult;
        }
Example #39
0
		private static string GetTransferEncodingName (TransferEncoding encoding)
		{
			switch (encoding) {
			case TransferEncoding.QuotedPrintable:
				return "quoted-printable";
			case TransferEncoding.SevenBit:
				return "7bit";
			case TransferEncoding.Base64:
				return "base64";
			}
			return "unknown";
		}
Example #40
0
        internal void SetContent(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (_streamSet)
            {
                _stream.Close();
                _stream = null;
                _streamSet = false;
            }

            _stream = stream;
            _streamSet = true;
            _streamUsedOnce = false;
            TransferEncoding = TransferEncoding.Base64;
        }
Example #41
0
        /// <summary>
        /// Returns a  string representation of <paramref name="encoding"/> compatable with the <c>micalg</c> parameter
        /// </summary>
        /// <param name="encoding">The <see cref="TransferEncoding"/> to stringify.</param>
        /// <returns>The string representation of the encoding compatable with the <c>Content-Transfer-Encoding</c> header</returns>
        public static string ToString(TransferEncoding encoding)
        {
            switch (encoding)
            {
                default:
                    throw new MimeException(MimeError.TransferEncodingNotSupported);

                case TransferEncoding.Base64:
                    return MimeStandard.TransferEncodingBase64;

                case TransferEncoding.SevenBit:
                    return MimeStandard.TransferEncoding7Bit;

                case TransferEncoding.QuotedPrintable:
                    return MimeStandard.TransferEncodingQuoted;
            }
        }
Example #42
0
        public void AddHeader(string field, string value)
        {
            switch (field.ToLowerInvariant()) {
                case "content-type": ContentType = new ContentType(value); break;
                case "transfer-encoding":
                    switch (value.ToLowerInvariant()) {
                        case "chunked":
                            TransferEncoding = TransferEncoding.Chunked;
                            break;
                    }
                    break;
                case "content-length":
                    int len;
                    if (int.TryParse(value, out len)) {
                        if (len < 0)
                            throw new HttpException("ContentLength was negative.");

                        ContentLength = len;
                    } else {
                        throw new HttpException("ContentLength was in an invalid format.");
                    }
                    break;
            }
        }
 /// <summary>
 /// Initializes a new instance of the Content class. To be used for string content.
 /// </summary>
 public Content(string content, string contentType, TransferEncoding contentTransferEncoding)
 {
     this.ContentData = content;
     this.ContentTransferEncoding = contentTransferEncoding.ToString();
     this.ContentType = contentType;
 }
Example #44
0
        private void WriteEncodedBodyText(Stream stream, String value, TransferEncoding encodeType, Encoding encoding, Int32 maxCharCount)
        {
            Stream str = stream;
            Byte[] bb = null;

            if (maxCharCount > MaxCharCountPerRow)
            { throw new ArgumentException("maxCharCount must less than MimeWriter.MaxCharCountPerRow."); }

            switch (encodeType)
            {
                case TransferEncoding.None: bb = GetAsciiBytes(value); break;
                case TransferEncoding.SevenBit: bb = GetAsciiBytes(value); break;
                case TransferEncoding.EightBit: bb = encoding.GetBytes(value); break;
                case TransferEncoding.Binary: bb = Encoding.UTF8.GetBytes(value); break;
                case TransferEncoding.Base64: bb = _Base64BodyConverter.Encode(encoding.GetBytes(value)); break;
                case TransferEncoding.QuotedPrintable: bb = _QuotedPrintableBodyConverter.Encode(encoding.GetBytes(value)); break;
                default: throw new InvalidOperationException();
            }
            stream.Write(bb);
            stream.Write(ByteData.NewLine);
        }
 /// <summary>
 /// Constructor that when given a stream, converts to encoded string based on encoding provided and saves it to content data
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="contentType"></param>
 /// <param name="encoding"></param>
 private Content(Stream stream, string contentType, TransferEncoding encoding)
 {
     this.ContentData = encoding == TransferEncoding.Base64 ? System.Convert.ToBase64String(ReadStreamAsByteArray(stream)) : ReadStreamAsString(stream);
     this.ContentType = contentType;
     this.ContentTransferEncoding = encoding.ToString();
 }
Example #46
0
        /// <summary>
        /// Instantiate a MIME part based on its body's byte array.
        /// </summary>
        /// <param name="name">Filename of the MIME part.</param>
        /// <param name="contentType">Content Type of the MIME part.</param>
        /// <param name="charset">Character Set used to encode the MIME part.</param>
        /// <param name="contentID">ID of the MIME part.</param>
        /// <param name="contentTransferEncoding">Content Transfer Encoding string of the MIME part.</param>
        /// <param name="bodyBytes">The MIME part's raw bytes.</param>
        public MimePart(string name, string contentType, string charset, string contentID, string contentTransferEncoding, byte[] bodyBytes)
        {
            BodyBytes = bodyBytes;
            ContentType = contentType;
            ContentID = contentID;
            CharSet = charset;
            Name = Functions.DecodeMailHeader(name).Replace("\r", "").Replace("\n", "");

            switch (contentTransferEncoding.ToLower())
            {
                case "base64":
                    ContentTransferEncoding = TransferEncoding.Base64;
                    break;
                case "quoted-printable":
                    ContentTransferEncoding = TransferEncoding.QuotedPrintable;
                    break;
                case "7bit":
                    ContentTransferEncoding = TransferEncoding.SevenBit;
                    break;
                case "8bit":
                    ContentTransferEncoding = TransferEncoding.EightBit;
                    break;
                default:
                    ContentTransferEncoding = TransferEncoding.Unknown;
                    break;
            }
        }
Example #47
0
		private void StartSection (string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) {
			SendData (String.Format ("--{0}", section));
			SendHeader ("content-type", sectionContentType.ToString ());
			SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
			if (contentDisposition != null)
				SendHeader ("content-disposition", contentDisposition.ToString ());
			SendData (string.Empty);
		}
Example #48
0
        internal void SetContent(Stream stream){
            if (stream == null) {
                throw new ArgumentNullException("stream");
            }
            
            if (streamSet) {
                this.stream.Close();
                this.stream = null;
                streamSet = false;
            }

            this.stream = stream;
            streamSet = true;
            streamUsedOnce = false;
            TransferEncoding = TransferEncoding.Base64;
        }
 public static string GetTransferEncodingName(TransferEncoding type)
 {
     switch (type)
     {
         case TransferEncoding.Base64:
             return "base64";
         case TransferEncoding.QuotedPrintable:
             return "quoted-printable";
         case TransferEncoding.SevenBit:
             return "7bit";
         default:
             throw new NotSupportedException(string.Format("The MIME transfer encoding '{0}' is not supported.", type));
     }
 }
Example #50
0
		private void StartSection(string section, ContentType sectionContentType, TransferEncoding transferEncoding, LinkedResource lr)
		{
			SendData (String.Format("--{0}", section));
			SendHeader ("content-type", sectionContentType.ToString ());
			SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));

			if (lr.ContentId != null && lr.ContentId.Length > 0)
				SendHeader("content-ID", "<" + lr.ContentId + ">");

			SendData (string.Empty);
		}
Example #51
0
 /// <summary>
 /// Decode the received single line using the correct decoder
 /// </summary>
 internal static string DecodeSingleLineString(string line, TransferEncoding encoding, string charSet)
 {
     switch (encoding)
     {
         case TransferEncoding.Base64:
             {
                 byte[] decodedBytes = Encoding.ASCII.GetBytes(line);
                 return DecodeBase64(new byte[][] { decodedBytes }, charSet);
             }
         case TransferEncoding.QuotedPrintable:
             {
                 byte[] decodedBytes = QuotedPrintableEncoding.DecodeSingleLine(line);
                 return DecodeBytesWithSpecificCharset(decodedBytes, charSet);
             }
         case TransferEncoding.SevenBit:
         default:
             return line;
     }
 }