POP收郵件方法

private void ReceivEmail(MailAccount mailAccount)
        {
            #region 開始獲取郵件


            #region 獲取賬號信息
            MailAccountManage mam = new MailAccountManage();
            DataTable tb = mam.GetTable(mailAccount.id);
            strlogin = tb.Rows[0]["EmailAccount"].ToString();
            strpassword = mailAccount.EmailPass;


            pophost = tb.Rows[0]["PopHost"].ToString();
            intport = Convert.ToInt32(tb.Rows[0]["PopPort"]);
            if (Convert.ToBoolean(tb.Rows[0]["PopSSL"]) == true)
                pop3usessl = true;
            else
                pop3usessl = false;
            #endregion


            using (POP3_Client pop3 = new POP3_Client())
            {
                try
                {
                    #region 與服務器進行身份驗證
                    //與pop3服務器建立連接
                    pop3.Connect(pophost, intport, pop3usessl);
                    //驗證身份,郵件如果太多,建議及時清理郵箱
                    pop3.Authenticate(strlogin, strpassword, false);
                    #endregion


                    #region  獲得郵件基礎信息列表
                    //獲取郵件信息列表
                    POP3_ClientMessageCollection infos = pop3.Messages;
                    #endregion


                    #region  臨時處理--僅僅允許查看最開始的100條記錄
                    int endNums = 0;
                    if (infos.Count > 1000)
                        endNums = infos.Count - 1000;
                    #endregion


                    for (int index = infos.Count - 1; index > endNums; index--)
                    {


                        #region 判斷郵件是否在數據庫中已經存在
                        POP3_ClientMessage info = infos[index];
                        //每封email會有一個在pop3服務器範圍內唯一的id,檢查這個id是否存在就可以知道以前有沒有接收過這封郵件
                        if (mM.JudgeEmailHasDownload(info.UID))
                            continue;
                        #endregion


                        #region 獲取這封郵件的內容
                        //獲取這封郵件的內容
                        byte[] bytes;
                        try
                        {
                            bytes = info.MessageToByte();
                        }
                        catch (Exception ex)
                        {
                            WriteLog("郵箱[" + strlogin + "]收取郵件裏獲取內容時發生錯誤!錯誤信息:[" + ex.ToString() + "]");
                            continue;
                        }
                        #endregion


                        #region  解析郵件內容並存入數據庫中
                        Mail curMail = new Mail();
                        //解析從pop3服務器發送過來的郵件信息
                        Mime m;
                        try
                        {
                            m = Mime.Parse(bytes);
                        }
                        catch (Exception ex)
                        {
                            WriteLog("郵箱[" + strlogin + "]收取郵件解析郵件內容時發生錯誤!錯誤信息:[" + ex.ToString() + "]");
                            continue;
                        }
                        #endregion


                        int insertMailID = 0;


                        if (m != null)
                        {
                            #region  解析郵件內容並存入數據庫中
                            string mailfrom = "";
                            string mailfromname = "";
                            if (m.MainEntity.From != null)
                            {
                                for (int i = 0; i < m.MainEntity.From.Mailboxes.Length; i++)
                                {
                                    if (i == 0)
                                    {
                                        mailfrom = (m.MainEntity.From).Mailboxes[i].EmailAddress;
                                    }
                                    else
                                    {
                                        mailfrom += string.Format(",{0}", (m.MainEntity.From).Mailboxes[i].EmailAddress);
                                    }
                                    mailfromname = (m.MainEntity.From).Mailboxes[0].DisplayName != ""
                                                       ? (m.MainEntity.From).Mailboxes[0].DisplayName
                                                       : (m.MainEntity.From).Mailboxes[0].LocalPart;
                                }
                            }
                            string mailto = "";
                            string mailtotocollection = "";
                            if (m.MainEntity.To != null)
                            {
                                mailtotocollection = m.MainEntity.To.ToAddressListString();


                                for (int i = 0; i < m.MainEntity.To.Mailboxes.Length; i++)
                                {
                                    if (i == 0)
                                    {
                                        mailto = (m.MainEntity.To).Mailboxes[i].EmailAddress;
                                    }
                                    else
                                    {
                                        mailto += string.Format(",{0}", (m.MainEntity.To).Mailboxes[i].EmailAddress);
                                    }


                                }
                            }
                            curMail.MailUID = info.UID;
                            curMail.Title = m.MainEntity.Subject;
                            curMail.FromAddress = mailfrom;
                            curMail.ToAddress = strlogin;
                            //if (m.MainEntity.To == null)
                            //    curMail.ToAddress = strlogin;
                            //else
                            //    curMail.ToAddress = m.MainEntity.To.Mailboxes[0].EmailAddress;
                            if (m.MainEntity.Date.Year < 1753)
                                curMail.SenderDate = DateTime.Now;
                            else
                                curMail.SenderDate = m.MainEntity.Date;
                            curMail.Content = m.MimeEntities.Length;
                            if (m.BodyHtml != null)
                            {
                                curMail.Body = m.BodyHtml;
                                curMail.HTMLFormat = true;
                            }
                            else
                            {
                                curMail.Body = m.BodyText;
                                curMail.HTMLFormat = false;
                            }
                            if (m.Attachments.Length > 0)
                            {
                                curMail.AttachmentFlag = true;
                            }
                            curMail.ReaderFlag = false;
                            curMail.ReplyFlag = false;
                            curMail.FolderID = 1;
                            curMail.MailAccountId = Convert.ToInt32(tb.Rows[0]["id"]);
                            curMail.MailType = true;
                            insertMailID = mM.AddModif(curMail, true);
                            #endregion
                        }
                        if (insertMailID != -1)
                        {
                            #region  成功插入數據庫後再獲取附件
                            Attachments curAttchment = new Attachments();
                            //獲取附件
                            foreach (MimeEntity entry in m.Attachments)
                            {
                                string attchmentFilename = entry.ContentDisposition_FileName; //獲取文件名稱
                                if (attchmentFilename == null || attchmentFilename == "")
                                    continue;
                                //存儲在服務器上的文件,避免名字衝突,採用格式化的命名規則
                                string serverFileName = DateTime.Now.ToString("yyyyMMddhhmmss ") + "." + GetExt(attchmentFilename);
                                string serverPhysicalPath = Config.ServerPhysicalPath;
                                string serverAttachmentsFloder = Config.ServerAttachmentsFloder; 
                                string serverFileFloder = DateTime.Now.ToString("yyyyMM");  //存儲到服務器上的文件夾
                                string serverFilePath = serverPhysicalPath + serverAttachmentsFloder + "\\" + serverFileFloder + "\\" + serverFileName;
                                //判斷存儲附件目錄是否存在
                                if (!File.Exists(serverPhysicalPath + serverAttachmentsFloder))
                                {
                                    try
                                    {
                                        Directory.CreateDirectory(serverPhysicalPath + serverAttachmentsFloder);
                                    }
                                    catch (Exception excreat)
                                    {
                                        WriteLog("郵箱[" + strlogin + "]創建附件目錄時出錯!錯誤信息:[" + excreat.ToString() + "]");
                                    }
                                }
                                //判斷存儲當前郵件的目錄是否存在
                                if (!File.Exists(serverPhysicalPath + serverAttachmentsFloder + "\\" + serverFileFloder))
                                {
                                    try
                                    {
                                        Directory.CreateDirectory(serverPhysicalPath + serverAttachmentsFloder + "\\" + serverFileFloder);
                                    }
                                    catch (Exception excreat)
                                    {
                                        WriteLog("郵箱[" + strlogin + "]創建附件目錄時出錯!錯誤信息:[" + excreat.ToString() + "]");
                                    }
                                }
                                byte[] data = entry.Data;
                                try
                                {
                                    FileStream pfilestream = null;
                                    pfilestream = new FileStream(serverFilePath, FileMode.Create);
                                    pfilestream.Write(data, 0, data.Length);
                                    pfilestream.Close();
                                }
                                catch (Exception excreat)
                                {
                                    WriteLog("郵箱[" + strlogin + "]創建附件時出錯!錯誤信息:[" + excreat.ToString() + "]");
                                }
                                curAttchment.MailID = insertMailID;
                                curAttchment.Url = serverAttachmentsFloder + "/" + serverFileFloder + "/" + serverFileName;
                                curAttchment.Name = attchmentFilename;
                                curAttchment.Content = entry.Data.Length;
                                curAttchment.Type = GetExt(attchmentFilename);
                                AttachmentsManage aM = new AttachmentsManage();
                                aM.AddModif(curAttchment, true);
                            }
                            #endregion
                        }
                    }
                    //WriteLog("接收郵件完成,共接收了郵件" + mailcount + ",完成時間爲:【" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss ") + "】");
                }
                catch (POP3_ClientException ex)
                {
                    WriteLog("郵箱[" + strlogin + "]接收失敗!錯誤信息:[" + ex.ToString() + "]");
                }
                pop3.Dispose();
            }


            #endregion
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章