天天看點

利用ASP.NET自帶System.Net.Mail發郵件和Jmail接收郵件

.net中自帶了可以發郵件的,但是如果要是收郵件的話,則需要第三方元件如JMail或是别的元件,下面簡單介紹下發送郵件代碼:

protected void send_Click(object sender, EventArgs e)

        {

            sendata = sendtarget.Value;

            title = sendtitle.Text;

            content = sendcontent.Text;

            //-------------------郵件發送部分-----------------------------------

            TimeFilename = System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();

            Filename = "mail" + TimeFilename + ".txt";

            Filepath= Server.MapPath(".")+"//faxlistfile//";

            FileTotalpath=Filepath+Filename;

            //-----------------------附件上傳并儲存-------------------------

            if (this.sendfileupload.PostedFile.FileName != "")

            {

                try

                {

                    strSaveDir = "//fileupload//";

                    strName = sendfileupload.PostedFile.FileName;

                    //取得檔案名(抱括路徑)裡最後一個"."的索引

                    int intExt = strName.LastIndexOf(".");

                    //取得檔案擴充名

                    strExt = strName.Substring(intExt);

                    //取得檔案名(包括路徑)裡最後一個"/"的索引

                    int intPath = strName.LastIndexOf("//");

                    //取得檔案名(不包括路徑)

                    Random objRand = new Random();

                    System.DateTime date = DateTime.Now;

                    //生成随機檔案名

                    string strFile = strName.Substring(intPath);

                    string str = strFile.Substring(1,strFile.LastIndexOf(".")-1);

                    string saveName = System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);

                    strNewName =str +"("+ saveName +")"+ strExt;//取新名字,防止重複

                    //儲存檔案到你所要的目錄,這裡是IIS根目錄下的fileupload目錄.你可以改變.

                    //注意: 我這裡用Server.MapPath()取目前檔案的絕對目錄.在asp.net裡"/"必須用"//"代替

                    strPath = Server.MapPath(".") + strSaveDir + strNewName;

                    //strPath = Server.MapPath(strSaveDir + strNewName);

                    sendfileupload.PostedFile.SaveAs(strPath);

                }

                catch

                {

                    Response.Write("<script language='javascript'>alert('請重新加載附件!');localtion='javascript:history.go(-1)'</script>");

                }

            }

            //------------------------END--------------------------------

            MailContent = commonfunction.getstringlist(sendata, 3);

            //MailFaxContent = commonfunction.getstringlist(sendata,4);

            MailNo = commonfunction.getstringlist(sendata, 1);

            MailUser = commonfunction.getstringlist(sendata, 2);

            commonfunction.buildDatafile(FileTotalpath,MailContent);

            //Attachment attach = new Attachment(FileTotalpath);

            MailTitle = "ADDRESS-LIST=" + Filename;

            MailAddress = System.Configuration.ConfigurationManager.AppSettings.Get("MailAddress");

            MailFrom = System.Configuration.ConfigurationManager.AppSettings.Get("MailFrom");

            POPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("POPAddress");

            STMPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("STMPAddress");

            MailUsername = System.Configuration.ConfigurationManager.AppSettings.Get("MailUsername");

            MailPass = System.Configuration.ConfigurationManager.AppSettings.Get("MailPass");

            MailMessage newmail = new MailMessage(MailFrom, MailAddress);

            newmail.Subject = MailTitle;

            newmail.Body = content;

            newmail.IsBodyHtml = false;

            if (!(sendfileupload.PostedFile.FileName).Equals(""))

            {

                try

                {

                    newmail.Attachments.Add(new Attachment(strPath));

                }

                catch

                {

                    Response.Redirect("sendupfileerror.htm");

                }

            }

            newmail.Attachments.Add(new Attachment(FileTotalpath));

            SmtpClient sc = new SmtpClient(STMPAddress);

            try

            {

                sc.Send(newmail);

            }

            catch (Exception) {

                newmail.Dispose();

                commonfunction.delDatafile(FileTotalpath);

                commonfunction.delDatafile(strPath);

                Response.Redirect("senderror.htm");          

            }

            newmail.Dispose();

            commonfunction.delDatafile(FileTotalpath);

            //------------------------END-----------------------------------

            //-----------------------更新到資料庫中-------------------------

            SqlConnection conn = sqlconn.CreateConn();

            SqlDataAdapter da = new SqlDataAdapter("select * from sendfax", conn);

            DataSet ds = new DataSet();

            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            for (int i=0;i<MailContent.Length;i++)

            {

                DataRow dr =dt.NewRow();

                dr["faxno"]=MailNo[i];

                dr["sendname"] = MailUser[i];

                dr["title"]= title;

                dr["content"]= content;

                dr["sendtime"] = System.DateTime.Now.ToString();

                dr["sendtag"] = "1";

                dr["attachment"] = strNewName;

                dt.Rows.Add(dr);

            }

            //ds.AcceptChanges();

            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);

            da.Update(dt);

            dt.AcceptChanges();

            conn.Close();

            Response.Redirect("sendsuccess.htm");

        } 

可發送後,我們在收郵件這塊其實大家有好多人存在問題,我在做這塊時也出現過,但是漫漫的來解決吧!

我們在看如下的收郵件代碼:導入如下空間

using System.Data.SqlClient;

using faxapp.dataconn;

using faxapp.common;

using System.Net.Sockets;

using jmail;

using System.IO;

收郵件完整代碼:

 public void ReceiveMails()

        {

            jmail.Message Msg = new jmail.Message();

            jmail.POP3 jpop = new jmail.POP3();

            jmail.Attachments atts;

            jmail.Attachment att;

            //Mime m = new Mime();

            //username為使用者名,該方法通過使用者名擷取該使用者的pop設定,即使用者的POP使用者名,密碼,POP伺服器位址以及端口号這四個參數,這四個參數是連接配接POP伺服器的必用參數.

            //SqlDataReader dataReader = this.ExtGetSetting(Username);

            //if (dataReader.Read())

            //{

            //    if (dataReader["PopServer"].ToString() != "" && dataReader["PopUsername"].ToString() != "")

            //    {

                    //連接配接POP伺服器

            MailAddress = System.Configuration.ConfigurationManager.AppSettings.Get("MailAddress");

            MailFrom = System.Configuration.ConfigurationManager.AppSettings.Get("MailFrom");

            POPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("POPAddress");

            STMPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("STMPAddress");

            MailUsername = System.Configuration.ConfigurationManager.AppSettings.Get("MailUsername");

            MailPass = System.Configuration.ConfigurationManager.AppSettings.Get("MailPass");

            Mailpassword=System.Configuration.ConfigurationManager.AppSettings.Get("Mailpassword");

            string mailPopPort = System.Configuration.ConfigurationManager.AppSettings.Get("MailPopPort");

            MailPopPort = Convert.ToInt32(mailPopPort);

            jpop.Connect(MailUsername, Mailpassword, POPAddress, MailPopPort);

            //如果伺服器上有郵件

            if (jpop.Count >= 1)

            {

                for (int i = 1; i <= jpop.Count; i++)

                {

                    Msg = jpop.Messages[i];

                    atts = Msg.Attachments;

                    //取資料庫中郵件資訊中的最大發送時間,即最近接收到的一封郵件的時間

                    DataTable data = this.GetDataTable("select max(accepttime) from acceptfax where sendtag='1'");

                    //對伺服器上的郵件的發送時間和資料庫最近一封郵件的時間進行比較,如果大那麼證明該郵件還未被收取,是一封新郵件,這樣避免重複收取郵件入庫

                    if (Msg.Date > Convert.ToDateTime(data.Rows[0][4].ToString()))

                    {

                        //将這封新郵件的資訊儲存到資料庫

                        //this.SaveExtMail(Msg, Username, dataReader["Email"].ToString(), jpop.GetMessageUID(i));

                        this.SaveExtMail(Msg.FromName, Msg.Subject, Msg.Body, Msg.Date.ToLongDateString());

                        //擷取附件上傳到伺服器并且将資訊存入資料庫

                        if (atts.Count >= 1)

                        {

                            for (int k = 0; k < atts.Count; k++)

                            {

                                att = atts[k];//獲得附件

                                string attname = att.Name;

                                try

                                {

                                    //Random TempNameInt = new Random();

                                    //string NewMailDirName = TempNameInt.Next(100000000).ToString();

                                    //生成随機檔案字尾名

                                    string strSaveDir = "//AttachFiles//";

                                    //取得檔案名(抱括路徑)裡最後一個"."的索引

                                    int intExt = attname.LastIndexOf(".");

                                    //取得檔案擴充名

                                    string strExt = attname.Substring(intExt);

                                    //取得檔案名(不包括路徑)

                                    Random objRand = new Random();

                                    System.DateTime date = DateTime.Now;

                                    //生成随機檔案名

                                    string str = attname.Substring(1, attname.LastIndexOf(".") - 1);

                                    string saveName = System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);

                                    string strNewName = str + "(" + saveName + ")" + strExt;//取新名字,防止重複

                                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(".") + "//AttachFiles//" + strNewName);

                                    string mailPath = strSaveDir + strNewName;

                                    att.SaveToFile(System.Web.HttpContext.Current.Server.MapPath(".") + mailPath);

                                    //擷取該封郵件在資料庫的ID,以便和附件資訊相對應,取郵件表中的最大ID即可

                                    int mailID = this.GetMailID();

                                    将附件資訊存入資料庫

                                    this.AttExtSend(mailID, attname, att.Size, mailPath, Msg.From);

                                }

                                catch (Exception ex)

                                {

                                    throw new Exception(ex.Message);

                                }

                            }

                        }

                    }

                }

            }

            //删除伺服器上的郵件

            jpop.DeleteMessages();

            //斷開連接配接   

            jpop.Disconnect();

            //    }

            //}

        }

        //取資料庫中郵件某個條件下的某條資訊

        public DataTable GetDataTable(string sqlstr)

        {

            SqlConnection conn = sqlconn.CreateConn();

            SqlDataAdapter da = new SqlDataAdapter(sqlstr , conn);

            DataSet ds = new DataSet();

            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            dt.AcceptChanges();

            conn.Close();

            return dt;

        }

        //将新郵件的資訊儲存到資料庫acceptfax表中

        public void SaveExtMail(string FromName, string Subject, string Body, string Date)

        {

            //-----------------------更新到資料庫中-------------------------

            SqlConnection conn = sqlconn.CreateConn();

            SqlDataAdapter da = new SqlDataAdapter("select * from acceptfax", conn);

            DataSet ds = new DataSet();

            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            DataRow dr = dt.NewRow();

            dr["faxno"] = FromName;

            dr["title"] = Subject;

            dr["content"] = Body;

            dr["accepttime"] = Date;

            dt.Rows.Add(dr);

            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);

            da.Update(dt);

            dt.AcceptChanges();

            conn.Close();

        }

        //擷取該郵件的在資料庫中的ID号,便與和附件相對應

        public int GetMailID()

        {

            //取資料庫中郵件資訊中的最大發送時間,即最近接收到的一封郵件的時間,得到該郵件sid号

            DataTable data = this.GetDataTable("select max(accepttime) from acceptfax where sendtag='1'");

            int result = Convert.ToInt32(data.Rows[0][0].ToString());

            return result;

        }

        //把每個附件的内容更新入資料庫

        public void AttExtSend(int mailID,string attname,int Size,string mailpath,string format)

        {

            //-----------------------更新到資料庫中-------------------------

            SqlConnection conn = sqlconn.CreateConn();

            SqlDataAdapter da = new SqlDataAdapter("select * from attachmentInfo", conn);

            DataSet ds = new DataSet();

            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            DataRow dr = dt.NewRow();

            dr["mailID"] = mailID;

            dr["attname"] = attname;

            dr["attsize"] = Size;

            dr["mailpath"] = mailpath;

            dr["format"] = format;

            dt.Rows.Add(dr);

            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);

            da.Update(dt);

            dt.AcceptChanges();

            conn.Close();

        }

希望大家互相交流!