Bootstrap

(七)电子邮件模块(使用Jmail接收邮件,sql server2014)

我设计了一个简单的表,它有 5个字段。

 id int identity(1,1)  primary key not null, identity(1,1)  primary key not null,//编号,自增,主键

sendmail varchar(50) not null,//发件人

mailtitle varchar(100) not null,//邮件主题

mailcontents varchar(5000)  null,//正文

mailtime date not null,//时间

idu varchar(50) not null,//邮件uid

att varchar(50) null,//附件路径

首先我们需要将数据库里的内容绑定在我们的gridview上,然后将它显示出来。这里我们使用代码将gridview和数据库绑定。后面接收邮件后还需再绑定一次数据库,gridview界面可以刷新。

private void showmail()
        {
            string con=ConfigurationManager.ConnectionStrings["jmailConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(con);
            connection.Open();
            String str = "select *from tb_JMail order by id desc";         
            SqlDataAdapter ad = new SqlDataAdapter(str, connection);
             DataSet adds = new DataSet();
             ad.Fill(adds);
             if (adds.Tables[0].Rows.Count > 0)
             {
                 GridView1.DataSource = adds;
                 GridView1.DataKeyNames = new string[] { "id" };
                 GridView1.DataBind();
             }
             connection.Close();     
        }

然后我们还需要将gridview改造一下,当我们点击它某一行时,会改变颜色和鼠标形状。jmailrecieve.aspx.cs一部分代码如下

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            int i;
            //执行循环,保证每条数据都可以更新
            for (i = 0; i < GridView1.Rows.Count + 1; i++)
            {
                //首先判断是否是数据行
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //当鼠标停留时更改背景色和鼠标形状
                    e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#5FB878';this.style.cursor='pointer'");
                    //当鼠标移开时还原背景色
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                }
            }
            PostBackOptions myPostBackOptions = new PostBackOptions(this);
            myPostBackOptions.AutoPostBack = false;
            myPostBackOptions.RequiresJavaScriptProtocol = true;
            myPostBackOptions.PerformValidation = false;
            String evt = Page.ClientScript.GetPostBackClientHyperlink(sender as GridView, "Select$" + e.Row.RowIndex.ToString());
            e.Row.Attributes.Add("onclick", evt);
        }
    }

写了这个事件会出现回发或回调参数无效 的问题,所以需要在配置文件中system.web节点加入<pages validateRequest="false"  enableEventValidation="false"/>

  我们还需要做到点击这一行可以查看该邮件的内容。

 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("email.aspx?id=" + this.GridView1.SelectedDataKey["id"].ToString());      }

上面的代码把邮件的id传了出来,然后我们在email.aspx.cs中就可以根据id值取读取数据库各个字段的内容。

显示发件人,主题,时间,正文,附件地址

下面开始我们最重要的内容,接收邮件

namespace email
{
    public partial class email : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String id = Request.Params["id"];
            String str = ConfigurationManager.ConnectionStrings["jmailConnectionString"].ConnectionString.ToString();
            SqlConnection connection=new SqlConnection(str);
            connection.Open();
            SqlCommand com = new SqlCommand("select mailtitle,sendmail,mailtime,mailcontents,att from tb_JMail where id="+Request.Params["id"], connection);
            SqlDataReader read = com.ExecuteReader();
            while (read.Read()==true)
            {
                Label1.Text = read["mailtitle"].ToString();
                Label2.Text = read["sendmail"].ToString();
                Label3.Text = read["mailtime"].ToString().Substring(0,9); 
                if (!read["mailcontents"].ToString().Equals(String.Empty))
                {
                    Label4.Text = read["mailcontents"].ToString();
                    Label4.Visible = true;
                }
                if (!read["att"].ToString().Equals(String.Empty))
                {
                    Label6.Text= read["att"].ToString();       
                    Label5.Visible = true;
                }
            }
            read.Close();
            connection.Close();
        }
    }
}

首先界面是这样的

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
                   使用jmail接收邮件<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">接收邮件</asp:LinkButton>            
                   
    </div>
                    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"  DataKeyNames="id"  PageSize="18" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" CellPadding="4" ForeColor="#333333" GridLines="None">
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"  />
                            <asp:BoundField DataField="sendmail" HeaderText="sendmail" />
                            <asp:BoundField DataField="mailtitle" HeaderText="mailtitle"/>
                            <asp:TemplateField HeaderText="mailcontents">                              
                                <ItemTemplate>
                                    <asp:Label ID="Label1" runat="server" Text='<%# MyContent((string)Eval("mailcontents"))%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="mailtime" HeaderText="mailtime" DataFormatString="{0:d}" />
                        </Columns>
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                    </asp:GridView>
    </form>
</body>
</html>

然后我们接收文件,需要写linkbuton的点击事件

protected void LinkButton1_Click(object sender, EventArgs e)
        {
            POP3Class popmails=new POP3Class();//建立接收邮箱的对象
            Message mailMessage;//邮箱信息接口
            try{
            string str = ConfigurationManager.ConnectionStrings["jmailConnectionString"].ConnectionString.ToString();
            SqlConnection con = new SqlConnection(str);
            con.Open();
            popmails.Connect("[email protected]", "xqqx09487", "pop.163.com",110);//链接邮箱服务  参数用户名,密码,服务器地址,端口
            if(popmails.Count>0)
                {
                  for(int i=1;i<popmails.Count;i++)
                   {
                    string theUid = popmails.GetMessageUID(i);
                    mailMessage = popmails.Messages[i];//获得一条邮件信息                 
                    if(!getLocalUID(theUid))
                      {
                   String s =null;
                   Attachments attachments = mailMessage.Attachments;      //建立附件集接口
         
                    for (int j = 0; j < attachments.Count; j++)         
                      {              //根据索引取附件

                          Attachment attachment = attachments[j];             //附件名
                          string fileName = attachment.Name;              //附件保存在指定路径,不要有同名文件,否则出异常
                          string road = Server.MapPath("/recieveatt/") + fileName;
                          attachment.SaveToFile(road);
                          s = road + "  ";
                        } 
                        string insert = "insert into tb_JMail(sendmail,mailtitle,mailcontents,mailtime,idu,att) values('"+ DecodeStr(mailMessage.From) + " " + "','" + DecodeStr(mailMessage.Headers.GetHeader("Subject")) + "','" + mailMessage.Body + "','" + mailMessage.Date.ToString("yyyy-MM-dd") + "','" + theUid +"','"+s+"')";                       
                        SqlCommand com = new SqlCommand(insert, con);
                        com.ExecuteNonQuery();
                      }                     
                    }
                }
            showmail();
            con.Close();
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

我们通过popmails.GetMessageUID(i)来判断数据库里有没有该文件public Boolean getLocalUID(string n)//通过uid判断数据库有没有该邮件   

 {
            string str = ConfigurationManager.ConnectionStrings["jmailConnectionString"].ConnectionString.ToString();
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand com = new SqlCommand("select * from tb_JMail where uid='"+n+"'", con);
            SqlDataReader rd = com.ExecuteReader();
            while (rd.Read() == true)
            {
                return true;
            }
            return false;
        }

虽然写好了,但是运行的时候出现了this function is not included in this version of jmail. 这个问题好像是由于jmail免费版本。解决方案是换一个jmail组件,我去下了个4.5版本的组件,JMail需要注册,大家可以根据dll的路径改.bat文件,.dll和.bat都在我的文件夹下,里面还有不同版本的jmail组件。

程序还会出现乱码,如果发件人是mailMessage.From,调试的时候会发现有时候发件人,主题会是这样      jmail.IMessage.From.get 返回 "=?utf-8?b?572R5piT5ri45oiPPHl4MTYzQHNlcnZpY2UubmV0ZWFzZS5jb20+?=" string,网页上会变成


然后我们需要写一个函数解决它

public string DecodeStr(string str)
        {
            Boolean flag=false;
            String[] code = { "UTF-8", "GB2312", "ISO-2022-JP","GB18030"};//添加编码
            string result = "";
            if (!str.Equals(String.Empty))
            {
                for (int i = 0; i < code.Length; i++)
                {
                    if (str.ToUpper().Contains(code[i]))
                    {
                        String[] array = str.Split('?');
                        if (array.Length > 2)
                        {
                            string title = array[3];
                            byte[] bytes = Convert.FromBase64CharArray(title.ToCharArray(), 0, title.ToCharArray().Length);
                            Encoding en = Encoding.GetEncoding(code[i].ToLower());
                            result = en.GetString(bytes);
                            return result;
                        }
                        flag = false;
                    }                                       
                }
                 if(!flag)
                     return str;
            }
            return "";
        }



在获取正文内容的时候,只能获取有文字的,图片什么的不能获取。

jmailrecieve先运行,然后跳转到email

https://github.com/1126048156/email.git


;