Based on lumisoft Net component, using IMAP protocol to receive mail

Lumisoft has been used in the early days Net component to process and find e-mail, which is very convenient for e-mail processing< Based on lumisoft Net component >It also introduces the mail sending and receiving processing based on POP3 and SMPT. Generally, the mail server supports POP3 very well. There is no problem with testing multiple servers in routine use, so there is little research on the processing of IMAP protocol. This essay expands the processing of IMAP protocol based on the requirements of the original POP3.

1. Create IMAP receiving auxiliary class

In order to facilitate the processing of receiving IMAP mail, we create an imapahelper and pass in some relevant parameters to encapsulate the processing operation of receiving mail.

As shown in the following auxiliary classes, enter the server domain name, address, port, whether SSL, user name and password.

 

 

Next, we need to connect to the server and try to get the authorization information. If we pass, we can get the mail information in the next step, as shown in the following code.

        /// <summary>
        /// Receive mail operation
        /// </summary>
        public void Receive()
        {
            using (var client = new IMAP_Client())
            {
                //Create log processing
                client.Logger = new Logger();
                client.Logger.WriteLog += new EventHandler<WriteLogEventArgs>(WriteLog);//Response record display

                //Use the account and password to connect to the server
                client.Connect(server, port, useSsl);
                //Login to obtain authorization
                client.Login(username, password);
                //var identity = client.AuthenticatedUserIdentity;

                //Get the summary information of each mailbox directory
                client.GetFolders(null).ToList().ForEach(f =>
                {

                    Console.WriteLine(f.FolderName);
                    var s = client.FolderStatus(f.FolderName);
                    s.ToList().ForEach(sIt =>
                    {
                        Console.WriteLine("total:{0},Unread:{1},lately{2}", sIt.MessagesCount, sIt.MessagesCount, sIt.UnseenCount);
                    });

                });

After we log in and get authorization, we test and obtain the summary email information of each directory, such as the total number of emails, the number of unread emails, etc.

Then select the specific mailbox directory, set the content format of the returned information, and return the mail with serial number from the server, as shown in the following code.

    //Select mailbox
    client.SelectFolder("INBOX");
    //First, make sure to take the second x To the first n Email,"1:*"Indicates the first to last letter
    var seqSet = IMAP_t_SeqSet.Parse("1:*");
    var items = new IMAP_t_Fetch_i[]
    {
        new IMAP_t_Fetch_i_Envelope(),  //E-mail title, body and other information
        new IMAP_t_Fetch_i_Uid(),       //Returns the of the message UID number, UID Number is a number that uniquely identifies the message
        new IMAP_t_Fetch_i_Flags(),     //The flag of this message should be read or unread
        new IMAP_t_Fetch_i_InternalDate(),//It seems to be the date of receipt
        new IMAP_t_Fetch_i_Rfc822()     //Rfc822 It is a standard mail data flow, which can be accessed through Lumisoft.Net.Mail.Mail_Message Object resolves all the information of the message
    };

Then we pass in the condition and give it a callback anonymous function to process the relevant mail information, as shown below.

    //Fetch First parameter false Time seqSet Effective
    client.Fetch(false, seqSet, items, (s, e) =>
    {
        //Anonymous function content for handling mail
    });

Then we deal with the conversion of mail information, and convert mail information into mail_ The information of the message object, which contains the header information, body, and attachment information related to the message.

   var email = e.Value as IMAP_r_u_Fetch;
    if (email.Rfc822 != null)
    {
        email.Rfc822.Stream.Position = 0;
        var mime_message = Mail_Message.ParseFromStream(email.Rfc822.Stream);
        email.Rfc822.Stream.Close();

The information we need to write to the database can be further converted into the information we need to store in the database.

    receiveInfo.ReceivedDate = DateTime.Now;//Receive local time
    receiveInfo.Company_ID = this.companyId;
    receiveInfo.User_ID = this.userId;
    receiveInfo.Email = this.email;//receive Email account number
    receiveInfo.MailConfig_ID = this.mailConfig_ID;//receive Email Account configuration record ID

    //Each Email There will be one in Pop3 Unique within the scope of the server Id,Check this Id If it exists, you can know whether you have received this email before
    receiveInfo.MailUid = email.UID.UID.ToString();

    try
    {
        //May appear[ LumiSoft.Net.ParseException: Header field 'Date' parsing failed]Abnormal error.
        receiveInfo.SendDate = mime_message.Date;
    }
    catch (Exception ex)
    {
        receiveInfo.SendDate = Convert.ToDateTime("1900-1-1");//Wrong assignment of a date
        error = string.Format("To convert messages Date error:account number{0} Email Title:{1}", username, mime_message.Subject);
        LogTextHelper.Error(error, ex);
    }

    //There may be garbled code, which can be converted by function
    receiveInfo.Title = mime_message.Subject;//DecodeString(mime_header.Subject);

    receiveInfo.MailBody = mime_message.BodyText;
    try
    {
        if (!string.IsNullOrEmpty(mime_message.BodyHtmlText))
        {
            receiveInfo.MailBody = mime_message.BodyHtmlText;
        }
    }
    catch
    {
        //There is an error in the shielding code. The error is BodyText Exist and BodyHtmlText When it does not exist, access BodyHtmlText Will appear
    }

Write to the database for processing, and call our general processing class to process the storage of data information.

    #region Write mail information to database
    int mailId = -1;
    try
    {
        mailId = BLLFactory<MailReceive>.Instance.Insert2(receiveInfo);
    }
    catch (Exception ex)
    {
        error = string.Format("Error writing mail information to database:account number{0}  Email Title:{1}", username, mime_message.Subject);
        LogTextHelper.Error(error, ex);
    }

    if (mailId <= 0) return; //If the message is not saved, do not save the attachment 
    #endregion

2. Attachment handling of mail

E-mail attachments include regular e-mail attachments and attachment pictures embedded in the text. Therefore, different types of judgments need to be made, and the attachments should be obtained and stored together, so that the relevant attachments can be displayed normally when displayed.

Where mail_ The message object has a function that can get the information of all these two types of attachments into the list.

public MIME_Entity[] GetAttachments(bool includeInline, bool includeEmbbedMessage)

In this way, we can call this function, and then extract and store the attachment.

    #region Email attachment content
    foreach (var entity in mime_message.GetAttachments(true, true))
    {
        string fileName = "";

        #region Determine whether it is an ordinary attachment or an embedded content attachment
        if (entity.ContentDisposition != null &&
            entity.ContentDisposition.DispositionType == MIME_DispositionTypes.Attachment)
        {
            Console.WriteLine("Attachment: " + entity.ContentDisposition.Param_FileName);
            fileName = entity.ContentDisposition.Param_FileName;
        }
        else
        {
            string cid = entity.ContentID.Substring(1, entity.ContentID.Length - 2);
            if (entity.ContentType.Param_Name != null &&
                mime_message.BodyHtmlText.Contains(string.Format("cid:{0}", cid)))
            {
                Console.WriteLine("Embeded image: " + cid);
                fileName = cid;
            }
            else
            {
                Console.WriteLine("Unknown attachment.");
            }
        }

The attachment information of the message, and the entity object needs to be converted to mime_ b_ Processing by singlebase.

 var byteObj = entity.Body as MIME_b_SinglepartBase;

Therefore, we can store its byte data in file mode, as shown below.

File.WriteAllBytes(filename, byteObj.Data);

Or call the attachment information for storage and processing (local storage, FTP upload, etc.)

 

 

For example, for testing emails with embedded pictures and attachment information, such processing can successfully obtain all attachment information.

 

Therefore, the processing of sending and receiving mail regularly in the mail management module can be used to realize the receiving and sending of mail.

 

 

3. 163 mailbox does not support IMAP protocol

When testing the IMAP protocol to receive mail, it is found that most mailboxes support POP3.

However, although mailbox 163 supports POP3 well, it does not support IMAP protocol. They all use the authorization code to log in, and the login is indeed successful. However, when switching mailboxes for mail collection under IMAP protocol, they will be prompted

Prompt error message.

 

  00023 NO SELECT Unsafe Login. Please contact kefu@188.com for help

 

If you are interested, learn about lumisoft Net component, please refer to my relevant essays, thank you.

Based on lumisoft Net components and NET API to realize mail sending function>

<Based on lumisoft Net>

<Based on lumisoft Net component development meets some problems such as garbled code>

<Based on lumisoft Net component>

<Operation instructions of mail collection and delivery software>

<Operation interface design and phased summary of mail receiving and sending function module>

Added by jovanross on Mon, 07 Mar 2022 08:14:52 +0200