/// <summary> /// Parses IMAP date time from string. /// </summary> /// <param name="date">DateTime string.</param> /// <returns>Returns parsed date-time value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>date</b> is null reference.</exception> public static DateTime ParseDate(string date) { if (date == null) { throw new ArgumentNullException("date"); } return(MIME_Utils.ParseRfc2822DateTime(date)); }
/// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static Mail_h_AddressList Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new[] { ':' }, 2); if (name_value.Length != 2) { throw new ParseException("Invalid header field value '" + value + "'."); } MIME_Reader r = new MIME_Reader(MIME_Utils.UnfoldHeader(name_value.Length == 2 ? name_value[1].TrimStart() : "")); Mail_h_AddressList retVal = new Mail_h_AddressList(name_value[0], new Mail_t_AddressList()); while (true) { string word = r.QuotedReadToDelimiter(new[] { ',', '<', ':' }); // We processed all data. if (word == null && r.Available == 0) { break; } // name-addr else if (r.Peek(true) == '<') { retVal.m_pAddresses.Add( new Mail_t_Mailbox( word != null ? MIME_Encoding_EncodedWord.DecodeAll(TextUtils.UnQuoteString(word)) : null, r.ReadParenthesized())); } // addr-spec else { retVal.m_pAddresses.Add(new Mail_t_Mailbox(null, word)); } // We have more addresses. if (r.Peek(true) == ',') { r.Char(false); } } retVal.m_ParseValue = value; retVal.m_pAddresses.AcceptChanges(); return(retVal); }
/// <summary> /// Creates Mime message based on UI data. /// </summary> private Mail_Message CreateMessage() { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.From = Mail_h_MailboxList.Parse("From: " + m_pFrom.Text).Addresses; msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(m_pFolder.User.FullName, m_pFolder.User.FullName + "@localhost")); msg.Subject = m_pSubject.Text; //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, m_pText.Text); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ------------------------------------------------------------------------------------------------------ MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, RtfToHtml()); multipartAlternative.BodyParts.Add(entity_text_html); //--- application/octet-stream ----------------------------------------------------------------------------------------------- foreach (ListViewItem item in m_pAttachments.Items) { multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(item.Tag.ToString())); } return(msg); }
/// <summary> /// 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 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); } } }
/// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <returns>Returns header field as string.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset) { if (IsModified) { StringBuilder retVal = new StringBuilder(); retVal.Append("Received: "); retVal.Append("FROM " + m_From); if (m_pFrom_TcpInfo != null) { retVal.Append(" (" + m_pFrom_TcpInfo + ")"); } retVal.Append(" BY " + m_By); if (m_pBy_TcpInfo != null) { retVal.Append(" (" + m_pBy_TcpInfo + ")"); } if (!string.IsNullOrEmpty(m_Via)) { retVal.Append(" VIA " + m_Via); } if (!string.IsNullOrEmpty(m_With)) { retVal.Append(" WITH " + m_With); } if (!string.IsNullOrEmpty(m_ID)) { retVal.Append(" ID " + m_ID); } if (!string.IsNullOrEmpty(m_For)) { retVal.Append(" FOR " + m_For); } retVal.Append("; " + MIME_Utils.DateTimeToRfc2822(m_Time)); retVal.Append("\r\n"); return(retVal.ToString()); } else { return(m_ParseValue); } }
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 void m_pOk_Click(object sender, EventArgs e) { 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; if (!string.IsNullOrEmpty(this.m_pTo.Text)) { mail_Message.To = Mail_h_AddressList.Parse("To: " + this.m_pTo.Text).Addresses; } mail_Message.Subject = this.m_pSubject.Text; MIME_b_Text mIME_b_Text = new MIME_b_Text(MIME_MediaTypes.Text.plain); mail_Message.Body = mIME_b_Text; mIME_b_Text.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, this.m_pBodyText.Text); this.m_Message = mail_Message.ToString(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B, Encoding.UTF8), Encoding.UTF8); base.DialogResult = DialogResult.OK; }
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); }
/// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Sender: [email protected]'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static Mail_h_Received Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new char[] { ':' }, 2); if (name_value.Length != 2) { throw new ParseException("Invalid header field value '" + value + "'."); } Mail_h_Received retVal = new Mail_h_Received("a", "b", DateTime.MinValue); MIME_Reader r = new MIME_Reader(name_value[1]); while (true) { string word = r.Word(); // We processed all data. if (word == null && r.Available == 0) { break; } // We have comment, just eat it. else if (r.StartsWith("(")) { r.ReadParenthesized(); } // We have date-time or unknown-data. else if (r.StartsWith(";")) { // Eat ';' r.Char(false); try{ retVal.m_Time = MIME_Utils.ParseRfc2822DateTime(r.QuotedReadToDelimiter(new char[] { ';' })); } catch { // We hane some unknown data, skip it. } } else { // We have some unexpected char like: .,= ... . Just eat it. if (word == null) { r.Char(true); continue; } word = word.ToUpperInvariant(); if (word == "FROM") { retVal.m_From = r.DotAtom(); r.ToFirstChar(); if (r.StartsWith("(")) { string[] parts = r.ReadParenthesized().Split(' '); if (parts.Length == 1) { if (Net_Utils.IsIPAddress(parts[0])) { retVal.m_pFrom_TcpInfo = new Mail_t_TcpInfo(IPAddress.Parse(parts[0]), null); } } else if (parts.Length == 2) { if (Net_Utils.IsIPAddress(parts[1])) { retVal.m_pFrom_TcpInfo = new Mail_t_TcpInfo(IPAddress.Parse(parts[1]), parts[0]); } } } } else if (word == "BY") { retVal.m_By = r.DotAtom(); r.ToFirstChar(); if (r.StartsWith("(")) { string[] parts = r.ReadParenthesized().Split(' '); if (parts.Length == 1) { if (Net_Utils.IsIPAddress(parts[0])) { retVal.m_pBy_TcpInfo = new Mail_t_TcpInfo(IPAddress.Parse(parts[0]), null); } } else if (parts.Length == 2) { if (Net_Utils.IsIPAddress(parts[1])) { retVal.m_pBy_TcpInfo = new Mail_t_TcpInfo(IPAddress.Parse(parts[1]), parts[0]); } } } } else if (word == "VIA") { retVal.m_Via = r.Word(); } else if (word == "WITH") { retVal.m_With = r.Word(); } else if (word == "ID") { // msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS] if (r.StartsWith("<")) { retVal.m_ID = r.ReadParenthesized(); } else { retVal.m_ID = r.Atom(); } } else if (word == "FOR") { r.ToFirstChar(); // path / angle-address if (r.StartsWith("<")) { retVal.m_For = r.ReadParenthesized(); } else { string mailbox = Mail_Utils.SMTP_Mailbox(r); if (mailbox == null) { throw new ParseException("Invalid Received: For parameter value '" + r.ToEnd() + "'."); } retVal.m_For = mailbox; } } // Unknown, just eat value. else { r.Word(); } } } retVal.m_ParseValue = value; return(retVal); }
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> /// Construct secified mime entity ENVELOPE string. /// </summary> /// <param name="entity">Mail message.</param> /// <returns></returns> public static string ConstructEnvelope(Mail_Message entity) { /* RFC 3501 7.4.2 * ENVELOPE * A parenthesized list that describes the envelope structure of a * message. This is computed by the server by parsing the * [RFC-2822] header into the component parts, defaulting various * fields as necessary. * * The fields of the envelope structure are in the following * order: date, subject, from, sender, reply-to, to, cc, bcc, * in-reply-to, and message-id. The date, subject, in-reply-to, * and message-id fields are strings. The from, sender, reply-to, * to, cc, and bcc fields are parenthesized lists of address * structures. * * An address structure is a parenthesized list that describes an * electronic mail address. The fields of an address structure * are in the following order: personal name, [SMTP] * at-domain-list (source route), mailbox name, and host name. * * [RFC-2822] group syntax is indicated by a special form of * address structure in which the host name field is NIL. If the * mailbox name field is also NIL, this is an end of group marker * (semi-colon in RFC 822 syntax). If the mailbox name field is * non-NIL, this is a start of group marker, and the mailbox name * field holds the group name phrase. * * If the Date, Subject, In-Reply-To, and Message-ID header lines * are absent in the [RFC-2822] header, the corresponding member * of the envelope is NIL; if these header lines are present but * empty the corresponding member of the envelope is the empty * string. * * Note: some servers may return a NIL envelope member in the * "present but empty" case. Clients SHOULD treat NIL and * empty string as identical. * * Note: [RFC-2822] requires that all messages have a valid * Date header. Therefore, the date member in the envelope can * not be NIL or the empty string. * * Note: [RFC-2822] requires that the In-Reply-To and * Message-ID headers, if present, have non-empty content. * Therefore, the in-reply-to and message-id members in the * envelope can not be the empty string. * * If the From, To, cc, and bcc header lines are absent in the * [RFC-2822] header, or are present but empty, the corresponding * member of the envelope is NIL. * * If the Sender or Reply-To lines are absent in the [RFC-2822] * header, or are present but empty, the server sets the * corresponding member of the envelope to be the same value as * the from member (the client is not expected to know to do * this). * * Note: [RFC-2822] requires that all messages have a valid * From header. Therefore, the from, sender, and reply-to * members in the envelope can not be NIL. * * ENVELOPE ("date" "subject" from sender reply-to to cc bcc "in-reply-to" "messageID") */ // NOTE: all header fields and parameters must in ENCODED form !!! MIME_Encoding_EncodedWord wordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B, Encoding.UTF8); wordEncoder.Split = false; StringBuilder retVal = new StringBuilder(); retVal.Append("ENVELOPE ("); // date try{ if (entity.Date != DateTime.MinValue) { retVal.Append(TextUtils.QuoteString(MIME_Utils.DateTimeToRfc2822(entity.Date))); } else { retVal.Append("NIL"); } } catch { retVal.Append("NIL"); } // subject if (entity.Subject != null) { //retVal.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.Subject))); string val = wordEncoder.Encode(entity.Subject); retVal.Append(" {" + val.Length + "}\r\n" + val); } else { retVal.Append(" NIL"); } // from if (entity.From != null && entity.From.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.From.ToArray(), wordEncoder)); } else { retVal.Append(" NIL"); } // sender // NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList. if (entity.Sender != null) { retVal.Append(" ("); retVal.Append(ConstructAddress(entity.Sender, wordEncoder)); retVal.Append(")"); } else { retVal.Append(" NIL"); } // reply-to if (entity.ReplyTo != null) { retVal.Append(" " + ConstructAddresses(entity.ReplyTo.Mailboxes, wordEncoder)); } else { retVal.Append(" NIL"); } // to if (entity.To != null && entity.To.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.To.Mailboxes, wordEncoder)); } else { retVal.Append(" NIL"); } // cc if (entity.Cc != null && entity.Cc.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.Cc.Mailboxes, wordEncoder)); } else { retVal.Append(" NIL"); } // bcc if (entity.Bcc != null && entity.Bcc.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.Bcc.Mailboxes, wordEncoder)); } else { retVal.Append(" NIL"); } // in-reply-to if (entity.InReplyTo != null) { retVal.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.InReplyTo))); } else { retVal.Append(" NIL"); } // message-id if (entity.MessageID != null) { retVal.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.MessageID))); } else { retVal.Append(" NIL"); } retVal.Append(")"); return(retVal.ToString()); }
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); }
/// <summary> /// Creates delivery status notifications(DSN) message. /// </summary> /// <param name="to">DSN message To.</param> /// <param name="subject">DSN message subject.</param> /// <param name="rtfText">DSN message RTF body text.</param> /// <param name="envelopeID">Envelope ID(MAIL FROM: ENVID).</param> /// <param name="arrivalDate">Message arrival date.</param> /// <param name="receivedFromMTA">The remote host EHLo name from where messages was received.</param> /// <param name="reportingMTA">Reporting MTA name.</param> /// <param name="originalRecipient">Original recipient(RCPT TO: ORCTP).</param> /// <param name="finalRecipient">Final recipient.</param> /// <param name="action">DSN action.</param> /// <param name="statusCode_text">Remote SMTP status code with text.</param> /// <param name="remoteMTA">Remote MTA what returned <b>statusCode_text</b>.</param> /// <param name="lastAttempt">Last delivery attempt.</param> /// <param name="retryUntil">Date time how long server will attempt to deliver message.</param> /// <param name="ret">Specifies what original message part are renturned.</param> /// <param name="message">Original message.</param> /// <returns>Returns created DSN message.</returns> public static Mail_Message CreateDsnMessage(string to, string subject, string rtfText, string envelopeID, DateTime arrivalDate, string receivedFromMTA, string reportingMTA, string originalRecipient, string finalRecipient, string action, string statusCode_text, string remoteMTA, DateTime lastAttempt, DateTime retryUntil, SMTP_DSN_Ret ret, Mail_Message message) { // For more info, see RFC 3464. // Ensure that all line-feeds are CRLF. rtfText = rtfText.Replace("\r\n", "\n").Replace("\n", "\r\n"); Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.Date = DateTime.Now; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox("Mail Delivery Subsystem", "postmaster@local")); msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(null, to)); msg.Subject = subject; //--- multipart/report ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartReport = new MIME_h_ContentType(MIME_MediaTypes.Multipart.report); contentType_multipartReport.Parameters["report-type"] = "delivery-status"; contentType_multipartReport.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartReport multipartReport = new MIME_b_MultipartReport(contentType_multipartReport); msg.Body = multipartReport; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipart_alternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipart_alternative.Body = multipartAlternative; multipartReport.BodyParts.Add(entity_multipart_alternative); //--- text/plain --------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToText(rtfText)); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ----------------------------------------------------------------------------------------------------- MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToHtml(rtfText)); multipartAlternative.BodyParts.Add(entity_text_html); //--- message/delivery-status MIME_Entity entity_message_deliveryStatus = new MIME_Entity(); MIME_b_Message body_message_deliveryStatus = new MIME_b_Message(MIME_MediaTypes.Message.delivery_status); entity_message_deliveryStatus.Body = body_message_deliveryStatus; StringBuilder dsnText = new StringBuilder(); if (!string.IsNullOrEmpty(envelopeID)) { dsnText.Append("Original-Envelope-Id: " + envelopeID + "\r\n"); } dsnText.Append("Arrival-Date: " + MIME_Utils.DateTimeToRfc2822(arrivalDate) + "\r\n"); if (!string.IsNullOrEmpty(receivedFromMTA)) { dsnText.Append("Received-From-MTA: dns; " + receivedFromMTA + "\r\n"); } dsnText.Append("Reporting-MTA: dns; " + reportingMTA + "\r\n"); dsnText.Append("\r\n"); if (!string.IsNullOrEmpty(originalRecipient)) { dsnText.Append("Original-Recipient: " + originalRecipient + "\r\n"); } dsnText.Append("Final-Recipient: rfc822;" + finalRecipient + "" + "\r\n"); dsnText.Append("Action: " + action + "\r\n"); dsnText.Append("Status: " + statusCode_text.Substring(0, 1) + ".0.0" + "\r\n"); if (!string.IsNullOrEmpty(statusCode_text)) { dsnText.Append("Diagnostic-Code: smtp; " + statusCode_text + "\r\n"); } if (!string.IsNullOrEmpty(remoteMTA)) { dsnText.Append("Remote-MTA: dns; " + remoteMTA + "\r\n"); } if (lastAttempt != DateTime.MinValue) { dsnText.Append("Last-Attempt-Date: " + MIME_Utils.DateTimeToRfc2822(lastAttempt) + "\r\n"); } if (retryUntil != DateTime.MinValue) { dsnText.Append("Will-Retry-Until: " + MIME_Utils.DateTimeToRfc2822(retryUntil) + "\r\n"); } dsnText.Append("\r\n"); body_message_deliveryStatus.SetData(new MemoryStream(Encoding.UTF8.GetBytes(dsnText.ToString())), MIME_TransferEncodings.EightBit); multipartReport.BodyParts.Add(entity_message_deliveryStatus); //--- message/rfc822 if (message != null) { MIME_Entity entity_message_rfc822 = new MIME_Entity(); MIME_b_MessageRfc822 body_message_rfc822 = new MIME_b_MessageRfc822(); entity_message_rfc822.Body = body_message_rfc822; if (ret == SMTP_DSN_Ret.FullMessage) { body_message_rfc822.Message = message; } else { MemoryStream ms = new MemoryStream(); message.Header.ToStream(ms, null, null); ms.Position = 0; body_message_rfc822.Message = Mail_Message.ParseFromStream(ms); } multipartReport.BodyParts.Add(entity_message_rfc822); } return(msg); }
/// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <param name="reEncode">If true always specified encoding is used. If false and header field value not modified, original encoding is kept.</param> /// <returns>Returns header field as string.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset, bool reEncode) { if (reEncode || this.IsModified) { StringBuilder retVal = new StringBuilder(); retVal.Append("Received: "); retVal.Append("from " + m_From); if (m_pFrom_TcpInfo != null) { retVal.Append(" (" + m_pFrom_TcpInfo.ToString() + ")"); } retVal.Append(" by " + m_By); if (m_pBy_TcpInfo != null) { retVal.Append(" (" + m_pBy_TcpInfo.ToString() + ")"); } if (!string.IsNullOrEmpty(m_Via)) { retVal.Append(" via " + m_Via); } if (!string.IsNullOrEmpty(m_With)) { retVal.Append(" with " + m_With); } if (!string.IsNullOrEmpty(m_ID)) { retVal.Append(" id " + m_ID); } if (!string.IsNullOrEmpty(m_For)) { retVal.Append(" for " + m_For); } retVal.Append("; " + MIME_Utils.DateTimeToRfc2822(m_Time)); retVal.Append("\r\n"); /* Some servers doesnt like uppercase. * retVal.Append("Received: "); * retVal.Append("FROM " + m_From); * if(m_pFrom_TcpInfo != null){ * retVal.Append(" (" + m_pFrom_TcpInfo.ToString() + ")"); * } * retVal.Append(" BY " + m_By); * if(m_pBy_TcpInfo != null){ * retVal.Append(" (" + m_pBy_TcpInfo.ToString() + ")"); * } * if(!string.IsNullOrEmpty(m_Via)){ * retVal.Append(" VIA " + m_Via); * } * if(!string.IsNullOrEmpty(m_With)){ * retVal.Append(" WITH " + m_With); * } * if(!string.IsNullOrEmpty(m_ID)){ * retVal.Append(" ID " + m_ID); * } * if(!string.IsNullOrEmpty(m_For)){ * retVal.Append(" FOR " + m_For); * } * retVal.Append("; " + MIME_Utils.DateTimeToRfc2822(m_Time)); * retVal.Append("\r\n");*/ return(retVal.ToString()); } else { return(m_ParseValue); } }
public static void ConstructEnvelope(StructureBuilder builder, Mail_Message entity) { // date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id var wordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B, Encoding.UTF8); wordEncoder.Split = false; builder.Append("ENVELOPE").SpaceNBracket(); // date try { if (entity.Date != DateTime.MinValue) { builder.Append(TextUtils.QuoteString(MIME_Utils.DateTimeToRfc2822(entity.Date))); } else { builder.Append("NIL"); } } catch { builder.Append("NIL"); } // subject if (entity.Subject != null) { builder.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.Subject))); //string val = wordEncoder.Encode(entity.Subject); //builder.Append(" {").Append(val.Length).Append("}\r\n").Append(val); } else { builder.AppendNil(); } // from if (entity.From != null && entity.From.Count > 0) { builder.Append(" "); ConstructAddresses(builder, entity.From.ToArray(), wordEncoder); } else { builder.AppendNil(); } // sender // NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList. if (entity.Sender != null) { builder.SpaceNBracket(); ConstructAddress(builder, entity.Sender, wordEncoder); builder.EndBracket(); } else { builder.AppendNil(); } // reply-to if (entity.ReplyTo != null) { builder.Append(" "); ConstructAddresses(builder, entity.ReplyTo.Mailboxes, wordEncoder); } else { builder.Append(" NIL"); } // to if (entity.To != null && entity.To.Count > 0) { builder.Append(" "); ConstructAddresses(builder, entity.To.Mailboxes, wordEncoder); } else { builder.Append(" NIL"); } // cc if (entity.Cc != null && entity.Cc.Count > 0) { builder.Append(" "); ConstructAddresses(builder, entity.Cc.Mailboxes, wordEncoder); } else { builder.AppendNil(); } // bcc if (entity.Bcc != null && entity.Bcc.Count > 0) { builder.Append(" "); ConstructAddresses(builder, entity.Bcc.Mailboxes, wordEncoder); } else { builder.AppendNil(); } // in-reply-to if (entity.InReplyTo != null) { builder.Append(" ").Append(TextUtils.QuoteString(wordEncoder.Encode(entity.InReplyTo))); } else { builder.AppendNil(); } // message-id if (entity.MessageID != null) { builder.Append(" ").Append(TextUtils.QuoteString(wordEncoder.Encode(entity.MessageID))); } else { builder.AppendNil(); } builder.EndBracket(); }
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); }
/// <summary> /// Parses IMAP FETCH ENVELOPE from reader. /// </summary> /// <param name="r">Fetch reader.</param> /// <returns>Returns parsed envelope.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> public static IMAP_t_Fetch_r_i_Envelope Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } /* RFC 3501 7.4.2. FETCH Response. * ENVELOPE * A parenthesized list that describes the envelope structure of a * message. This is computed by the server by parsing the * [RFC-2822] header into the component parts, defaulting various * fields as necessary. * * The fields of the envelope structure are in the following * order: date, subject, from, sender, reply-to, to, cc, bcc, * in-reply-to, and message-id. The date, subject, in-reply-to, * and message-id fields are strings. The from, sender, reply-to, * to, cc, and bcc fields are parenthesized lists of address * structures. * * An address structure is a parenthesized list that describes an * electronic mail address. The fields of an address structure * are in the following order: personal name, [SMTP] * at-domain-list (source route), mailbox name, and host name. * * [RFC-2822] group syntax is indicated by a special form of * address structure in which the host name field is NIL. If the * mailbox name field is also NIL, this is an end of group marker * (semi-colon in RFC 822 syntax). If the mailbox name field is * non-NIL, this is a start of group marker, and the mailbox name * field holds the group name phrase. * * If the Date, Subject, In-Reply-To, and Message-ID header lines * are absent in the [RFC-2822] header, the corresponding member * of the envelope is NIL; if these header lines are present but * empty the corresponding member of the envelope is the empty * string. * * Note: some servers may return a NIL envelope member in the * "present but empty" case. Clients SHOULD treat NIL and * empty string as identical. * * Note: [RFC-2822] requires that all messages have a valid * Date header. Therefore, the date member in the envelope can * not be NIL or the empty string. * * Note: [RFC-2822] requires that the In-Reply-To and * Message-ID headers, if present, have non-empty content. * Therefore, the in-reply-to and message-id members in the * envelope can not be the empty string. * * If the From, To, cc, and bcc header lines are absent in the * [RFC-2822] header, or are present but empty, the corresponding * member of the envelope is NIL. * * If the Sender or Reply-To lines are absent in the [RFC-2822] * header, or are present but empty, the server sets the * corresponding member of the envelope to be the same value as * the from member (the client is not expected to know to do * this). * * Note: [RFC-2822] requires that all messages have a valid * From header. Therefore, the from, sender, and reply-to * members in the envelope can not be NIL. */ // Read "date". DateTime date = DateTime.MinValue; string dateS = r.ReadWord(); if (!string.IsNullOrEmpty(dateS) && !dateS.Equals("NIL", Helpers.GetDefaultIgnoreCaseComparison())) { date = MIME_Utils.ParseRfc2822DateTime(dateS); } // Read "subject". string subject = ReadAndDecodeWord(r); // Read "from" Mail_t_Address[] from = ReadAddresses(r); //Read "sender" Mail_t_Address[] sender = ReadAddresses(r); // Read "reply-to" Mail_t_Address[] replyTo = ReadAddresses(r); // Read "to" Mail_t_Address[] to = ReadAddresses(r); // Read "cc" Mail_t_Address[] cc = ReadAddresses(r); // Read "bcc" Mail_t_Address[] bcc = ReadAddresses(r); // Read "in-reply-to" string inReplyTo = r.ReadWord(); // Read "message-id" string messageID = r.ReadWord(); return(new IMAP_t_Fetch_r_i_Envelope(date, subject, from, sender, replyTo, to, cc, bcc, inReplyTo, messageID)); }
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> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static Mail_h_MailboxList Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new[] { ':' }, 2); if (name_value.Length != 2) { throw new ParseException("Invalid header field value '" + value + "'."); } /* RFC 5322 3.4. * mailbox = name-addr / addr-spec * * name-addr = [display-name] angle-addr * * angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr * * display-name = phrase * * mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list */ MIME_Reader r = new MIME_Reader(MIME_Utils.UnfoldHeader(name_value.Length == 2 ? name_value[1].TrimStart() : "")); Mail_h_MailboxList retVal = new Mail_h_MailboxList(name_value[0], new Mail_t_MailboxList()); while (true) { string word = r.QuotedReadToDelimiter(new[] { ',', '<', ':' }); // We processed all data. if (word == null && r.Available == 0) { break; } // name-addr else if (r.Peek(true) == '<') { retVal.m_pAddresses.Add( new Mail_t_Mailbox( word != null ? MIME_Encoding_EncodedWord.DecodeAll(word) : null, r.ReadParenthesized())); } // addr-spec else { retVal.m_pAddresses.Add(new Mail_t_Mailbox(null, word)); } // We have more addresses. if (r.Peek(true) == ',') { r.Char(false); } } retVal.m_ParseValue = value; retVal.m_pAddresses.AcceptChanges(); return(retVal); }
public void Send(ChannelMessage message) { var creds = CredentialsProvider.GetCredentials().ToNetworkCredential(); Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Subject = message.Context; msg.From = message.From.ToMailBoxList(); msg.ReplyTo = message.ReturnTo == null? message.From.ToAddressList() : message.ReturnTo.ToAddressList(); if (String.IsNullOrEmpty(message.InReplyTo) == false) { msg.InReplyTo = message.InReplyTo; } msg.To = new Mail_t_AddressList(); foreach (var address in message.To) { msg.To.Add(address.ToMailBox()); } msg.Cc = new Mail_t_AddressList(); foreach (var address in message.CC) { msg.Cc.Add(address.ToMailBox()); } //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; // Add text body if there is any if (message.BodyText != null && message.BodyText.Length > 0) { var bodyText = message.BodyText.ReadString(); // Make sure there is a newline at the end of our text, otherwise it will screw up // our multipart data format if (!bodyText.EndsWith(Environment.NewLine)) { bodyText = bodyText + Environment.NewLine; } text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText); } multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ------------------------------------------------------------------------------------------------------ MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; if (message.BodyHtml != null && message.BodyHtml.Length > 0) { var bodyHtml = message.BodyHtml.ReadString(); // Make sure there is a newline at the end of our text, otherwise it will screw up // our multipart data format if (!bodyHtml.EndsWith(Environment.NewLine)) { bodyHtml = bodyHtml + Environment.NewLine; } text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml); } multipartAlternative.BodyParts.Add(entity_text_html); foreach (var channelAttachment in message.Attachments) { MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream); MIME_Entity attachment = new MIME_Entity(); attachment.Body = attachmentBody; // Has to happen before the following lines of code multipartMixed.BodyParts.Add(attachment); attachment.ContentType = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename)); attachment.ContentType.Param_Name = channelAttachment.Filename; MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment); contentDisposition.Param_FileName = channelAttachment.Filename; attachment.ContentDisposition = contentDisposition; attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString(); attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64); } // Inject headers if (!String.IsNullOrEmpty(message.MessageIdentifier)) { msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier)); } //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow)) // msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow)); //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference)) // mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference); //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence)) // mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence); //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation)) // mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation); //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId)) // mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId); // Send message try { SMTP_Client client = new SMTP_Client(); if ("/Settings/Channels/LoggerEnabled".AsKey(false)) { client.Logger = new LumiSoft.Net.Log.Logger(); } // todo push this logic into the smtp client implementation itself if (Hostname == "smtp.live.com") { // Hack for hotmail, first do a connect with no secured channel, // then a STARTTLS client.Connect(Hostname, Port, false); client.StartTLS(); } else { client.Connect(Hostname, Port, IsSecured); } client.Authenticate(creds.UserName, creds.Password); using (MemoryStream ms = new MemoryStream()) { client.MailFrom(msg.From[0].Address, -1); msg.ToStream(ms, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); // Reset stream ms.Seek(0, SeekOrigin.Begin); foreach (var address in message.To) { client.RcptTo(address.Address); } foreach (var address in message.CC) { client.RcptTo(address.Address); } foreach (var address in message.BCC) { client.RcptTo(address.Address); } try { client.SendMessage(ms); } finally { client.Dispose(); } } } catch (SmtpFailedRecipientsException e) { throw new ChannelFunctionalException(e.Message, e) { DoNotRetry = true }; } catch (SmtpException e) { throw new ChannelFunctionalException(e.Message, e); } catch (Exception e) { throw new ChannelFunctionalException(e.Message, e); } }