利用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();
        }

希望大家互相交流!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值