Cross-platform. NET mail protocol MailKit component parsing,. netmailkit

Source: Internet
Author: User
Tags rfc822

Cross-platform. NET mail protocol MailKit component parsing,. netmailkit

Initiated. the NET Core open-source organization called on me to speed up the development, and many park friends actively participated in the process. (although some people are sincere at the scene, it should be my old temper, I should have been hospitalized, but fortunately, there are a few people who say yes when doing one thing, and some say that they are using Wuhan to say "eye-catching "),. the NET community is not a person who is not willing to share knowledge, but does not have a complete and good ecological environment. NET is becoming more and more powerful. Here I want to say, "We hope we can make waves, but we are also willing to make small waves before the waves hit ".

I have finished the above. (I can't change this habit if I have to talk about it before I do my work ...)

In the project, for timely communication, data is directly sent to the page, text message notifications are also used, and the mail components I introduced today are also available. Our main task today is to explain that there is a. NET free open-source mail component MailKit. This article will continue to explain the knowledge of related components by combining the underlying code of instances and components. (When recruiting people in the project, I will ask about the underlying principles of. NET. Is there a great God asking me what it means? We cannot write it either. I personally think that the underlying principle of NET is just to handle some program problems well, when coding programs, you can select the most appropriate method to improve performance. Any method has its advantages and disadvantages ,. NET class library code, if we know. NET underlying implementation, we can according. NET underlying implementation, select an appropriate method for optimal performance ).

1. Mailkit component Overview

There are many opportunities to use Email in a project. Generally, emails can be used for a slightly larger project. For.. NET has many mail operation components and methods. Today we will introduce a mail operation component MailKit, which is an open source and free, now let's take a look at the features of this component. MimeKit aims to solve this problem by following MIME specifications as closely as possible, and also provides a very easy-to-use advanced API for programmers.

Components support many client types, such as SMTP client, POP3 client, and IMAP client. This component is a cross-platform Email component that supports platforms such as. NET 4.0,. NET 4.5, Xamarin. Android, Xamarin. iOS, and Windows Phone 8.1. This component provides a MIME parser that features flexible resolution, high performance, and good processing of a variety of broken MIME formatting. The performance of MimeKit is actually equivalent to that of GMime.

This component is highly secure and has many security methods, such as SASL authentication, S/MIME v3.2, OpenPGP, and DKIM signature. The Mailkit component can use CancellationToken to cancel the corresponding operation. The CancellationToken can be used to send a notification that the operation should be canceled. A CancellationToken can be used to enable the thread, between the thread pool work items, or to cancel the cooperation task objects. Creates a cancellation Token by instantiating the CancellationTokenSource object. This object manages the cancellation Token retrieved from its CancellationTokenSource. Token attribute. Then, the cancellation token is passed to any number of threads, tasks, or operations that should receive the cancellation notification. The token cannot be used for start cancellation.

The MailKit component supports asynchronous operations and internally writes classes related to I/O asynchronous operations.

Ii. MailKit instance:

The background and features of the MailKit component are described above. Here we will introduce the simple application of the Email component.

1. Create an email:
Public void SentEmail (string path) {var message = new MimeMessage (); // obtain the address list in the From header and add the specified address message. from. add (new MailboxAddress ("Joey", "joey@friends.com"); // gets the address list in the To header and adds the specified address message. to. add (new MailboxAddress ("Alice", "alice@wonderland.com"); // gets or sets the message topic message. subject = "How you doin? "; // Create 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 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)}; // now create a multipart/mixed container to save the message text and Image attachment var multipart = new Multipart ("mixed") {body, attachment }; // now set multipart/mixed to message body message. body = multipart ;}

It is relatively simple to call this component to send emails and add attachments to emails. The first step is to instantiate the MimeMessage object. After the MimeMessage object is obtained, specify the email address, subject, and other information. Step 2 instantiate the TextPart object and set text information for the object. If you need to ask the attachment of the file created in the mail, you can use the MimePart object, which contains an attachment of the leaf node MIME part of the content (such as the message body text or. Step 4: Create a Multipart object and a mail container for loading text information and attachments after creating the email subject and text and attachment information. Finally, call the MimeMessage. body attribute to obtain or set the message body.

2. email information parsing:
var message = MimeMessage.Load(stream);

We need to parse the mail Information. Here we use the Load method of MimeMessage, which loads MimeKit. MimeMessage from the specified stream. You can use the MimeParser class to load data.

3. Receive Emails:
Public static void HandleMimeEntity (MimeEntity entity) {// MimeEntity is converted to Multipart object 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 and uses recursive traversal of the MIME structure. MIME is the structure of the content, much like a file system. MIME indeed defines a set of common rules for the mail client to explain the tree structure of the MIME part. The Content Disposition Header of is used to provide a prompt to the receiving client. The Content Disposition Header is used as a part of the message body and is intended to be interpreted as an attachment. The other two methods are not introduced.

Iii. Analysis of MailKit core objects

The basic operations of Email are not described too much. It is relatively simple to use this component. Here we will look at the type structure of the component and some core objects. The class library structure is as follows:

1. MimeMessage. Load ():
public static MimeMessage Load (ParserOptions options, Stream stream, bool persistent, 
CancellationToken cancellationToken = default (CancellationToken)) { if (options == null) throw new ArgumentNullException (nameof (options)); if (stream == null) throw new ArgumentNullException (nameof (stream)); var parser = new MimeParser (options, stream, MimeFormat.Entity, persistent); return parser.ParseMessage (cancellationToken); }

This method loads MimeMessage from the specified stream and has six method reloads. This method returns a MimeMessage object. The source code shows that a MimeParser object is created in this method. The MimeParser contains the leaf node MIME part of the content (such as the mail body text or attachment. Call the ParseMessage method to parse the messages 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);                    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) {                            encoding = CharsetUtils.Latin1;                        }                    }                    return encoding.GetString (content, 0, (int) memory.Length);                }            }            set {                SetText (Encoding.UTF8, value);            }        }

This attribute gets the decoded text content. This attribute is a readable and writable attribute. ContentType. Parameters ["charset"] is used to obtain the value of the charset parameter. This method is used to set the parameter value to the data stream and set the corresponding encoding. When we see the exception handling structure, we just want to talk a few simple words ,. NET exceptions are relatively weak and are often written. NET exception is more simple. The above is to capture the exception knowledge, some are not processed, and some are to recover the exception.

3. MimeEntity. WriteTo ():
public virtual void WriteTo (FormatOptions options, Stream stream, bool contentOnly, 
CancellationToken cancellationToken = default (CancellationToken)) { if (options == null) throw new ArgumentNullException (nameof (options)); if (stream == null) throw new ArgumentNullException (nameof (stream)); if (!contentOnly) Headers.WriteTo (options, stream, cancellationToken); }

This method writes MimeEntity to the specified data stream. This method accepts the options format option. Stream output data stream. contentOnly determines whether data can be written. This method is defined as a virtual method. After inheriting this method, you can override this method in the subclass.

Iv. Summary

I think that if a third-party component is introduced in project development, we should try to introduce the source code of the component. In this way, we have an understanding of the entire component structure, we can also have a detailed understanding of the implementation of components, especially when debugging is performed, we can perform breakpoint debugging one by one. The above is a brief introduction to this component. If you are interested, you can go deep into and learn.

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.