Cross-platform. NET Mail protocol Mailkit component parsing

Source: Internet
Author: User
Tags rfc822

Initiated by the. NET Core Open source organization call, the speed of progress is I did not think of, many friends are actively involved (although some people sincerely hit the party, if I had a former treasure temper, this should be I call the hospital, but fortunately is a few, do one thing always someone said, also some people say that the "eye ”),. NET community is not not happy to share knowledge of the people, but not a complete and good ecological environment, in short, hope the domestic. NET development is becoming more and more powerful. I think of a word here: "We wish we could do the big waves, but we are willing to do the waves before the storm."

Above the end of the tear (I am the person in advance, will be some nonsense, this habit can not be changed off ...) )

In order to timely communication in the project, there are direct data to the page, there is also the use of SMS notification, but also the mail components we introduced today. Our main task today is to explain that there is one. Net of free open source mail components mailkit. This article will continue to be a combination of examples and components of the underlying code to explain the knowledge of related components. (I'll ask when the project is hiring.) NET of the underlying principle, there is a great God asked me what is the meaning of this? We can't write it either. NET bottom of the excellent processing way, why get to know these, in fact, I personally think, ask the underlying principle, just to deal with a good process some of the problems, as well as coding the program, choose the most appropriate way to improve performance, any one way has advantages and disadvantages. NET class library code is the same, if we know. NET, we can be based on the requirements of the project when it is implemented. NET bottom-level implementation, choose the right way, in order to optimize performance).

I. Mailkit Components Overview

The use of email in the project more opportunities, generally slightly larger items, will use the mail operation this one operation. For. NET mail operations more components and ways, today we introduce a mail operation of the component Mailkit, this mail component is an open source free, we will now look at the characteristics of this component. Mimekit is designed to address this problem by following the MIME specification as closely as possible, while also providing programmers with a very easy-to-use, high-level API.

The component supports more client types, such as SMTP clients, POP3 clients, and IMAP clients. This component is a cross-platform email component that supports the. NET 4.0,.net 4.5,xamarin.android,xamarin.ios,windows Phone 8.1 platform. The component provides a MIME parser with flexible parsing features, high performance, and good handling of a wide variety of broken MIME formats. the performance of Mimekit is actually equivalent to Gmime.

The security of the component is still relatively high, the way to handle security more, SASL authentication, support S/MIME v3.2, support OpenPGP, support Dkim signature and so on. Mailkit components can beCancellationToken cancel the corresponding operation, CancellationToken propagation should cancel the operation of the notification,a The object that makes the thread, thread pool work items, or cancels the collaboration task Cancellationtokensource cancellationtokensource.token property retrieved cancellation token The then passes the cancellation token to any number of threads, tasks, or actions that should be notified of the cancellation. The token cannot be used to initiate cancellation.

The Mailkit component supports asynchronous operations, and the classes written internally about I/O asynchronous operations.

Two. Mailkit Example:

The background and features of the Mailkit component are described above, and the simple application of the email component is described here.

1. How to create a message:


 public void sentemail (String path)         {             var message = new  MimeMessage ();             //Gets the address list in the From header, adding the specified address             message. From.add (new mailboxaddress ("Joey",  "[email protected]"));             //Gets the address list in the to header, adding the specified address              message. To.add (new mailboxaddress ("Alice",  "[email protected]"));             //Gets or sets the subject of the message              message. subject =  "How you doin?";             //  creates our message text just as before (except not set to message.) Body)             var body = new  textpart ("plain")             {                 text = @ "Hey  alice-- joey "            };             //  Create an image attachment for a file that is located in the path              var attachment = new mimepart ("image",   "GIF")             {                 ContentObject = new  Contentobject (File.openread (path),  contentencoding.default),                 contentdisposition = new  Contentdisposition (contentdisposition.attachment),                 ContentTransferEncoding = ContentEncoding.Base64,                 FileName =  Path.getfilename (PATH)             };             //  Create multipart /  Now Mixed container to save message text and image attachments             var multipart  = new multipart ("mixed")              {                body,  attachment            };             //  now set multipart / mixed to the message body               message. body = multipart;        }


It is easier to call this component to send a message and add an attachment to the message, the first step is to instantiate the MimeMessage object, and the parsing of the object will be done below, after getting the MimeMessage object, specify the address and subject of the message, and so on. The second step instantiates the Textpart object and sets the text information for the object. If you need to ask a message to create an attachment to a file, you can use the MimePart object, which contains an attachment to the Leaf node mime part of the content (such as message body text or). The fourth step is to create the message body and text as well as the attachment information, you can create a multipart object, create a mail container, to load text information and attachments. Finally call the Mimemessage.body property to get or set the body of the message.

2. Analysis of message information:
var message = Mimemessage.load (stream);

Message we need to do the corresponding parsing, here we use the MimeMessage load method, the method loads the mimekit.mimemessage from the specified stream. Another way to load the data, you can use the Mimeparser class, which is no longer parsed.

3. Receipt of mail:


   public static void handlemimeentity (mimeentity entity)          {            // Mimeentity converted to multipart entities             var  multipart = entity as multipart;             if  (multipart != null)              {                 for  (Int i = 0; i < multipart. count; i++)                      handlemimeentity (Multipart[i]);                 return;            }             var rfc822 = entity as MessagePart;             if  (rfc822 != null)              {                 var message = rfc822. message;                 Handlemimeentity (message. Body);                return;             }             var part =  (MimePart) entity;         }


The above is a traversal of the received message, using recursion to traverse the MIME structure. MIME is the tree structure of content, much like a file system. MIME does define a common set of rules for how the mail client interprets the tree structure of the MIME part. of the the content disposition header is intended to provide the receiving client with hints as to which portions are to be displayed as part of the message body, and are meant to be interpreted as attachments. There are two other ways of doing this.

Three. Mailkit Core Object parsing

The above describes the basic operation of email does not do too much introduction, in the use of the component, the more simple. Here's a look at the type structure of the component and some core objects. The class library structure resembles the following:

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/831875/201703/831875-20170317002859135-1588383177. PNG "style=" margin:0px;padding:0px;border:0px; "/>

1.mimemessage.load ():


MimeMessage Load (parseroptions options, Stream stream, persistent, CancellationToken can Cellationtoken = (Options = = (Stream = = Parser =


The method loads the mimemessage from the specified stream, with 6 method overloads. The method returns a MimeMessage object, as the source can see, creates a Mimeparser object inside the method, Mimeparser the leaf node mime part that contains content such as message body text or attachments. Call the Parsemessage method to parse the message from the stream.

2.textpart.text:


Public string text {            get  {                if   (Contentobject == null)                      return string. Empty;                var  charset = contenttype.parameters["CharSet"];                 using  (Var memory = new memorystream   ())  {                     ContentObject.DecodeTo  (memory);                   &nbsP; var content = memory. toarray  ();                     Encoding encoding = null;                     if  (charset !=  null)  {                         try {                              encoding = CharsetUtils.GetEncoding  (CharSet);                          } catch  (NotSupportedException)  {                        }                      }                     if  (encoding == null)  {                         try {                              return CharsetUtils.UTF8.GetString  ( content, 0,  (int)  memory. Length);                         } catch  (decoderfallbackexception) &NBSP;{&NBsp;                            encoding = CharsetUtils.Latin1;                          }                     }                     return encoding. getstring  (content, 0,  (int)  memory. Length);                 }             }             set {                 settext  (Encoding.utf8, value);             }        }


This property gets the decoded text content. This property is a readable and writable property. Contenttype.parameters["CharSet"] is used to get the value of the CharSet parameter. This method is used to set the value of the parameter to the data stream and set the corresponding encoding. See here the exception handling structure, just want to talk a few simple words,. NET exception comparison is weak, many times in writing. NET exception is more simple, the above is the exception of knowledge capture, some places do not do processing, and some places are the abnormal place to recover.

3.mimeentity.writeto ():


WriteTo (formatoptions options, Stream stream, contentonly, CancellationToken Cancellationtok En = (options = = (Stream = = (!


The method writes mimeentity to the specified data stream, which accepts the parameter options format option. Stream output data stream, contentonly determine whether writable. The method is defined as a virtual method, and after inheriting this method, the method can be overridden in subclasses.

Four. Summary

I think in the project development, if the introduction of third-party components, we try to introduce the source code of the component, so that we have an understanding of the structure of the entire component, the implementation of the components we can also be detailed understanding, especially when we are debugging the post is more useful, we can do the breakpoint debugging one by one. The above is a brief introduction to the component, interested can go in-depth understanding and learning.


Cross-platform. NET Mail protocol Mailkit component parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.