public static MIME_Entity CreateImage(this Mail_Message xml, string file) { if (file == null) { throw new ArgumentNullException("file"); } string ext = Path.GetExtension(file); string media_type = null; if (".gif".Equals(ext, StringComparison.CurrentCultureIgnoreCase)) media_type = MIME_MediaTypes.Image.gif; else if (".jpg".Equals(ext, StringComparison.CurrentCultureIgnoreCase) || ".jpeg".Equals(ext, StringComparison.CurrentCultureIgnoreCase)) media_type = MIME_MediaTypes.Image.jpeg; else if (".tiff".Equals(ext, StringComparison.CurrentCultureIgnoreCase)) media_type = MIME_MediaTypes.Image.tiff; else throw new Exception("file extension is error"); MIME_Entity retVal = new MIME_Entity(); MIME_b_Image body = new MIME_b_Image(media_type); retVal.Body = body; body.SetDataFromFile(file, MIME_TransferEncodings.Base64); retVal.ContentType.Param_Name = Path.GetFileName(file); FileInfo fileInfo = new FileInfo(file); MIME_h_ContentDisposition disposition = new MIME_h_ContentDisposition(MIME_DispositionTypes.Attachment); disposition.Param_FileName = Path.GetFileName(file); disposition.Param_Size = fileInfo.Length; disposition.Param_CreationDate = fileInfo.CreationTime; disposition.Param_ModificationDate = fileInfo.LastWriteTime; disposition.Param_ReadDate = fileInfo.LastAccessTime; retVal.ContentDisposition = disposition; 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> /// 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> /// Sets body parent. /// </summary> /// <param name="entity">Owner entity.</param> /// <param name="setContentType">If true sets entity.ContentType header value.</param> internal virtual void SetParent(MIME_Entity entity,bool setContentType) { m_pEntity = entity; // Owner entity has no content-type or has different content-type, just add/overwrite it. if(setContentType &&(entity.ContentType == null || !string.Equals(entity.ContentType.TypeWithSubtype,this.MediaType,StringComparison.InvariantCultureIgnoreCase))){ entity.ContentType = m_pContentType; } }
/// <summary> /// Adds specified MIME enity to the collection. /// </summary> /// <param name="entity">MIME entity.</param> /// <exception cref="ArgumentNullException">Is raised when <b>entity</b> is null reference.</exception> public void Add(MIME_Entity entity) { if(entity == null){ throw new ArgumentNullException("entity"); } m_pCollection.Add(entity); m_IsModified = true; }
/// <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> /// Inserts a new MIME entity into the collection at the specified location. /// </summary> /// <param name="index">The location in the collection where you want to add the MIME entity.</param> /// <param name="entity">MIME entity.</param> /// <exception cref="IndexOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>entity</b> is null reference.</exception> public void Insert(int index,MIME_Entity entity) { if(entity == null){ throw new ArgumentNullException("entity"); } m_pCollection.Insert(index,entity); m_IsModified = true; }
/// <summary> /// Gets if the collection contains specified MIME entity. /// </summary> /// <param name="entity">MIME entity.</param> /// <returns>Returns true if the specified MIME entity exists in the collection, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>entity</b> is null.</exception> public bool Contains(MIME_Entity entity) { if(entity == null){ throw new ArgumentNullException("entity"); } return m_pCollection.Contains(entity); }
/// <summary> /// 发送阅读回折邮件 /// </summary> /// <param name="sHtmlText">邮件内容</param> /// <param name="from">发送人</param> /// <param name="to">接收人</param> public void sendReceiptMail(string sHtmlText, string subject, ASObject from, string[] to) { using (MemoryStreamEx stream = new MemoryStreamEx(32000)) { Mail_Message m = new Mail_Message(); m.MimeVersion = "1.0"; m.Date = DateTime.Now; m.MessageID = MIME_Utils.CreateMessageID(); m.Subject = subject; StringBuilder sb = new StringBuilder(); foreach (string p in to) { if (sb.Length > 0) sb.Append(","); sb.Append(p); } m.To = Mail_t_AddressList.Parse(sb.ToString()); //--- 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, sHtmlText); 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, sHtmlText); multipartAlternative.BodyParts.Add(entity_text_html); MIME_Encoding_EncodedWord headerwordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8); m.ToStream(stream, headerwordEncoder, Encoding.UTF8); stream.Position = 0; SMTP_Client.QuickSendSmartHost(null, from.getString("send_address", "stmp.sina.com"), from.getInt("send_port", 25), from.getBoolean("is_send_ssl", false), from.getString("account"), PassUtil.Decrypt(from.getString("password")), from.getString("account"), to, stream); } }
/// <summary> /// Sets MIME entity parent entity. /// </summary> /// <param name="parent">Parent entity.</param> internal void SetParent(MIME_Entity parent) { m_pParent = parent; }
/// <summary> /// Constructs specified entity and it's childentities bodystructure string. /// </summary> /// <param name="entity">Mime entity.</param> /// <param name="bodystructure">Specifies if to construct BODY or BODYSTRUCTURE.</param> /// <returns></returns> private static string ConstructParts(MIME_Entity entity,bool bodystructure) { /* RFC 3501 7.4.2 BODYSTRUCTURE BODY A form of BODYSTRUCTURE without extension data. A parenthesized list that describes the [MIME-IMB] body structure of a message. This is computed by the server by parsing the [MIME-IMB] header fields, defaulting various fields as necessary. For example, a simple text message of 48 lines and 2279 octets can have a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 2279 48) Multiple parts are indicated by parenthesis nesting. Instead of a body type as the first element of the parenthesized list, there is a sequence of one or more nested body structures. The second element of the parenthesized list is the multipart subtype (mixed, digest, parallel, alternative, etc.). For example, a two part message consisting of a text and a BASE64-encoded text attachment can have a body structure of: (("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") "<*****@*****.**>" "Compiler diff" "BASE64" 4554 73) "MIXED") Extension data follows the multipart subtype. Extension data is never returned with the BODY fetch, but can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. The extension data of a multipart body part are in the following order: body parameter parenthesized list A parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo", and "rag" is the value of "baz"] as defined in [MIME-IMB]. body disposition A parenthesized list, consisting of a disposition type string, followed by a parenthesized list of disposition attribute/value pairs as defined in [DISPOSITION]. body language A string or parenthesized list giving the body language value as defined in [LANGUAGE-TAGS]. body location A string list giving the body content URI as defined in [LOCATION]. Any following extension data are not yet defined in this version of the protocol. Such extension data can consist of zero or more NILs, strings, numbers, or potentially nested parenthesized lists of such data. Client implementations that do a BODYSTRUCTURE fetch MUST be prepared to accept such extension data. Server implementations MUST NOT send such extension data until it has been defined by a revision of this protocol. The basic fields of a non-multipart body part are in the following order: body type A string giving the content media type name as defined in [MIME-IMB]. body subtype A string giving the content subtype name as defined in [MIME-IMB]. body parameter parenthesized list A parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo" and "rag" is the value of "baz"] as defined in [MIME-IMB]. body id A string giving the content id as defined in [MIME-IMB]. body description A string giving the content description as defined in [MIME-IMB]. body encoding A string giving the content transfer encoding as defined in [MIME-IMB]. body size A number giving the size of the body in octets. Note that this size is the size in its transfer encoding and not the resulting size after any decoding. A body type of type MESSAGE and subtype RFC822 contains, immediately after the basic fields, the envelope structure, body structure, and size in text lines of the encapsulated message. A body type of type TEXT contains, immediately after the basic fields, the size of the body in text lines. Note that this size is the size in its content transfer encoding and not the resulting size after any decoding. Extension data follows the basic fields and the type-specific fields listed above. Extension data is never returned with the BODY fetch, but can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. The extension data of a non-multipart body part are in the following order: body MD5 A string giving the body MD5 value as defined in [MD5]. body disposition A parenthesized list with the same content and function as the body disposition for a multipart body part. body language A string or parenthesized list giving the body language value as defined in [LANGUAGE-TAGS]. body location A string list giving the body content URI as defined in [LOCATION]. Any following extension data are not yet defined in this version of the protocol, and would be as described above under multipart extension data. // We don't construct extention fields like rfc says: Server implementations MUST NOT send such extension data until it has been defined by a revision of this protocol. contentTypeMainMediaType - Example: 'TEXT' contentTypeSubMediaType - Example: 'PLAIN' conentTypeParameters - Example: '("CHARSET" "iso-8859-1" ...)' contentID - Content-ID: header field value. contentDescription - Content-Description: header field value. contentEncoding - Content-Transfer-Encoding: header field value. contentSize - mimeEntity ENCODED data size [envelope] - NOTE: included only if contentType = "message" !!! [contentLines] - number of ENCODED data lines. NOTE: included only if contentType = "text" !!! // Basic fields for multipart (nestedMimeEntries) contentTypeSubMediaType // Basic fields for non-multipart contentTypeMainMediaType contentTypeSubMediaType (conentTypeParameters) contentID contentDescription contentEncoding contentSize [envelope] [contentLine] */ MIME_Encoding_EncodedWord wordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B,Encoding.UTF8); wordEncoder.Split = false; StringBuilder retVal = new StringBuilder(); // Multipart message if(entity.Body is MIME_b_Multipart){ retVal.Append("("); // Construct child entities. foreach(MIME_Entity childEntity in ((MIME_b_Multipart)entity.Body).BodyParts){ // Construct child entity. This can be multipart or non multipart. retVal.Append(ConstructParts(childEntity,bodystructure)); } // Add contentTypeSubMediaType if(entity.ContentType != null && entity.ContentType.SubType != null){ retVal.Append(" \"" + entity.ContentType.SubType + "\""); } else{ retVal.Append(" NIL"); } retVal.Append(")"); } // Single part message else{ retVal.Append("("); // NOTE: all header fields and parameters must in ENCODED form !!! // Add contentTypeMainMediaType if(entity.ContentType != null && entity.ContentType.Type != null){ retVal.Append("\"" + entity.ContentType.Type + "\""); } else{ retVal.Append("NIL"); } // Add contentTypeSubMediaType if(entity.ContentType != null && entity.ContentType.SubType != null){ retVal.Append(" \"" + entity.ContentType.SubType + "\""); } else{ retVal.Append(" NIL"); } // conentTypeParameters - Syntax: {("name" SP "value" *(SP "name" SP "value"))} if(entity.ContentType != null){ if(entity.ContentType.Parameters.Count > 0){ retVal.Append(" ("); bool first = true; foreach(MIME_h_Parameter parameter in entity.ContentType.Parameters){ // For the first item, don't add SP. if(first){ first = false; } else{ retVal.Append(" "); } retVal.Append("\"" + parameter.Name + "\" \"" + wordEncoder.Encode(parameter.Value) + "\""); } retVal.Append(")"); } else{ retVal.Append(" NIL"); } } else{ retVal.Append(" NIL"); } // contentID string contentID = entity.ContentID; if(contentID != null){ retVal.Append(" \"" + wordEncoder.Encode(contentID) + "\""); } else{ retVal.Append(" NIL"); } // contentDescription string contentDescription = entity.ContentDescription; if(contentDescription != null){ retVal.Append(" \"" + wordEncoder.Encode(contentDescription) + "\""); } else{ retVal.Append(" NIL"); } // contentEncoding if(entity.ContentTransferEncoding != null){ retVal.Append(" \"" + wordEncoder.Encode(entity.ContentTransferEncoding) + "\""); } else{ // If not specified, then must be 7bit. retVal.Append(" \"7bit\""); } // contentSize if(entity.Body is MIME_b_SinglepartBase){ retVal.Append(" " + ((MIME_b_SinglepartBase)entity.Body).EncodedData.Length.ToString()); } else{ retVal.Append(" 0"); } // envelope ---> FOR ContentType: message/rfc822 ONLY ### if(entity.Body is MIME_b_MessageRfc822){ retVal.Append(" " + IMAP_Envelope.ConstructEnvelope(((MIME_b_MessageRfc822)entity.Body).Message)); // TODO: BODYSTRUCTURE,LINES } // contentLines ---> FOR ContentType: text/xxx ONLY ### if(entity.Body is MIME_b_Text){ long lineCount = 0; StreamLineReader r = new StreamLineReader(new MemoryStream(((MIME_b_SinglepartBase)entity.Body).EncodedData)); byte[] line = r.ReadLine(); while(line != null){ lineCount++; line = r.ReadLine(); } retVal.Append(" " + lineCount.ToString()); } retVal.Append(")"); } return retVal.ToString(); }
/// <summary> /// Internal body parsing. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <param name="body">Multipart body instance.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b>, <b>stream</b> or <b>body</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static void ParseInternal(MIME_Entity owner,string mediaType,SmartStream stream,MIME_b_Multipart body) { if(owner == null){ throw new ArgumentNullException("owner"); } if(mediaType == null){ throw new ArgumentNullException("mediaType"); } 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' parameter."); } if(body == null){ throw new ArgumentNullException("body"); } _MultipartReader multipartReader = new _MultipartReader(stream,owner.ContentType.Param_Boundary); while(multipartReader.Next()){ MIME_Entity entity = new MIME_Entity(); entity.Parse(new SmartStream(multipartReader,false),Encoding.UTF8,body.DefaultBodyPartContentType); body.m_pBodyParts.Add(entity); entity.SetParent(owner); } body.m_TextPreamble = multipartReader.TextPreamble; body.m_TextEpilogue = multipartReader.TextEpilogue; body.BodyParts.SetModified(false); }
/// <summary> /// Cleans up any resources being used. This method is thread-safe. /// </summary> public void Dispose() { lock(this){ if(m_IsDisposed){ return; } m_IsDisposed = true; m_pHeader = null; m_pParent = null; } }
/// <summary> /// Removes specified MIME entity from the collection. /// </summary> /// <param name="entity">MIME entity.</param> /// <exception cref="ArgumentNullException">Is raised when <b>field</b> is null reference.</exception> public void Remove(MIME_Entity entity) { if(entity == null){ throw new ArgumentNullException("field"); } m_pCollection.Remove(entity); m_IsModified = true; }
/// <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 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>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> /// Sets body parent. /// </summary> /// <param name="entity">Owner entity.</param> /// <param name="setContentType">If true sets entity.ContentType header value.</param> internal override void SetParent(MIME_Entity entity,bool setContentType) { base.SetParent(entity,setContentType); // Owner entity has no content-type or has different content-type, just add/overwrite it. if(setContentType && (this.Entity.ContentType == null || !string.Equals(this.Entity.ContentType.TypeWithSubtype,this.MediaType,StringComparison.InvariantCultureIgnoreCase))){ this.Entity.ContentType = new MIME_h_ContentType(MediaType); } }
private void updateMessage(Mail_Message m) { if (from != null) m.From = Mail_t_MailboxList.Parse(from.getString("account")); m.To = Mail_t_AddressList.Parse(txtTo.Text); if (!String.IsNullOrWhiteSpace(txtSubject.Text)) m.Subject = txtSubject.Text; if (!String.IsNullOrWhiteSpace(txtCc.Text)) m.Cc = Mail_t_AddressList.Parse(txtCc.Text.Trim()); if (Receipt.IsChecked == true) { m.DispositionNotificationTo = Mail_t_MailboxList.Parse(from.getString("account")); } if (Importance.IsChecked == true) { m.Priority = "urgent"; } string sHtmlText = htmlEditor.ContentHtml; List<string> sUrlList = getHtmlImageUrlList(sHtmlText); if (sUrlList.Count > 0 || attachments.Children.OfType<AttachmentItem>().Count() > 0) { //--- 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); m.Body = multipartMixed; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_mulipart_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_mulipart_alternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_mulipart_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, txtEditor.Text); multipartAlternative.BodyParts.Add(entity_text_plain); // Create attachment etities: --- applactation/octet-stream ------------------------- foreach (AttachmentItem item in attachments.Children.OfType<AttachmentItem>()) { multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(item.File)); } foreach (string url in sUrlList) { MIME_Entity img_entity = Mail_Message.CreateImage(url); string contentID = Guid.NewGuid().ToString().Replace("-", "$"); img_entity.ContentID = "<" + contentID + ">"; sHtmlText = sHtmlText.Replace(url, "cid:" + contentID); multipartMixed.BodyParts.Add(img_entity); } //--- 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, sHtmlText); multipartAlternative.BodyParts.Add(entity_text_html); } else { //--- 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, txtEditor.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, sHtmlText); multipartAlternative.BodyParts.Add(entity_text_html); } }
/// <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 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)bodyType.GetMethod("Parse",System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy).Invoke(null,new object[]{owner,defaultContentType,stream}); }
/// <summary> /// Creates attachment entity. /// </summary> /// <param name="file">File name with optional path.</param> /// <returns>Returns created attachment entity.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>file</b> is null reference.</exception> public static MIME_Entity CreateAttachment(string file) { if(file == null){ throw new ArgumentNullException("file"); } MIME_Entity retVal = new MIME_Entity(); MIME_b_Application body = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream); retVal.Body = body; body.SetDataFromFile(file,MIME_TransferEncodings.Base64); retVal.ContentType.Param_Name = Path.GetFileName(file); FileInfo fileInfo = new FileInfo(file); MIME_h_ContentDisposition disposition = new MIME_h_ContentDisposition(MIME_DispositionTypes.Attachment); disposition.Param_FileName = Path.GetFileName(file); disposition.Param_Size = fileInfo.Length; disposition.Param_CreationDate = fileInfo.CreationTime; disposition.Param_ModificationDate = fileInfo.LastWriteTime; disposition.Param_ReadDate = fileInfo.LastAccessTime; retVal.ContentDisposition = disposition; return retVal; }