/// <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); }
private void menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { MIME_Entity entity = (MIME_Entity)m_pTabMail_Attachments.SelectedItems[0].Tag; SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = m_pTabMail_Attachments.SelectedItems[0].Text; if (dlg.ShowDialog(this) == DialogResult.OK) { File.WriteAllBytes(dlg.FileName, ((MIME_b_SinglepartBase)entity.Body).Data); } }
/// <summary> /// Gets requested mime entity header. Returns null if specified mime entity doesn't exist. /// Note: Header terminator blank line is included. /// </summary> /// <param name="message">Mail message.</param> /// <param name="mimeEntitySpecifier">Mime entity specifier. Nested mime entities are pointed by '.'. /// For example: 1,1.1,2.1, ... .</param> /// <returns>Returns requested mime entity data or NULL if requested entry doesn't exist.</returns> public static byte[] GetMimeEntityHeader(Mail_Message message, string mimeEntitySpecifier) { MIME_Entity mEntry = GetMimeEntity(message, mimeEntitySpecifier); if (mEntry != null) { return(GetMimeEntityHeader(mEntry)); } else { return(null); } }
/// <summary> /// Gets requested mime entity data. Returns null if specified mime entity doesn't exist. /// </summary> /// <param name="message">Mail message.</param> /// <param name="mimeEntitySpecifier">Mime entity specifier. Nested mime entities are pointed by '.'. /// For example: 1,1.1,2.1, ... .</param> /// <returns>Returns requested mime entity data or NULL if requested entry doesn't exist.</returns> public static byte[] GetMimeEntityData(Mail_Message message, string mimeEntitySpecifier) { MIME_Entity entity = GetMimeEntity(message, mimeEntitySpecifier); if (entity != null) { if (entity.Body is MIME_b_SinglepartBase) { return(((MIME_b_SinglepartBase)entity.Body).EncodedData); } } return(null); }
public static byte[] PickHeaderToBytes(MIME_Entity entity, HashSet <string> fieldNames, bool includeOrExclude) { var builder = new StringBuilder(); foreach (MIME_h header in entity.Header) { if ((includeOrExclude && fieldNames.Contains(header.Name)) || (!includeOrExclude && !fieldNames.Contains(header.Name))) { builder.Append(header.ToString(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B, Encoding.UTF8), Encoding.UTF8)); } } return(Encoding.UTF8.GetBytes(builder.ToString())); }
internal Pop3Attachment(MIME_Entity origin) { this.origin = origin; if (origin != null) { if (origin.ContentDisposition == null || origin.ContentDisposition.Param_FileName == null) { fileName = origin.ContentType.Param_Name; } else { fileName = origin.ContentDisposition.Param_FileName; } } }
public static void ConstructParts(StructureBuilder builder, MIME_Entity entity, bool includeExtensions) { var wordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B, Encoding.UTF8); wordEncoder.Split = false; if (entity.Body is MIME_b_Multipart) { // Recursive build for multipart builder.StartBracket(); foreach (MIME_Entity child in ((MIME_b_Multipart)entity.Body).BodyParts) { ConstructParts(builder, child, includeExtensions); } if (entity.ContentType != null && entity.ContentType.SubType != null) { builder.SpaceNQuoted(entity.ContentType.SubType.ToUpperInvariant()); } else { builder.AppendQuoted("PLAIN"); } if (includeExtensions) { // conentTypeParameters - Syntax: {("name" SP "value" *(SP "name" SP "value"))} ConstructTypeParameters(builder, entity, wordEncoder); // body disposition Syntax: {(disposition-type [ SP ("name" SP "value" *(SP "name" SP "value"))])} ConstructBodyDisposition(builder, entity, wordEncoder); // body language builder.AppendNil(); // body location builder.AppendNil(); } builder.Append(")"); } else { ConstructSinglePart(builder, entity, wordEncoder, includeExtensions); } }
/// <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); }
public static int GetLines(MIME_Entity entity) { var count = 0; using (var memory = new MemoryStream(((MIME_b_SinglepartBase)entity.Body).EncodedData)) { using (var reader = new StreamReader(memory)) { var line = reader.ReadLine(); while (line != null) { count++; line = reader.ReadLine(); } } } return(count); }
public void CreateMultiMail(ConfigMail mail) { CreateMail(mail); var contentTypeMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentTypeMixed.Param_Boundary = Guid.NewGuid().ToString().Replace("-", "_"); var multipartMixed = new MIME_b_MultipartMixed(contentTypeMixed); Mail.Body = multipartMixed; //Create a entity to hold multipart/alternative body var entityAlternative = new MIME_Entity(); var contentTypeAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentTypeAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace("-", "_"); var multipartAlternative = new MIME_b_MultipartAlternative(contentTypeAlternative); entityAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entityAlternative); var entityTextPlain = new MIME_Entity(); var plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entityTextPlain.Body = plain; plain.SetText(MIME_TransferEncodings.Base64, Encoding.UTF8, "If you see this message, it means that your mail client does not support html."); multipartAlternative.BodyParts.Add(entityTextPlain); var entityTextHtml = new MIME_Entity(); var html = new MIME_b_Text(MIME_MediaTypes.Text.html); entityTextHtml.Body = html; html.SetText(MIME_TransferEncodings.Base64, Encoding.UTF8, mail.Body); multipartAlternative.BodyParts.Add(entityTextHtml); foreach (string attachment in mail.Attachments) { multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(attachment)); } foreach (string resource in mail.Resources) { var entity = new MIME_Entity(); entity.ContentDisposition = new MIME_h_ContentDisposition(MIME_DispositionTypes.Inline); entity.ContentID = Convert.ToBase64String(Encoding.Default.GetBytes(Path.GetFileName(resource))); //eg.<img src="cid:ContentID"/> var image = new MIME_b_Image(MIME_MediaTypes.Image.jpeg); entity.Body = image; image.SetDataFromFile(resource, MIME_TransferEncodings.Base64); multipartMixed.BodyParts.Add(entity); } }
public static void ConstructBodyDisposition(StructureBuilder builder, MIME_Entity entity, MIME_Encoding_EncodedWord wordEncoder) { if (entity.ContentDisposition != null && entity.ContentDisposition.Parameters.Count > 0) { builder.SpaceNBracket().AppendQuoted(entity.ContentDisposition.DispositionType.ToUpperInvariant()); if (entity.ContentDisposition.Parameters.Count > 0) { builder.SpaceNBracket(); bool first = true; foreach (MIME_h_Parameter parameter in entity.ContentDisposition.Parameters) { if (String.IsNullOrEmpty(parameter.Name)) { continue; } // For the first item, don't add SP. if (first) { first = false; } else { builder.Append(" "); } builder.AppendQuoted(parameter.Name.ToUpperInvariant()).SpaceNQuoted(wordEncoder.Encode(parameter.Value)); } builder.EndBracket(); } else { builder.AppendNil(); } builder.EndBracket(); } else { builder.AppendNil(); } }
public void SendEmail(Mail mail, Setting setting) { Mail_Message message = new Mail_Message() { From = new Mail_t_MailboxList(), Subject = mail.Subject, //增加主题 Priority = mail.Priority.ToString(), //设置优先级 MessageID = MIME_Utils.CreateMessageID(), Date = mail.CreatedDateTime }; //增加发件人地址 message.From.Add(new Mail_t_Mailbox(null, mail.From)); //增加收件人地址 mail.To.ForEach(address => message.To.Add(new Mail_t_Mailbox(address, address))); //增加邮件内容 MIME_Entity.CreateEntity_Text_Html("Base64", Encoding.Default, mail.Body); //增加附件 if (mail.Attachments != null && mail.Attachments.Count > 0) { mail.Attachments.ForEach(attachment => { MIME_Entity.CreateEntity_Attachment(attachment.Name); }); } using (SMTP_Client smtpClient = new SMTP_Client()) { //设置SMPT服务地址和端口并连接 smtpClient.Connect(setting.SmtpHostName, setting.SmtpPort); //设置Authentication smtpClient.Auth(new LumiSoft.Net.AUTH.AUTH_SASL_Client_Login(setting.User.UserName, setting.User.Password)); using (MemoryStream stream = new MemoryStream()) { message.ToStream(stream); stream.Position = 0; //发送邮件 smtpClient.SendMessage(stream); } } }
private Mail_Message CreateMessage() { Mail_Message mail_Message = new Mail_Message(); mail_Message.MimeVersion = "1.0"; mail_Message.MessageID = MIME_Utils.CreateMessageID(); mail_Message.Date = DateTime.Now; mail_Message.From = Mail_h_MailboxList.Parse("From: " + this.m_pFrom.Text).Addresses; mail_Message.To = new Mail_t_AddressList(); mail_Message.To.Add(new Mail_t_Mailbox(this.m_pFolder.User.FullName, this.m_pFolder.User.FullName + "@localhost")); mail_Message.Subject = this.m_pSubject.Text; MIME_b_MultipartMixed mIME_b_MultipartMixed = new MIME_b_MultipartMixed(new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') }); mail_Message.Body = mIME_b_MultipartMixed; MIME_Entity mIME_Entity = new MIME_Entity(); MIME_b_MultipartAlternative mIME_b_MultipartAlternative = new MIME_b_MultipartAlternative(new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') }); mIME_Entity.Body = mIME_b_MultipartAlternative; mIME_b_MultipartMixed.BodyParts.Add(mIME_Entity); MIME_Entity mIME_Entity2 = new MIME_Entity(); MIME_b_Text mIME_b_Text = new MIME_b_Text(MIME_MediaTypes.Text.plain); mIME_Entity2.Body = mIME_b_Text; mIME_b_Text.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, this.m_pText.Text); mIME_b_MultipartAlternative.BodyParts.Add(mIME_Entity2); MIME_Entity mIME_Entity3 = new MIME_Entity(); MIME_b_Text mIME_b_Text2 = new MIME_b_Text(MIME_MediaTypes.Text.html); mIME_Entity3.Body = mIME_b_Text2; mIME_b_Text2.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, this.RtfToHtml()); mIME_b_MultipartAlternative.BodyParts.Add(mIME_Entity3); foreach (ListViewItem listViewItem in this.m_pAttachments.Items) { mIME_b_MultipartMixed.BodyParts.Add(MIME_Message.CreateAttachment(listViewItem.Tag.ToString())); } return(mail_Message); }
private static RequestFileInfo GetAsAttachment(MIME_Entity entity) { var attachment = new RequestFileInfo { Body = ((MIME_b_SinglepartBase)entity.Body).Data }; if (!string.IsNullOrEmpty(entity.ContentDisposition.Param_FileName)) { attachment.Name = entity.ContentDisposition.Param_FileName; } else if (!string.IsNullOrEmpty(entity.ContentType.Param_Name)) { attachment.Name = entity.ContentType.Param_Name; } attachment.ContentType = MimeMapping.GetMimeMapping(attachment.Name); return(attachment); }
public static Mail_Message GenerateBadMessage(Stream message) { if (message == null) { throw new ArgumentNullException("message"); } Mail_Message mail_Message = new Mail_Message(); mail_Message.MimeVersion = "1.0"; mail_Message.MessageID = MIME_Utils.CreateMessageID(); mail_Message.Date = DateTime.Now; mail_Message.From = new Mail_t_MailboxList(); mail_Message.From.Add(new Mail_t_Mailbox("system", "system")); mail_Message.To = new Mail_t_AddressList(); mail_Message.To.Add(new Mail_t_Mailbox("system", "system")); mail_Message.Subject = "[BAD MESSAGE] Bad message, message parsing failed !"; MIME_b_MultipartMixed mIME_b_MultipartMixed = new MIME_b_MultipartMixed(new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') }); mail_Message.Body = mIME_b_MultipartMixed; MIME_Entity mIME_Entity = new MIME_Entity(); MIME_b_Text mIME_b_Text = new MIME_b_Text(MIME_MediaTypes.Text.plain); mIME_Entity.Body = mIME_b_Text; mIME_b_Text.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, "NOTE: Bad message, message parsing failed.\r\n\r\nOriginal message attached as 'data.eml'\r\n"); mIME_b_MultipartMixed.BodyParts.Add(mIME_Entity); MIME_Entity mIME_Entity2 = new MIME_Entity(); mIME_Entity2.ContentDisposition = new MIME_h_ContentDisposition("attachment"); mIME_Entity2.ContentDisposition.Param_FileName = "data.eml"; MIME_b_Application mIME_b_Application = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream); mIME_Entity2.Body = mIME_b_Application; mIME_b_Application.SetData(message, "base64"); mIME_b_MultipartMixed.BodyParts.Add(mIME_Entity2); return(mail_Message); }
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); }
private static bool CheckNFixEntity(MIME_Entity entity) { var result = false; if (entity.ContentType != null && !String.IsNullOrEmpty(entity.ContentType.Param_Boundary) && entity.ContentType.Param_Boundary.Length > 80) { result = true; entity.ContentType.Param_Boundary = Guid.NewGuid().ToString().ToLower(); } var multipart = entity.Body as MIME_b_Multipart; if (multipart != null) { foreach (MIME_Entity each in multipart.BodyParts) { result |= CheckNFixEntity(each); } } return(result); }
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) { rtfText = rtfText.Replace("\r\n", "\n").Replace("\n", "\r\n"); Mail_Message mail_Message = new Mail_Message(); mail_Message.MimeVersion = "1.0"; mail_Message.Date = DateTime.Now; mail_Message.From = new Mail_t_MailboxList(); mail_Message.From.Add(new Mail_t_Mailbox("Mail Delivery Subsystem", "postmaster@local")); mail_Message.To = new Mail_t_AddressList(); mail_Message.To.Add(new Mail_t_Mailbox(null, to)); mail_Message.Subject = subject; MIME_h_ContentType mIME_h_ContentType = new MIME_h_ContentType(MIME_MediaTypes.Multipart.report); mIME_h_ContentType.Parameters["report-type"] = "delivery-status"; mIME_h_ContentType.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartReport mIME_b_MultipartReport = new MIME_b_MultipartReport(mIME_h_ContentType); mail_Message.Body = mIME_b_MultipartReport; MIME_Entity mIME_Entity = new MIME_Entity(); MIME_b_MultipartAlternative mIME_b_MultipartAlternative = new MIME_b_MultipartAlternative(new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') }); mIME_Entity.Body = mIME_b_MultipartAlternative; mIME_b_MultipartReport.BodyParts.Add(mIME_Entity); MIME_Entity mIME_Entity2 = new MIME_Entity(); MIME_b_Text mIME_b_Text = new MIME_b_Text(MIME_MediaTypes.Text.plain); mIME_Entity2.Body = mIME_b_Text; mIME_b_Text.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToText(rtfText)); mIME_b_MultipartAlternative.BodyParts.Add(mIME_Entity2); MIME_Entity mIME_Entity3 = new MIME_Entity(); MIME_b_Text mIME_b_Text2 = new MIME_b_Text(MIME_MediaTypes.Text.html); mIME_Entity3.Body = mIME_b_Text2; mIME_b_Text2.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToHtml(rtfText)); mIME_b_MultipartAlternative.BodyParts.Add(mIME_Entity3); MIME_Entity mIME_Entity4 = new MIME_Entity(); MIME_b_Message mIME_b_Message = new MIME_b_Message(MIME_MediaTypes.Message.delivery_status); mIME_Entity4.Body = mIME_b_Message; StringBuilder stringBuilder = new StringBuilder(); if (!string.IsNullOrEmpty(envelopeID)) { stringBuilder.Append("Original-Envelope-Id: " + envelopeID + "\r\n"); } stringBuilder.Append("Arrival-Date: " + MIME_Utils.DateTimeToRfc2822(arrivalDate) + "\r\n"); if (!string.IsNullOrEmpty(receivedFromMTA)) { stringBuilder.Append("Received-From-MTA: dns; " + receivedFromMTA + "\r\n"); } stringBuilder.Append("Reporting-MTA: dns; " + reportingMTA + "\r\n"); stringBuilder.Append("\r\n"); if (!string.IsNullOrEmpty(originalRecipient)) { stringBuilder.Append("Original-Recipient: " + originalRecipient + "\r\n"); } stringBuilder.Append("Final-Recipient: rfc822;" + finalRecipient + "\r\n"); stringBuilder.Append("Action: " + action + "\r\n"); stringBuilder.Append("Status: " + statusCode_text.Substring(0, 1) + ".0.0\r\n"); if (!string.IsNullOrEmpty(statusCode_text)) { stringBuilder.Append("Diagnostic-Code: smtp; " + statusCode_text + "\r\n"); } if (!string.IsNullOrEmpty(remoteMTA)) { stringBuilder.Append("Remote-MTA: dns; " + remoteMTA + "\r\n"); } if (lastAttempt != DateTime.MinValue) { stringBuilder.Append("Last-Attempt-Date: " + MIME_Utils.DateTimeToRfc2822(lastAttempt) + "\r\n"); } if (retryUntil != DateTime.MinValue) { stringBuilder.Append("Will-Retry-Until: " + MIME_Utils.DateTimeToRfc2822(retryUntil) + "\r\n"); } stringBuilder.Append("\r\n"); mIME_b_Message.SetData(new MemoryStream(Encoding.UTF8.GetBytes(stringBuilder.ToString())), MIME_TransferEncodings.EightBit); mIME_b_MultipartReport.BodyParts.Add(mIME_Entity4); if (message != null) { MIME_Entity mIME_Entity5 = new MIME_Entity(); MIME_b_MessageRfc822 mIME_b_MessageRfc = new MIME_b_MessageRfc822(); mIME_Entity5.Body = mIME_b_MessageRfc; if (ret == SMTP_DSN_Ret.FullMessage) { mIME_b_MessageRfc.Message = message; } else { MemoryStream memoryStream = new MemoryStream(); message.Header.ToStream(memoryStream, null, null); memoryStream.Position = 0L; mIME_b_MessageRfc.Message = Mail_Message.ParseFromStream(memoryStream); } mIME_b_MultipartReport.BodyParts.Add(mIME_Entity5); } return(mail_Message); }
/// <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()); }
string ConvertImageToBase64(MIME_Entity image) { return(String.Format("data:{0};base64,{1}", image.ContentType.TypeWithSubtype, Convert.ToBase64String((image.Body as MIME_b_Image).Data))); }
private static string ConstructParts(MIME_Entity entity, bool bodystructure) { MIME_Encoding_EncodedWord mIME_Encoding_EncodedWord = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B, Encoding.UTF8); mIME_Encoding_EncodedWord.Split = false; StringBuilder stringBuilder = new StringBuilder(); if (entity.Body is MIME_b_Multipart) { stringBuilder.Append("("); foreach (MIME_Entity entity2 in ((MIME_b_Multipart)entity.Body).BodyParts) { stringBuilder.Append(IMAP_BODY.ConstructParts(entity2, bodystructure)); } if (entity.ContentType != null && entity.ContentType.SubType != null) { stringBuilder.Append(" \"" + entity.ContentType.SubType + "\""); } else { stringBuilder.Append(" NIL"); } stringBuilder.Append(")"); } else { stringBuilder.Append("("); if (entity.ContentType != null && entity.ContentType.Type != null) { stringBuilder.Append("\"" + entity.ContentType.Type + "\""); } else { stringBuilder.Append("NIL"); } if (entity.ContentType != null && entity.ContentType.SubType != null) { stringBuilder.Append(" \"" + entity.ContentType.SubType + "\""); } else { stringBuilder.Append(" NIL"); } if (entity.ContentType != null) { if (entity.ContentType.Parameters.Count > 0) { stringBuilder.Append(" ("); bool flag = true; foreach (MIME_h_Parameter mIME_h_Parameter in entity.ContentType.Parameters) { if (flag) { flag = false; } else { stringBuilder.Append(" "); } stringBuilder.Append(string.Concat(new string[] { "\"", mIME_h_Parameter.Name, "\" \"", mIME_Encoding_EncodedWord.Encode(mIME_h_Parameter.Value), "\"" })); } stringBuilder.Append(")"); } else { stringBuilder.Append(" NIL"); } } else { stringBuilder.Append(" NIL"); } string contentID = entity.ContentID; if (contentID != null) { stringBuilder.Append(" \"" + mIME_Encoding_EncodedWord.Encode(contentID) + "\""); } else { stringBuilder.Append(" NIL"); } string contentDescription = entity.ContentDescription; if (contentDescription != null) { stringBuilder.Append(" \"" + mIME_Encoding_EncodedWord.Encode(contentDescription) + "\""); } else { stringBuilder.Append(" NIL"); } if (entity.ContentTransferEncoding != null) { stringBuilder.Append(" \"" + mIME_Encoding_EncodedWord.Encode(entity.ContentTransferEncoding) + "\""); } else { stringBuilder.Append(" \"7bit\""); } if (entity.Body is MIME_b_SinglepartBase) { stringBuilder.Append(" " + ((MIME_b_SinglepartBase)entity.Body).EncodedData.Length.ToString()); } else { stringBuilder.Append(" 0"); } if (entity.Body is MIME_b_MessageRfc822) { stringBuilder.Append(" " + IMAP_Envelope.ConstructEnvelope(((MIME_b_MessageRfc822)entity.Body).Message)); } if (entity.Body is MIME_b_Text) { long num = 0L; StreamLineReader streamLineReader = new StreamLineReader(new MemoryStream(((MIME_b_SinglepartBase)entity.Body).EncodedData)); for (byte[] array = streamLineReader.ReadLine(); array != null; array = streamLineReader.ReadLine()) { num += 1L; } stringBuilder.Append(" " + num.ToString()); } stringBuilder.Append(")"); } return(stringBuilder.ToString()); }
public static Mail_Message Create_PlainText_Html_Attachment_Image(Dictionary <string, string> tomails, Dictionary <string, string> ccmails, string mailFrom, string mailFromDisplay, string subject, string body, Dictionary <string, string> attachments, string notifyEmail = "", string plaintTextTips = "") { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.Subject = subject; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox(mailFromDisplay, mailFrom)); msg.To = new Mail_t_AddressList(); foreach (string address in tomails.Keys) { string displayName = tomails[address]; msg.To.Add(new Mail_t_Mailbox(displayName, address)); } msg.Cc = new Mail_t_AddressList(); foreach (string address in ccmails.Keys) { string displayName = ccmails[address]; msg.Cc.Add(new Mail_t_Mailbox(displayName, address)); } //设置回执通知 if (!string.IsNullOrEmpty(notifyEmail) && IsEmail(notifyEmail)) { msg.DispositionNotificationTo.Add(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(plaintTextTips)) { plainTextBody = plaintTextTips; } text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, plainTextBody); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ----------------------------------------- string htmlText = body;//"<html>这是一份测试邮件,<img src=\"cid:test.jpg\">来自<font color=red><b>LumiSoft.Net</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 ------------------------- WebClient client = new WebClient(); foreach (string attach in attachments.Keys) { try { byte[] bytes = client.DownloadData(attachments[attach]); using (MemoryStream stream = new MemoryStream(bytes)) { multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(stream, attach)); } } catch (Exception ex) { throw ex; } } #endregion return(msg); }
private Mail_Message Create_PlainText_Html_Attachment_Image(Dictionary <string, string> tomails, Dictionary <string, string> ccmails, string mailFrom, string mailFromDisplay, string subject, string body, Dictionary <string, string> attachments, string notifyEmail = "", string plaintTextTips = "", bool checkspmail = false) { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.Subject = subject; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox(mailFromDisplay, mailFrom)); msg.To = new Mail_t_AddressList(); foreach (string address in tomails.Keys) { string displayName = tomails[address]; msg.To.Add(new Mail_t_Mailbox(displayName, address)); } msg.Cc = new Mail_t_AddressList(); foreach (string address in ccmails.Keys) { string displayName = ccmails[address]; msg.Cc.Add(new Mail_t_Mailbox(displayName, address)); } if (!string.IsNullOrEmpty(notifyEmail)) { msg.DispositionNotificationTo.Add(new Mail_t_Mailbox(notifyEmail, notifyEmail)); } #region MyRegion 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; 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); 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; string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容"; if (!string.IsNullOrEmpty(plaintTextTips)) { plainTextBody = plaintTextTips; } text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, plainTextBody); multipartAlternative.BodyParts.Add(entity_text_plain); string htmlText = body; 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); var i = 1; foreach (string attach in attachments.Keys) { string filename = string.Empty; FileInfo fino = new FileInfo(attach); if (mAttRename) { filename = mAttachmentName + i.ToString() + fino.Extension; } else { if (!string.IsNullOrEmpty(attachments[attach])) { filename = attachments[attach]; } else { filename = fino.Name; } } if (filename.Length > 30) { FileInfo aainfo = new FileInfo(filename); filename = filename.Substring(0, 15) + "_略" + aainfo.Extension; } filename = MimeUtils.EncodeWord(filename); using (var fs = File.OpenRead(attach)) { var ate = Mail_Message.CreateAttachment(fs, filename); multipartAlternative.BodyParts.Add(ate); fs.Close(); } } #endregion return(msg); }
/// <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); }
public static void ConstructSinglePart(StructureBuilder builder, MIME_Entity entity, MIME_Encoding_EncodedWord wordEncoder, bool includeExtensions) { builder.Append("("); // NOTE: all header fields and parameters must in ENCODED form !!! // Add contentTypeMainMediaType if (entity.ContentType != null && entity.ContentType.Type != null) { builder.AppendQuoted(entity.ContentType.Type.ToUpperInvariant()); } else { builder.AppendQuoted("TEXT"); } // Add contentTypeSubMediaType if (entity.ContentType != null && entity.ContentType.SubType != null) { builder.SpaceNQuoted(entity.ContentType.SubType.ToUpperInvariant()); } else { builder.SpaceNQuoted("PLAIN"); } // conentTypeParameters - Syntax: {("name" SP "value" *(SP "name" SP "value"))} ConstructTypeParameters(builder, entity, wordEncoder); // contentID string contentID = entity.ContentID; if (contentID != null) { builder.SpaceNQuoted(wordEncoder.Encode(contentID)); } else { builder.AppendNil(); } // contentDescription string contentDescription = entity.ContentDescription; if (contentDescription != null) { builder.SpaceNQuoted(wordEncoder.Encode(contentDescription)); } else { builder.AppendNil(); } // contentEncoding if (entity.ContentTransferEncoding != null) { builder.SpaceNQuoted(entity.ContentTransferEncoding.ToUpperInvariant()); } else { // If not specified, then must be 7bit. builder.SpaceNQuoted("7bit"); } // contentSize if (entity.Body is MIME_b_SinglepartBase) { builder.Append(" ").Append(((MIME_b_SinglepartBase)entity.Body).EncodedData.Length.ToString()); } else { builder.Append(" 0"); } // envelope --->FOR ContentType: message / rfc822 ONLY ### if (entity.Body is MIME_b_MessageRfc822) { builder.Append(" "); ENVELOPE.ConstructEnvelope(builder, ((MIME_b_MessageRfc822)entity.Body).Message); // BODYSTRUCTURE builder.AppendNil(); // LINES builder.AppendNil(); } // contentLines ---> FOR ContentType: text/xxx ONLY ### if (entity.Body is MIME_b_Text) { builder.Append(" ").Append(GetLines(entity).ToString()); } #region BODYSTRUCTURE extention fields if (includeExtensions) { // body MD5 builder.AppendNil(); // body disposition Syntax: {(disposition-type [ SP ("name" SP "value" *(SP "name" SP "value"))])} ConstructBodyDisposition(builder, entity, wordEncoder); // body language builder.AppendNil(); // body location builder.AppendNil(); } #endregion builder.EndBracket(); }
/// <summary> /// Gets specified mime entity header. /// Note: Header terminator blank line is included. /// </summary> /// <param name="entity">Mime entity.</param> /// <returns></returns> public static byte[] GetMimeEntityHeader(MIME_Entity entity) { return(System.Text.Encoding.ASCII.GetBytes(entity.Header.ToString() + "\r\n")); }
/// <summary> /// Returns requested header fields lines. /// Note: Header terminator blank line is included. /// </summary> /// <param name="fieldsStr">Header fields to get.</param> /// <param name="entity">Entity which header field lines to get.</param> /// <returns></returns> public static byte[] ParseHeaderFields(string fieldsStr, MIME_Entity entity) { return(ParseHeaderFields(fieldsStr, System.Text.Encoding.Default.GetBytes(entity.Header.ToString()))); }
/// <summary> /// Gets specified mime entity. Returns null if specified mime entity doesn't exist. /// </summary> /// <param name="message">Mail message.</param> /// <param name="mimeEntitySpecifier">Mime entity specifier. Nested mime entities are pointed by '.'. /// For example: 1,1.1,2.1, ... .</param> /// <returns></returns> public static MIME_Entity GetMimeEntity(Mail_Message message, string mimeEntitySpecifier) { // TODO: nested rfc 822 message // For single part message there is only one entity with value 1. // Example: // header // entity -> 1 // For multipart message, entity counting starts from MainEntity.ChildEntities // Example: // header // multipart/mixed // text/plain -> 1 // application/pdf -> 2 // ... // Single part if (message.ContentType == null || message.ContentType.Type.ToLower() != "multipart") { if (Convert.ToInt32(mimeEntitySpecifier) == 1) { return(message); } else { return(null); } } // multipart else { /* * MIME_Entity currentEntity = message; * * string[] parts = mimeEntitySpecifier.Split('.'); * for(int i=0;i<parts.Length;i++){ * int partSpecifier = Convert.ToInt32(parts[i]) - 1; // Enitites are zero base, mimeEntitySpecifier is 1 based. * * currentEntity * * // Last mime part. * if(i == (parts.Length - 1)){ * } * // Not a last mime part. * else{ * } * }*/ MIME_Entity entity = message; string[] parts = mimeEntitySpecifier.Split('.'); foreach (string part in parts) { int mEntryNo = Convert.ToInt32(part) - 1; // Enitites are zero base, mimeEntitySpecifier is 1 based. if (entity.Body is MIME_b_Multipart) { MIME_b_Multipart multipart = (MIME_b_Multipart)entity.Body; if (mEntryNo > -1 && mEntryNo < multipart.BodyParts.Count) { entity = multipart.BodyParts[mEntryNo]; } else { return(null); } } else { return(null); } } return(entity); } }
private static Mail_Message Create_PlainText_Html_Attachment_Image(string tomail, string mailFrom, string mailFromDisplay, string subject, string body) { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.Subject = subject; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox("绘学霸", mailFrom)); msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(tomail, tomail)); //设置回执通知 string notifyEmail = "*****@*****.**"; if (!string.IsNullOrEmpty(notifyEmail)) { msg.DispositionNotificationTo = new Mail_t_MailboxList(); msg.DispositionNotificationTo.Add(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(plaintTextTips)) * { * plainTextBody = "回执信息"; * } */ text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, plainTextBody); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ----------------------------------------- string htmlText = body; 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); #endregion return(msg); }
private bool Match(bool syntaxCheckOnly, System.NetworkToolkit.StringReader r, string mailFrom, string[] rcptTo, SMTP_Session smtpSession, Mail_Message mime, int messageSize) { GlobalMessageRuleProcessor.PossibleClauseItem possibleClauseItem = (GlobalMessageRuleProcessor.PossibleClauseItem) 56; bool flag = false; r.ReadToFirstChar(); if (r.Available == 0L) { throw new Exception("Invalid syntax: '" + this.ClauseItemsToString(possibleClauseItem) + "' expected !"); } while (r.Available > 0L) { r.ReadToFirstChar(); if (syntaxCheckOnly) { flag = true; } if (r.StartsWith("(")) { flag = this.Match(syntaxCheckOnly, new System.NetworkToolkit.StringReader(r.ReadParenthesized()), mailFrom, rcptTo, smtpSession, mime, messageSize); possibleClauseItem = (GlobalMessageRuleProcessor.PossibleClauseItem) 56; } else if (r.StartsWith("and", false)) { if ((possibleClauseItem & GlobalMessageRuleProcessor.PossibleClauseItem.AND) == (GlobalMessageRuleProcessor.PossibleClauseItem) 0) { throw new Exception("Invalid syntax: '" + this.ClauseItemsToString(possibleClauseItem) + "' expected !"); } if (!flag) { return(false); } r.ReadWord(); r.ReadToFirstChar(); flag = this.Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize); possibleClauseItem = (GlobalMessageRuleProcessor.PossibleClauseItem) 56; } else if (r.StartsWith("or", false)) { if ((possibleClauseItem & GlobalMessageRuleProcessor.PossibleClauseItem.OR) == (GlobalMessageRuleProcessor.PossibleClauseItem) 0) { throw new Exception("Invalid syntax: '" + this.ClauseItemsToString(possibleClauseItem) + "' expected !"); } r.ReadWord(); r.ReadToFirstChar(); if (flag) { this.Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize); } else { flag = this.Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize); } possibleClauseItem = (GlobalMessageRuleProcessor.PossibleClauseItem) 56; } else if (r.StartsWith("not", false)) { if ((possibleClauseItem & GlobalMessageRuleProcessor.PossibleClauseItem.NOT) == (GlobalMessageRuleProcessor.PossibleClauseItem) 0) { throw new Exception("Invalid syntax: '" + this.ClauseItemsToString(possibleClauseItem) + "' expected !"); } r.ReadWord(); r.ReadToFirstChar(); flag = !this.Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize); possibleClauseItem = (GlobalMessageRuleProcessor.PossibleClauseItem) 48; } else { if ((possibleClauseItem & GlobalMessageRuleProcessor.PossibleClauseItem.Matcher) == (GlobalMessageRuleProcessor.PossibleClauseItem) 0) { throw new Exception(string.Concat(new string[] { "Invalid syntax: '", this.ClauseItemsToString(possibleClauseItem), "' expected ! \r\n\r\n Near: '", r.OriginalString.Substring(0, r.Position), "'" })); } string text = r.ReadWord(); if (text == null) { throw new Exception("Invalid syntax: matcher is missing !"); } text = text.ToLower(); string[] array = new string[0]; if (text == "smtp.mail_from") { if (!syntaxCheckOnly) { array = new string[] { mailFrom }; } } else if (text == "smtp.rcpt_to") { if (!syntaxCheckOnly) { array = rcptTo; } } else if (text == "smtp.ehlo") { if (!syntaxCheckOnly) { array = new string[] { smtpSession.EhloHost }; } } else if (text == "smtp.authenticated") { if (!syntaxCheckOnly && smtpSession != null) { array = new string[] { smtpSession.IsAuthenticated.ToString() }; } } else if (text == "smtp.user") { if (!syntaxCheckOnly && smtpSession != null && smtpSession.AuthenticatedUserIdentity != null) { array = new string[] { smtpSession.AuthenticatedUserIdentity.Name }; } } else if (text == "smtp.remote_ip") { if (!syntaxCheckOnly && smtpSession != null) { array = new string[] { smtpSession.RemoteEndPoint.Address.ToString() }; } } else if (text == "message.size") { if (!syntaxCheckOnly) { array = new string[] { messageSize.ToString() }; } } else if (text == "message.header") { string text2 = r.ReadWord(); if (text2 == null) { throw new Exception("Match source MainHeaderField HeaderFieldName is missing ! Syntax:{MainHeaderField <SP> \"HeaderFieldName:\"}"); } if (!syntaxCheckOnly && mime.Header.Contains(text2)) { MIME_h[] array2 = mime.Header[text2]; array = new string[array2.Length]; for (int i = 0; i < array.Length; i++) { array[i] = array2[i].ValueToString(); } } } else if (text == "message.all_headers") { string text3 = r.ReadWord(); if (text3 == null) { throw new Exception("Match source MainHeaderField HeaderFieldName is missing ! Syntax:{MainHeaderField <SP> \"HeaderFieldName:\"}"); } if (!syntaxCheckOnly) { List <string> list = new List <string>(); MIME_Entity[] allEntities = mime.AllEntities; for (int j = 0; j < allEntities.Length; j++) { MIME_Entity mIME_Entity = allEntities[j]; if (mIME_Entity.Header.Contains(text3)) { MIME_h[] array3 = mIME_Entity.Header[text3]; for (int k = 0; k < array3.Length; k++) { list.Add(array3[k].ValueToString()); } } } array = list.ToArray(); } } else if (text == "message.body_text") { if (!syntaxCheckOnly) { array = new string[] { mime.BodyText }; } } else if (text == "message.body_html") { if (!syntaxCheckOnly) { array = new string[] { mime.BodyHtmlText }; } } else if (text == "message.content_md5") { if (!syntaxCheckOnly) { List <string> list2 = new List <string>(); MIME_Entity[] allEntities2 = mime.AllEntities; for (int l = 0; l < allEntities2.Length; l++) { MIME_Entity mIME_Entity2 = allEntities2[l]; try { if (mIME_Entity2.Body is MIME_b_SinglepartBase) { byte[] data = ((MIME_b_SinglepartBase)mIME_Entity2.Body).Data; if (data != null) { MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider(); list2.Add(Encoding.UTF8.GetString(mD5CryptoServiceProvider.ComputeHash(data))); } } } catch { } } array = list2.ToArray(); } } else if (text == "sys.date_time") { if (!syntaxCheckOnly) { array = new string[] { DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") }; } } else if (text == "sys.date") { if (!syntaxCheckOnly) { array = new string[] { DateTime.Today.ToString("dd.MM.yyyy") }; } } else if (text == "sys.time") { if (!syntaxCheckOnly) { array = new string[] { DateTime.Now.ToString("HH:mm:ss") }; } } else if (text == "sys.day_of_week") { if (!syntaxCheckOnly) { array = new string[] { DateTime.Today.DayOfWeek.ToString() }; } } else { if (!(text == "sys.day_of_year")) { throw new Exception("Unknown match source '" + text + "' !"); } if (!syntaxCheckOnly) { array = new string[] { DateTime.Today.ToString("M") }; } } flag = false; text = r.ReadWord(true, new char[] { ' ' }, true); if (text == null) { throw new Exception("Invalid syntax: operator is missing ! \r\n\r\n Near: '" + r.OriginalString.Substring(0, r.Position) + "'"); } text = text.ToLower(); if (text == "*") { string text4 = r.ReadWord(); if (text4 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text4 = text4.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int m = 0; m < array4.Length; m++) { string text5 = array4[m]; if (SCore.IsAstericMatch(text4, text5.ToLower())) { flag = true; break; } } } } else if (text == "!*") { string text6 = r.ReadWord(); if (text6 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text6 = text6.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text7 = array4[j]; if (SCore.IsAstericMatch(text6, text7.ToLower())) { flag = false; break; } } } } else if (text == "==") { string text8 = r.ReadWord(); if (text8 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text8 = text8.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text9 = array4[j]; if (text8 == text9.ToLower()) { flag = true; break; } } } } else if (text == "!=") { string text10 = r.ReadWord(); if (text10 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text10 = text10.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text11 = array4[j]; if (text10 == text11.ToLower()) { flag = false; break; } flag = true; } } } else if (text == ">=") { string text12 = r.ReadWord(); if (text12 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text12 = text12.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text13 = array4[j]; if (text13.ToLower().CompareTo(text12) >= 0) { flag = true; break; } } } } else if (text == "<=") { string text14 = r.ReadWord(); if (text14 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text14 = text14.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text15 = array4[j]; if (text15.ToLower().CompareTo(text14) <= 0) { flag = true; break; } } } } else if (text == ">") { string text16 = r.ReadWord(); if (text16 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text16 = text16.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text17 = array4[j]; if (text17.ToLower().CompareTo(text16) > 0) { flag = true; break; } } } } else if (text == "<") { string text18 = r.ReadWord(); if (text18 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text18 = text18.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text19 = array4[j]; if (text19.ToLower().CompareTo(text18) < 0) { flag = true; break; } } } } else { if (!(text == "regex")) { throw new Exception("Unknown keword '" + text + "' !"); } string text20 = r.ReadWord(); if (text20 == null) { throw new Exception("Invalid syntax: <SP> \"value\" is missing !"); } text20 = text20.ToLower(); if (!syntaxCheckOnly) { string[] array4 = array; for (int j = 0; j < array4.Length; j++) { string text21 = array4[j]; if (Regex.IsMatch(text20, text21.ToLower())) { flag = true; break; } } } } possibleClauseItem = (GlobalMessageRuleProcessor.PossibleClauseItem) 6; } } return(flag); }