/// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_MultipartParallel(MIME_h_ContentType contentType) : base(contentType) { if(!string.Equals(contentType.TypeWithSubtype,"multipart/parallel",StringComparison.CurrentCultureIgnoreCase)){ throw new ArgumentException("Argument 'contentType.TypeWithSubype' value must be 'multipart/parallel'."); } }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } // We need to buffer all body data, otherwise we don't know if we have readed all data // from stream. MemoryStream msBuffer = new MemoryStream(); Net_Utils.StreamCopy(stream,msBuffer,32000); msBuffer.Position = 0; SmartStream parseStream = new SmartStream(msBuffer,true); MIME_b_MessageDeliveryStatus retVal = new MIME_b_MessageDeliveryStatus(); //Pare per-message fields. retVal.m_pMessageFields.Parse(parseStream); // Parse per-recipient fields. while(parseStream.Position - parseStream.BytesInReadBuffer < parseStream.Length){ MIME_h_Collection recipientFields = new MIME_h_Collection(new MIME_h_Provider()); recipientFields.Parse(parseStream); retVal.m_pRecipientBlocks.Add(recipientFields); } return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } string mediaType = null; try{ mediaType = owner.ContentType.TypeWithSubtype; } catch{ mediaType = "unparsable/unparsable"; } MIME_b_Unknown retVal = new MIME_b_Unknown(mediaType); Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000); return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } MIME_b_Text retVal = null; if(owner.ContentType != null){ retVal = new MIME_b_Text(owner.ContentType.TypeWithSubtype); } else{ retVal = new MIME_b_Text(defaultContentType.TypeWithSubtype); } Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000); retVal.SetModified(false); return retVal; }
/// <summary> /// Default constructor. The protocol = 'application/x-pkcs7-signature',micalg = 'sha1' and boundary = auto-generated. /// </summary> public MIME_b_MultipartSigned() : base() { MIME_h_ContentType contentType_multipartSigned = new MIME_h_ContentType(MIME_MediaTypes.Multipart.signed); contentType_multipartSigned.Parameters["protocol"] = "application/x-pkcs7-signature"; contentType_multipartSigned.Parameters["micalg"] = "sha1"; contentType_multipartSigned.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); this.ContentType = contentType_multipartSigned; }
/// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b(MIME_h_ContentType contentType) { if(contentType == null){ throw new ArgumentNullException("contentType"); } m_pContentType = contentType; }
/// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> public MIME_b_SinglepartBase(MIME_h_ContentType contentType) : base(contentType) { if(contentType == null){ throw new ArgumentNullException("contentType"); } m_pEncodedDataStream = new MemoryStreamEx(32000); }
/// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_MultipartReport(MIME_h_ContentType contentType) : base(contentType) { if(!string.Equals(contentType.TypeWithSubtype,"multipart/report",StringComparison.CurrentCultureIgnoreCase)){ throw new ArgumentException("Argument 'contentType.TypeWithSubype' value must be 'multipart/report'."); } //if(contentType.Parameters["report-type"] == null){ // throw new ArgumentException("Argument 'contentType' does not contain required 'report-type' paramter."); //} }
/// <summary> /// Parses MIME entity body from specified stream. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="stream">Stream from where to parse entity body.</param> /// <param name="defaultContentType">Default content type.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>, <b>strean</b> or <b>defaultContentType</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public MIME_b Parse(MIME_Entity owner,SmartStream stream,MIME_h_ContentType defaultContentType) { if(owner == null){ throw new ArgumentNullException("owner"); } if(stream == null){ throw new ArgumentNullException("stream"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } string mediaType = defaultContentType.TypeWithSubype; if(owner.ContentType != null){ mediaType = owner.ContentType.TypeWithSubype; } Type bodyType = null; // We have exact body provider for specified mediaType. if(m_pBodyTypes.ContainsKey(mediaType)){ bodyType = m_pBodyTypes[mediaType]; } // Use default mediaType. else{ // Registered list of mediaTypes are available: http://www.iana.org/assignments/media-types/. string mediaRootType = mediaType.Split('/')[0].ToLowerInvariant(); if(mediaRootType == "application"){ bodyType = typeof(MIME_b_Application); } else if(mediaRootType == "audio"){ bodyType = typeof(MIME_b_Audio); } else if(mediaRootType == "image"){ bodyType = typeof(MIME_b_Image); } else if(mediaRootType == "message"){ bodyType = typeof(MIME_b_Message); } else if(mediaRootType == "multipart"){ bodyType = typeof(MIME_b_Multipart); } else if(mediaRootType == "text"){ bodyType = typeof(MIME_b_Text); } else if(mediaRootType == "video"){ bodyType = typeof(MIME_b_Video); } else{ throw new ParseException("Invalid media-type '" + mediaType + "'."); } } return (MIME_b)bodyType.GetMethod("Parse",System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy).Invoke(null,new object[]{owner,mediaType,stream}); }
/// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_Multipart(MIME_h_ContentType contentType) : base(contentType) { if(contentType == null){ throw new ArgumentNullException("contentType"); } if(string.IsNullOrEmpty(contentType.Param_Boundary)){ throw new ArgumentException("Argument 'contentType' doesn't contain required boundary parameter."); } m_pBodyParts = new MIME_EntityCollection(); }
/// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_Multipart(MIME_h_ContentType contentType) : base(contentType) { if (contentType == null) { throw new ArgumentNullException("contentType"); } if (string.IsNullOrEmpty(contentType.Param_Boundary)) { throw new ArgumentException("Argument 'contentType' doesn't contain required boundary parameter."); } m_pBodyParts = new MIME_EntityCollection(); }
/// <summary> /// Parses MIME entiry from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="defaultContentType">Default content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>defaultContentType</b> is null reference.</exception> internal void Parse(SmartStream stream, MIME_h_ContentType defaultContentType) { if (stream == null) { throw new ArgumentNullException("stream"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } m_pHeader.Parse(stream); this.Body = m_pBodyProvider.Parse(this, stream, defaultContentType); }
/// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static MIME_h_ContentType Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } // We should not have encoded words here, but some email clients do this, so encoded them if any. string valueDecoded = MIME_Encoding_EncodedWord.DecodeS(value); MIME_h_ContentType retVal = new MIME_h_ContentType(); string[] name_value = valueDecoded.Split(new char[] { ':' }, 2); if (name_value.Length != 2) { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } MIME_Reader r = new MIME_Reader(name_value[1]); string type = r.Token(); if (type == null) { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_Type = type; if (r.Char(false) != '/') { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } string subtype = r.Token(); if (subtype == null) { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_SubType = subtype; if (r.Available > 0) { retVal.m_pParameters.Parse(r); } retVal.m_ParseValue = value; retVal.m_IsModified = false; return(retVal); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } throw new NotImplementedException("Body provider class does not implement required Parse method."); }
/// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static MIME_h_ContentType Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } MIME_h_ContentType retVal = new MIME_h_ContentType(); string[] name_value = value.Split(new char[] { ':' }, 2); if (name_value.Length != 2) { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } MIME_Reader r = new MIME_Reader(name_value[1]); string type = r.Token(); if (type == null) { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_Type = type; if (r.Char(false) != '/') { retVal.m_SubType = "unknown"; //throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } else { string subtype = r.Token(); if (subtype == null) { throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_SubType = subtype; } retVal.m_pParameters.Parse(r); retVal.m_ParseValue = value; retVal.m_IsModified = false; return(retVal); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } MIME_b_ApplicationPkcs7Mime retVal = new MIME_b_ApplicationPkcs7Mime(); Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000); return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } MIME_b_MessageRfc822 retVal = new MIME_b_MessageRfc822(); retVal.m_pMessage = Mail_Message.ParseFromStream(stream); return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } throw new NotImplementedException("Body provider class does not implement required Parse method."); }
/// <summary> /// Parses MIME entiry from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="headerEncoding">Header reading encoding. If not sure UTF-8 is recommended.</param> /// <param name="defaultContentType">Default content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>,<b>headerEncoding</b> or <b>defaultContentType</b> is null reference.</exception> internal protected void Parse(SmartStream stream, Encoding headerEncoding, MIME_h_ContentType defaultContentType) { if (stream == null) { throw new ArgumentNullException("stream"); } if (headerEncoding == null) { throw new ArgumentNullException("headerEncoding"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } m_pHeader.Parse(stream, headerEncoding); m_pBody = m_pBodyProvider.Parse(this, stream, defaultContentType); m_pBody.SetParent(this, false); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } if(owner.ContentType == null || owner.ContentType.Param_Boundary == null){ throw new ParseException("Multipart entity has not required 'boundary' paramter."); } MIME_b_MultipartParallel retVal = new MIME_b_MultipartParallel(owner.ContentType); ParseInternal(owner,owner.ContentType.TypeWithSubtype,stream,retVal); return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_MessageRfc822 retVal = new MIME_b_MessageRfc822(); retVal.m_pMessage = Mail_Message.ParseFromStream(stream); return(retVal); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_ApplicationPkcs7Mime retVal = new MIME_b_ApplicationPkcs7Mime(); Net_Utils.StreamCopy(stream, retVal.EncodedStream, stream.LineBufferSize); return(retVal); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } // We need to buffer all body data, otherwise we don't know if we have readed all data // from stream. MemoryStream msBuffer = new MemoryStream(); Net_Utils.StreamCopy(stream, msBuffer, 32000); msBuffer.Position = 0; SmartStream parseStream = new SmartStream(msBuffer, true); MIME_b_MessageDeliveryStatus retVal = new MIME_b_MessageDeliveryStatus(); //Pare per-message fields. retVal.m_pMessageFields.Parse(parseStream); // Parse per-recipient fields. while (parseStream.Position - parseStream.BytesInReadBuffer < parseStream.Length) { MIME_h_Collection recipientFields = new MIME_h_Collection(new MIME_h_Provider()); recipientFields.Parse(parseStream); retVal.m_pRecipientBlocks.Add(recipientFields); } return(retVal); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } MIME_b_Application retVal = null; if(owner.ContentType != null){ retVal = new MIME_b_Application(owner.ContentType.TypeWithSubtype); } else{ retVal = new MIME_b_Application(defaultContentType.TypeWithSubtype); } Net_Utils.StreamCopy(stream,retVal.EncodedStream,stream.LineBufferSize); return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream) { if(owner == null){ throw new ArgumentNullException("owner"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } if(stream == null){ throw new ArgumentNullException("stream"); } MIME_b_Unknown retVal = null; if(owner.ContentType != null){ retVal = new MIME_b_Unknown(owner.ContentType.TypeWithSubype); } else{ retVal = new MIME_b_Unknown(defaultContentType.TypeWithSubype); } Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000); return retVal; }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_MessageDeliveryStatus retVal = new MIME_b_MessageDeliveryStatus(); //Pare per-message fields. retVal.m_pMessageFields.Parse(stream); // Parse per-recipient fields. while (true) { MIME_h_Collection recipientFields = new MIME_h_Collection(new MIME_h_Provider()); recipientFields.Parse(stream); if (recipientFields.Count == 0) { break; } else { retVal.m_pRecipientBlocks.Add(recipientFields); } } return(retVal); }
/// <summary> /// Parses MIME entiry from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="headerEncoding">Header reading encoding. If not sure UTF-8 is recommended.</param> /// <param name="defaultContentType">Default content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>,<b>headerEncoding</b> or <b>defaultContentType</b> is null reference.</exception> internal protected void Parse(SmartStream stream,Encoding headerEncoding,MIME_h_ContentType defaultContentType) { if(stream == null){ throw new ArgumentNullException("stream"); } if(headerEncoding == null){ throw new ArgumentNullException("headerEncoding"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } m_pHeader.Parse(stream,headerEncoding); m_pBody = m_pBodyProvider.Parse(this,stream,defaultContentType); m_pBody.SetParent(this,false); }
/// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static MIME_h_ContentType Parse(string value) { if(value == null){ throw new ArgumentNullException("value"); } MIME_h_ContentType retVal = new MIME_h_ContentType(); string[] name_value = value.Split(new char[]{':'},2); if(name_value.Length != 2){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } MIME_Reader r = new MIME_Reader(name_value[1]); string type = r.Token(); if(type == null){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_Type = type; if(r.Char(false) != '/'){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } string subtype = r.Token(); if(subtype == null){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_SubType = subtype; retVal.m_pParameters.Parse(r); retVal.m_ParseValue = value; retVal.m_IsModified = false; return retVal; }
/// <summary> /// Creates delivery status notifications(DSN) message. /// </summary> /// <param name="to">DSN message To.</param> /// <param name="subject">DSN message subject.</param> /// <param name="rtfText">DSN message RTF body text.</param> /// <param name="envelopeID">Envelope ID(MAIL FROM: ENVID).</param> /// <param name="arrivalDate">Message arrival date.</param> /// <param name="receivedFromMTA">The remote host EHLo name from where messages was received.</param> /// <param name="reportingMTA">Reporting MTA name.</param> /// <param name="originalRecipient">Original recipient(RCPT TO: ORCTP).</param> /// <param name="finalRecipient">Final recipient.</param> /// <param name="action">DSN action.</param> /// <param name="statusCode_text">Remote SMTP status code with text.</param> /// <param name="remoteMTA">Remote MTA what returned <b>statusCode_text</b>.</param> /// <param name="lastAttempt">Last delivery attempt.</param> /// <param name="retryUntil">Date time how long server will attempt to deliver message.</param> /// <param name="ret">Specifies what original message part are renturned.</param> /// <param name="message">Original message.</param> /// <returns>Returns created DSN message.</returns> public static Mail_Message CreateDsnMessage(string to,string subject,string rtfText,string envelopeID,DateTime arrivalDate,string receivedFromMTA,string reportingMTA,string originalRecipient,string finalRecipient,string action,string statusCode_text,string remoteMTA,DateTime lastAttempt,DateTime retryUntil,SMTP_DSN_Ret ret,Mail_Message message) { // For more info, see RFC 3464. // Ensure that all line-feeds are CRLF. rtfText = rtfText.Replace("\r\n","\n").Replace("\n","\r\n"); Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.Date = DateTime.Now; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox("Mail Delivery Subsystem","postmaster@local")); msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(null,to)); msg.Subject = subject; //--- multipart/report ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartReport = new MIME_h_ContentType(MIME_MediaTypes.Multipart.report); contentType_multipartReport.Parameters["report-type"] = "delivery-status"; contentType_multipartReport.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); MIME_b_MultipartReport multipartReport = new MIME_b_MultipartReport(contentType_multipartReport); msg.Body = multipartReport; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipart_alternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipart_alternative.Body = multipartAlternative; multipartReport.BodyParts.Add(entity_multipart_alternative); //--- text/plain --------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,SCore.RtfToText(rtfText)); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ----------------------------------------------------------------------------------------------------- MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,SCore.RtfToHtml(rtfText)); multipartAlternative.BodyParts.Add(entity_text_html); //--- message/delivery-status MIME_Entity entity_message_deliveryStatus = new MIME_Entity(); MIME_b_Message body_message_deliveryStatus = new MIME_b_Message(MIME_MediaTypes.Message.delivery_status); entity_message_deliveryStatus.Body = body_message_deliveryStatus; StringBuilder dsnText = new StringBuilder(); if(!string.IsNullOrEmpty(envelopeID)){ dsnText.Append("Original-Envelope-Id: " + envelopeID + "\r\n"); } dsnText.Append("Arrival-Date: " + MIME_Utils.DateTimeToRfc2822(arrivalDate) + "\r\n"); if(!string.IsNullOrEmpty(receivedFromMTA)){ dsnText.Append("Received-From-MTA: dns; " + receivedFromMTA + "\r\n"); } dsnText.Append("Reporting-MTA: dns; " + reportingMTA + "\r\n"); dsnText.Append("\r\n"); if(!string.IsNullOrEmpty(originalRecipient)){ dsnText.Append("Original-Recipient: " + originalRecipient + "\r\n"); } dsnText.Append("Final-Recipient: rfc822;" + finalRecipient + "" + "\r\n"); dsnText.Append("Action: " + action + "\r\n"); dsnText.Append("Status: " + statusCode_text.Substring(0,1) + ".0.0" + "\r\n"); if(!string.IsNullOrEmpty(statusCode_text)){ dsnText.Append("Diagnostic-Code: smtp; " + statusCode_text + "\r\n"); } if(!string.IsNullOrEmpty(remoteMTA)){ dsnText.Append("Remote-MTA: dns; " + remoteMTA + "\r\n"); } if(lastAttempt != DateTime.MinValue){ dsnText.Append("Last-Attempt-Date: " + MIME_Utils.DateTimeToRfc2822(lastAttempt) + "\r\n"); } if(retryUntil != DateTime.MinValue){ dsnText.Append("Will-Retry-Until: " + MIME_Utils.DateTimeToRfc2822(retryUntil) + "\r\n"); } dsnText.Append("\r\n"); body_message_deliveryStatus.SetData(new MemoryStream(Encoding.UTF8.GetBytes(dsnText.ToString())),MIME_TransferEncodings.EightBit); multipartReport.BodyParts.Add(entity_message_deliveryStatus); //--- message/rfc822 if(message != null){ MIME_Entity entity_message_rfc822 = new MIME_Entity(); MIME_b_MessageRfc822 body_message_rfc822 = new MIME_b_MessageRfc822(); entity_message_rfc822.Body = body_message_rfc822; if(ret == SMTP_DSN_Ret.FullMessage){ body_message_rfc822.Message = message; } else{ MemoryStream ms = new MemoryStream(); message.Header.ToStream(ms,null,null); ms.Position = 0; body_message_rfc822.Message = Mail_Message.ParseFromStream(ms); } multipartReport.BodyParts.Add(entity_message_rfc822); } return msg; }
/// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static MIME_h_ContentType Parse(string value) { if(value == null){ throw new ArgumentNullException("value"); } // We should not have encoded words here, but some email clients do this, so encoded them if any. string valueDecoded = MIME_Encoding_EncodedWord.DecodeS(value); MIME_h_ContentType retVal = new MIME_h_ContentType(); string[] name_value = valueDecoded.Split(new char[]{':'},2); if(name_value.Length != 2){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } MIME_Reader r = new MIME_Reader(name_value[1]); string type = r.Token(); if(type == null){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_Type = type; if(r.Char(false) != '/'){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } string subtype = r.Token(); if(subtype == null){ throw new ParseException("Invalid Content-Type: header field value '" + value + "'."); } retVal.m_SubType = subtype; if(r.Available > 0){ retVal.m_pParameters.Parse(r); } retVal.m_ParseValue = value; retVal.m_IsModified = false; return retVal; }
/// <summary> /// Parses MIME entiry from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="defaultContentType">Default content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>defaultContentType</b> is null reference.</exception> internal void Parse(SmartStream stream,MIME_h_ContentType defaultContentType) { if(stream == null){ throw new ArgumentNullException("stream"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } m_pHeader.Parse(stream); this.Body = m_pBodyProvider.Parse(this,stream,defaultContentType); }
/// <summary> /// Stores message to specified folder. /// </summary> /// <param name="accessingUser">User who accesses this method. /// User needs r permission to call this method or Exception is thrown. /// There is special user 'system' for which permission check is skipped.</param> /// <param name="folderOwnerUser">User who's folder it is.</param> /// <param name="folder">Folder where to store message. For example: Inbox,Public Folders/Documnets .</param> /// <param name="msgStream">Stream where message has stored. Stream position must be at the beginning of the message.</param> /// <param name="date">Recieve date.</param> /// <param name="flags">Message flags.</param> public void StoreMessage(string accessingUser,string folderOwnerUser,string folder,Stream msgStream,DateTime date,IMAP_MessageFlags flags) { /* Implementation notes: *) Validate values. Throw ArgumnetExcetion if invalid values. *) Ensure that user exists. *) Normalize folder. Remove '/' from folder start and end, ... . *) Do Shared Folders mapping. *) Ensure that folder exists. Throw Exception if don't. *) See if user has sufficient permissions. User requires 'p' or 'i' permission. There is builtin user system, skip ACL for it. *) Store message. */ //--- Validate values -------------------// ArgsValidator.ValidateUserName(folderOwnerUser); ArgsValidator.ValidateFolder(folder); ArgsValidator.ValidateNotNull(msgStream); //---------------------------------------// // Ensure that user exists. if(!UserExists(folderOwnerUser)){ throw new Exception("User '" + folderOwnerUser + "' doesn't exist !"); } // Normalize folder. Remove '/' from folder start and end. folder = API_Utlis.NormalizeFolder(folder); // Do Shared Folders mapping. string originalFolder = folder; SharedFolderMapInfo mappedFolder = MapSharedFolder(originalFolder); if(mappedFolder.IsSharedFolder){ folderOwnerUser = mappedFolder.FolderOnwer; folder = mappedFolder.Folder; if(folderOwnerUser == "" || folder == ""){ throw new ArgumentException("Specified root folder '" + originalFolder + "' isn't accessible !"); } } // Ensure that folder exists. Throw Exception if don't. if(!FolderExists(folderOwnerUser + "/" + folder)){ throw new Exception("Folder '" + folder + "' doesn't exist !"); } // See if user has sufficient permissions. User requires 'p' or 'i' permission. // There is builtin user system, skip ACL for it. if(accessingUser.ToLower() != "system"){ IMAP_ACL_Flags acl = GetUserACL(folderOwnerUser,folder,accessingUser); if((acl & IMAP_ACL_Flags.p) == 0 && (acl & IMAP_ACL_Flags.i) == 0){ throw new InsufficientPermissionsException("Insufficient permissions for folder '" + accessingUser + "/" + folder + "' !"); } } //--- Store message MemoryStream msgMemStream = new MemoryStream(); Net_Utils.StreamCopy(msgStream,msgMemStream,32000); byte[] messageData = msgMemStream.ToArray(); byte[] topLines = GetTopLines(new MemoryStream(messageData),50); Mail_Message message = null; try{ msgStream.Position = 0; message = Mail_Message.ParseFromByte(messageData); } catch(Exception x){ message = new Mail_Message(); message.MimeVersion = "1.0"; message.MessageID = MIME_Utils.CreateMessageID(); message.Date = DateTime.Now; message.From = new Mail_t_MailboxList(); message.From.Add(new Mail_t_Mailbox("system","system")); message.To = new Mail_t_AddressList(); message.To.Add(new Mail_t_Mailbox("system","system")); message.Subject = "[BAD MESSAGE] Bad message, message parsing failed !"; //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); message.Body = multipartMixed; //--- text/plain --------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,"NOTE: Bad message, message parsing failed.\r\n\r\n"); multipartMixed.BodyParts.Add(entity_text_plain); } byte[] envelope = System.Text.Encoding.Default.GetBytes(IMAP_Envelope.ConstructEnvelope(message)); byte[] body = System.Text.Encoding.Default.GetBytes(IMAP_BODY.ConstructBodyStructure(message,false)); using(WSqlCommand sqlCmd = new WSqlCommand(m_ConStr,"lspr_StoreMessage")){ sqlCmd.AddParameter("_userName" ,NpgsqlDbType.Varchar ,folderOwnerUser); sqlCmd.AddParameter("_folder" ,NpgsqlDbType.Varchar ,folder); sqlCmd.AddParameter("_messageID" ,NpgsqlDbType.Varchar ,Guid.NewGuid().ToString()); sqlCmd.AddParameter("_size" ,NpgsqlDbType.Integer ,messageData.Length); sqlCmd.AddParameter("_messageFlags" ,NpgsqlDbType.Integer ,(int)flags); sqlCmd.AddParameter("_date" ,NpgsqlDbType.Timestamp ,date); sqlCmd.AddParameter("_topLines" ,NpgsqlDbType.Bytea ,topLines); sqlCmd.AddParameter("_data" ,NpgsqlDbType.Bytea ,messageData); sqlCmd.AddParameter("_imapEnvelope" ,NpgsqlDbType.Bytea ,envelope); sqlCmd.AddParameter("_imapBody" ,NpgsqlDbType.Bytea ,body); DataSet ds = sqlCmd.Execute(); } }
private static void CreateBodyPart(Mail_Message msg, string BodyText) { //--- multipart/mixed ----------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; entity_text_plain.ContentTransferEncoding = MIME_TransferEncodings.Base64; //普通文本邮件内容,如果对方的收件客户端不支持HTML,这是必需的 string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容"; //if (!string.IsNullOrEmpty(SystemConfig.Default.PlaintTextTips)) //{ // plainTextBody = SystemConfig.Default.PlaintTextTips; //} text_plain.SetText(MIME_TransferEncodings.Base64, Encoding.UTF8, plainTextBody); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ----------------------------------------- string htmlText = "<html>" + BodyText.Replace("\r\n", "<br>") + "</html>"; MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, htmlText); multipartAlternative.BodyParts.Add(entity_text_html); }
private Mail_Message Create_PlainText_Html_Attachment_Image(string mailTo, string mailFrom, string mailFromDisplay) { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox(mailFromDisplay, mailFrom)); msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(mailTo, mailTo)); msg.Subject = "Test Send Mail"; //设置回执通知 //string notifyEmail = SystemConfig.Default.DispositionNotificationTo; //if (!string.IsNullOrEmpty(notifyEmail) && ValidateUtil.IsEmail(notifyEmail)) //{ // msg.DispositionNotificationTo = new Mail_t_Mailbox(notifyEmail, notifyEmail); //} #region MyRegion //--- multipart/mixed ----------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; //普通文本邮件内容,如果对方的收件客户端不支持HTML,这是必需的 string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容"; //if (!string.IsNullOrEmpty(SystemConfig.Default.PlaintTextTips)) //{ // plainTextBody = SystemConfig.Default.PlaintTextTips; //} text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, plainTextBody); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ----------------------------------------- string htmlText = "<html>这是一份测试邮件,来自<font color=red><b>厦门至正测试程序</b></font></html>"; MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, htmlText); multipartAlternative.BodyParts.Add(entity_text_html); //--- application/octet-stream ------------------------- //foreach (string attach in mailInfo.Attachments) //{ // multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(attach)); //} //foreach (string imageFile in mailInfo.EmbedImages) //{ //MIME_Entity entity_image = new MIME_Entity(); //entity_image.ContentDisposition = new MIME_h_ContentDisposition(MIME_DispositionTypes.Inline); //string fileName = "D:\\test.txt"; // DirectoryUtil.GetFileName(imageFile, true); //entity_image.ContentID = (new Guid()).ToString().Replace('-', '.'); //BytesTools.BytesToHex(Encoding.Default.GetBytes(fileName)); //MIME_b_Image body_image = new MIME_b_Image(MIME_MediaTypes.Image.jpeg); //entity_image.Body = body_image; //body_image.SetDataFromFile("D:\\test.txt", MIME_TransferEncodings.Base64); //multipartMixed.BodyParts.Add(entity_image); //} #endregion return msg; }
public void Send(ChannelMessage message) { var creds = CredentialsProvider.GetCredentials().ToNetworkCredential(); Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Subject = message.Context; msg.From = message.From.ToMailBoxList(); msg.ReplyTo = message.ReturnTo == null ? message.From.ToAddressList() : message.ReturnTo.ToAddressList(); if (String.IsNullOrEmpty(message.InReplyTo) == false) msg.InReplyTo = message.InReplyTo; msg.To = new Mail_t_AddressList(); foreach (var address in message.To) msg.To.Add(address.ToMailBox()); msg.Cc = new Mail_t_AddressList(); foreach (var address in message.CC) msg.Cc.Add(address.ToMailBox()); //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; // Add text body if there is any if (message.BodyText != null && message.BodyText.Length > 0) { var bodyText = message.BodyText.ReadString(); // Make sure there is a newline at the end of our text, otherwise it will screw up // our multipart data format if (!bodyText.EndsWith(Environment.NewLine)) bodyText = bodyText + Environment.NewLine; text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText); } multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ------------------------------------------------------------------------------------------------------ MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; if (message.BodyHtml != null && message.BodyHtml.Length > 0) { var bodyHtml = message.BodyHtml.ReadString(); // Make sure there is a newline at the end of our text, otherwise it will screw up // our multipart data format if (!bodyHtml.EndsWith(Environment.NewLine)) bodyHtml = bodyHtml + Environment.NewLine; text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml); } multipartAlternative.BodyParts.Add(entity_text_html); foreach (var channelAttachment in message.Attachments) { MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream); MIME_Entity attachment = new MIME_Entity(); attachment.Body = attachmentBody; // Has to happen before the following lines of code multipartMixed.BodyParts.Add(attachment); attachment.ContentType = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename)); attachment.ContentType.Param_Name = channelAttachment.Filename; MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment); contentDisposition.Param_FileName = channelAttachment.Filename; attachment.ContentDisposition = contentDisposition; attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString(); attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64); } // Inject headers if (!String.IsNullOrEmpty(message.MessageIdentifier)) msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier)); //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow)) // msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow)); //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference)) // mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference); //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence)) // mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence); //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation)) // mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation); //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId)) // mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId); // Send message try { SMTP_Client client = new SMTP_Client(); if ("/Settings/Channels/LoggerEnabled".AsKey(false)) client.Logger = new LumiSoft.Net.Log.Logger(); // todo push this logic into the smtp client implementation itself if (Hostname == "smtp.live.com") { // Hack for hotmail, first do a connect with no secured channel, // then a STARTTLS client.Connect(Hostname, Port, false); client.StartTLS(); } else { client.Connect(Hostname, Port, IsSecured); } client.Authenticate(creds.UserName, creds.Password); using (MemoryStream ms = new MemoryStream()) { client.MailFrom(msg.From[0].Address, -1); msg.ToStream(ms, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); // Reset stream ms.Seek(0, SeekOrigin.Begin); foreach (var address in message.To) client.RcptTo(address.Address); foreach (var address in message.CC) client.RcptTo(address.Address); foreach (var address in message.BCC) client.RcptTo(address.Address); try { client.SendMessage(ms); } finally { client.Dispose(); } } } catch(SmtpFailedRecipientsException e) { throw new ChannelFunctionalException(e.Message, e) { DoNotRetry = true }; } catch (SmtpException e) { throw new ChannelFunctionalException(e.Message, e); } catch (Exception e) { throw new ChannelFunctionalException(e.Message, e); } }
/// <summary> /// Default constructor. The boundary = auto-generated. /// </summary> public MIME_b_MultipartMixed() : base() { MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); this.ContentType = contentType_multipartMixed; }
/// <summary> /// Parses entity and it's child entities. /// </summary> internal void Parse(string text) { StringReader r = new StringReader(text); r.ReadToFirstChar(); // If starts with ( then multipart/xxx, otherwise normal single part entity if(r.StartsWith("(")){ // Entities are (entity1)(entity2)(...) <SP> ContentTypeSubType while(r.StartsWith("(")){ IMAP_BODY_Entity entity = new IMAP_BODY_Entity(); entity.Parse(r.ReadParenthesized()); entity.m_pParentEntity = this; m_pChildEntities.Add(entity); r.ReadToFirstChar(); } // Read multipart values. (nestedMimeEntries) contentTypeSubMediaType string contentTypeSubMediaType = r.ReadWord(); m_pContentType = new MIME_h_ContentType("multipart/" + contentTypeSubMediaType); } else{ // Basic fields for non-multipart // contentTypeMainMediaType contentTypeSubMediaType (conentTypeParameters) contentID contentDescription contentEncoding contentSize [envelope] [contentLine] // Content-Type string contentTypeMainMediaType = r.ReadWord(); string contentTypeSubMediaType = r.ReadWord(); if(contentTypeMainMediaType.ToUpper() != "NIL" && contentTypeSubMediaType.ToUpper() != "NIL"){ m_pContentType = new MIME_h_ContentType(contentTypeMainMediaType + "/" + contentTypeSubMediaType); } // Content-Type header field parameters // Parameters syntax: "name" <SP> "value" <SP> "name" <SP> "value" <SP> ... . r.ReadToFirstChar(); string conentTypeParameters = "NIL"; if(r.StartsWith("(")){ conentTypeParameters = r.ReadParenthesized(); StringReader contentTypeParamReader = new StringReader(conentTypeParameters); while(contentTypeParamReader.Available > 0){ string parameterName = contentTypeParamReader.ReadWord(); string parameterValue = MIME_Encoding_EncodedWord.DecodeS(contentTypeParamReader.ReadWord()); m_pContentType.Parameters[parameterName] = parameterValue; } } else{ // Skip NIL r.ReadWord(); } // Content-ID: string contentID = r.ReadWord(); if(contentID.ToUpper() != "NIL"){ m_ContentID = contentID; } // Content-Description: string contentDescription = r.ReadWord(); if(contentDescription.ToUpper() != "NIL"){ m_ContentDescription = contentDescription; } // Content-Transfer-Encoding: string contentEncoding = r.ReadWord(); if(contentEncoding.ToUpper() != "NIL"){ m_ContentEncoding = contentEncoding; } // Content Encoded data size in bytes string contentSize = r.ReadWord(); if(contentSize.ToUpper() != "NIL"){ m_ContentSize = Convert.ToInt32(contentSize); } // Only for ContentType message/rfc822 if(string.Equals(this.ContentType.TypeWithSubype,MIME_MediaTypes.Message.rfc822,StringComparison.InvariantCultureIgnoreCase)){ r.ReadToFirstChar(); // envelope if(r.StartsWith("(")){ r.ReadParenthesized(); } else{ // Skip NIL, ENVELOPE wasn't included r.ReadWord(); } // TODO: // BODYSTRUCTURE // contentLine } // Only for ContentType text/xxx if(contentTypeMainMediaType.ToLower() == "text"){ // contentLine string contentLines = r.ReadWord(); if(contentLines.ToUpper() != "NIL"){ m_ContentLines = Convert.ToInt32(contentLines); } } } }
private Mail_Message CreateMessage(string message) { Mail_Message m = new Mail_Message(); m.MimeVersion = "1.0"; m.Date = DateTime.Now; m.MessageID = MIME_Utils.CreateMessageID(); m.From = Mail_t_MailboxList.Parse(form); m.To = Mail_t_AddressList.Parse(to); m.Subject = subject; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); m.Body = multipartAlternative; //--- text/plain ---------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, message); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ------------------------------------------------------------------------------------------------------ MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, message); multipartAlternative.BodyParts.Add(entity_text_html); return m; }
/// <summary> /// Creates Mime message based on UI data. /// </summary> private Mail_Message CreateMessage() { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.From = Mail_h_MailboxList.Parse("From: " + m_pFrom.Text).Addresses; msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(m_pFolder.User.FullName,m_pFolder.User.FullName + "@localhost")); msg.Subject = m_pSubject.Text; //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,m_pText.Text); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ------------------------------------------------------------------------------------------------------ MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,RtfToHtml()); multipartAlternative.BodyParts.Add(entity_text_html); //--- application/octet-stream ----------------------------------------------------------------------------------------------- foreach(ListViewItem item in m_pAttachments.Items){ multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(item.Tag.ToString())); } return msg; }
/// <summary> /// Default constructor. The boundary = auto-generated. /// </summary> public MIME_b_MultipartAlternative() : base() { MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); this.ContentType = contentType_multipartAlternative; }
/// <summary> /// Parses MIME entity body from specified stream. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="stream">Stream from where to parse entity body.</param> /// <param name="defaultContentType">Default content type.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>, <b>strean</b> or <b>defaultContentType</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public MIME_b Parse(MIME_Entity owner, SmartStream stream, MIME_h_ContentType defaultContentType) { if (owner == null) { throw new ArgumentNullException("owner"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } string mediaType = defaultContentType.TypeWithSubtype; try { if (owner.ContentType != null) { mediaType = owner.ContentType.TypeWithSubtype; } } catch { // Do nothing, content will be MIME_b_Unknown. mediaType = "unknown/unknown"; } Type bodyType = null; // We have exact body provider for specified mediaType. if (m_pBodyTypes.ContainsKey(mediaType)) { bodyType = m_pBodyTypes[mediaType]; } // Use default mediaType. else { // Registered list of mediaTypes are available: http://www.iana.org/assignments/media-types/. string mediaRootType = mediaType.Split('/')[0].ToLowerInvariant(); if (mediaRootType == "application") { bodyType = typeof(MIME_b_Application); } else if (mediaRootType == "audio") { bodyType = typeof(MIME_b_Audio); } else if (mediaRootType == "image") { bodyType = typeof(MIME_b_Image); } else if (mediaRootType == "message") { bodyType = typeof(MIME_b_Message); } else if (mediaRootType == "multipart") { bodyType = typeof(MIME_b_Multipart); } else if (mediaRootType == "text") { bodyType = typeof(MIME_b_Text); } else if (mediaRootType == "video") { bodyType = typeof(MIME_b_Video); } else { bodyType = typeof(MIME_b_Unknown); } } return((MIME_b)System.Reflection.IntrospectionExtensions.GetTypeInfo(bodyType) .GetMethod("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy).Invoke(null, new object[] { owner, defaultContentType, stream })); }
/// <summary> /// Generates message parsing failed message. /// </summary> /// <param name="message">Message stream.</param> /// <returns>Returns message parsing failed message.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>message</b> is null reference.</exception> public static Mail_Message GenerateBadMessage(Stream message) { if(message == null){ throw new ArgumentNullException("message"); } Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox("system","system")); msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox("system","system")); msg.Subject = "[BAD MESSAGE] Bad message, message parsing failed !"; //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- text/plain --------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,"NOTE: Bad message, message parsing failed.\r\n\r\nOriginal message attached as 'data.eml'\r\n"); multipartMixed.BodyParts.Add(entity_text_plain); //--- application/octet-stream -------------------------------------------------------------------------------------- MIME_Entity entity_application_octet_stream = new MIME_Entity(); entity_application_octet_stream.ContentDisposition = new MIME_h_ContentDisposition("attachment"); entity_application_octet_stream.ContentDisposition.Param_FileName = "data.eml"; MIME_b_Application application_octet_stream = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream); entity_application_octet_stream.Body = application_octet_stream; application_octet_stream.SetData(message,"base64"); multipartMixed.BodyParts.Add(entity_application_octet_stream); return msg; }