POP收邮件方法

来源:互联网 发布:mac 所有软件打不开 编辑:程序博客网 时间:2024/04/29 04:55
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
        }
原创粉丝点击