C#Mail:为什么这个功能无法发送电子邮件? [英] C# Mail: why this function cannot send emails?

查看:82
本文介绍了C#Mail:为什么这个功能无法发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基于Web的ASP.NET建议框程序中,管理员将能够使用所有者的用户名查看GridView控件中列出的所有建议。在GridView的最后一列中,状态将列在那里。当管理员点击其中一个建议的状态时,将出现一个新的弹出窗口(asp.net ajax ModalPopUpExtender),列出所有可能的状态,例如:actioned,approved ...等。当Admin选择其中一个状态,建议的状态将在数据库中更新。一切正常。我现在要做的是当用户更新任何建议的状态时,将向所有者发送关于更新其建议状态的电子邮件通知。



我已经编写了Mail函数,但我不知道为什么它不发送任何电子邮件,我在调试代码时收到此错误:



使用未分配的本地变量''description''



我已将其分配给[的值]数据库中的列,但我不知道为什么会收到此错误。



任何人都可以帮助我用这个?



我真的很难获得更新建议的用户名。仅供参考,我有以下数据库设计:



In a web-based ASP.NET suggestions box program, the Admin will be able to see all suggestions listed in a GridView control with the username of the owner. In the last column of the GridView, the status will be listed there. When the Admin clicks on the status of one of these suggestion, a new pop-up window (asp.net ajax ModalPopUpExtender) will be appeared with listing all the possible status such as: actioned, approved... etc. And when the Admin selects one of these status, the status of the suggestion will be updated in the database. Everything works fine. What I want to do now is when the user updates the status of anyone of the suggestions, an email notification will be sent to the owner regarding the update of status of his suggestion.

I already wrote the Mail function but I don''t know why it does not send any email and I am getting this error while debugging the code:

Use of unassigned local variable ''description''

I already assigned it to the value of the [Description] column in the database but I don''t know why I am getting this error.

Could anyone help me with this?

I am really struggling with getting the username of that updated suggestion. FYI, I have the following database design:

Employee Table: Username, Name...
    SafetySuggestionsLog: ID, Title, Description, Username, StatusID
    SafetySuggestionsStatus: ID, Status





** ASP.NET代码:**



**ASP.NET code:**

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
                        AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
                        width="900px" CssClass="mGrid"
                        DataSourceID="SqlDataSource1"
                        OnRowDataBound="GridView1_RowDataBound">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" CssClass="alt" />
            <HeaderStyle Font-Bold = "True" ForeColor="Black" Height="20px"/>
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="No." InsertVisible="False"
                    ReadOnly="True" SortExpression="ID" />
                <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                <asp:BoundField DataField="Description" HeaderText="Description"
                    SortExpression="Description" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Username" HeaderText="Username"
                    SortExpression="Username" />
                <asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
                    SortExpression="DivisionShortcut" />
                <asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />

                <%-- This to make status be opened and edited through the Ajax ModalPopUp Window --%>
                <asp:TemplateField HeaderText="Status">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkSuggestionStatus" Text=''<%#Eval("Status")%>''
                                        OnClick="lnkSuggestionStatus_Click">
                        </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>

                <%--<asp:HyperLinkField HeaderText="Status"
                    SortExpression="Status" />--%>
            </Columns>
            <RowStyle HorizontalAlign="Center" />
        </asp:GridView>

        <asp:Button runat="server" ID="btnModalPopUp" style="display:none" />

        <AjaxToolkit:ModalPopUpExtender ID="modalPopUpExtender1"
                                        runat="server"
                                        TargetControlID="btnModalPopUp"
                                        PopupControlID="pnlPopUp"
                                        BackgroundCssClass="popUpStyle"
                                        PopupDragHandleControlID="panelDragHandle"
                                        OkControlID="OKButton">
        </AjaxToolkit:ModalPopUpExtender>

        <asp:HiddenField ID="HiddenField1" runat="server"/>

        <asp:Panel runat="server" ID="pnlPopUp" CssClass="popUpStyle">

                    <asp:RadioButtonList ID="StatusList" runat="server" RepeatColumns="1" RepeatDirection="Vertical"
                                            RepeatLayout="Table" TextAlign="Right" DataSourceID="SuggestionStatusDataSource"
                                            DataTextField="Status" DataValueField="ID">
                        <asp:ListItem id="option1" runat="server" Value="ACTIONED" />
                        <asp:ListItem id="option2" runat="server" Value="APPROVED" />
                        <asp:ListItem id="option3" runat="server" Value="PENDING" />
                        <asp:ListItem id="option4" runat="server" Value="TRANSFERRED" />
                    </asp:RadioButtonList>
                    <asp:SqlDataSource ID="SuggestionStatusDataSource" runat="server"
                                        ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
                                        SelectCommand="SELECT * FROM [SafetySuggestionsStatus]"></asp:SqlDataSource>

                    <asp:Button ID="confirmButton" runat="server" Text="Confirm"
                                OnClientClick="javascript:return confirm(''Are you sure you want to send an email notification about the safety suggestion to the owner?'')"
                                OnClick="btnSendStatus_Click" />

            <asp:Button ID="OKButton" runat="server" Text="Close" />
        </asp:Panel>
        </ContentTemplate>
        </asp:UpdatePanel>







**代码背后:**




**Code-Behind:**

    protected void lnkSuggestionStatus_Click(object sender, EventArgs e)
        {
            LinkButton lnkSuggestionStatus = sender as LinkButton;

            //var safetySuggestionsId =

            //get reference to the row selected
            GridViewRow gvrow = (GridViewRow)lnkSuggestionStatus.NamingContainer;

            //set the selected index to the selected row so that the selected row will be highlighted
            GridView1.SelectedIndex = gvrow.RowIndex;

            //This HiddenField used to store the value of the ID
            HiddenField1.Value = GridView1.DataKeys[gvrow.RowIndex].Value.ToString();
            //ViewState["Username"] = gvrow.Cells[4].Text;

            //show the modalPopUp
            modalPopUpExtender1.Show();
        }

        public void btnSendStatus_Click(object sender, EventArgs e) {
            //get the ID of the selected suggestion/row
            var statusID = StatusList.SelectedValue;
            var safetySuggestionsID = HiddenField1.Value;

            string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=xxdb;Integrated Security=True";
            //For updating the status of the safety suggestion
            string updateCommand = "UPDATE SafetySuggestionsLog SET StatusID= @statusID where ID=@SafetySuggestionsID";
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
                {
                    cmd.Parameters.AddWithValue("@statusID", Convert.ToInt32(statusID));
                    cmd.Parameters.AddWithValue("@SafetySuggestionsID", Convert.ToInt32(HiddenField1.Value));
                    cmd.ExecuteNonQuery();
                }
                //reset the value of hiddenfield
                HiddenField1.Value = "-1";
            }

            GridView1.DataBind();


            SendSuggestionStatusToUser(safetySuggestionsID);
        }

        


***Note: I know that I should not post a lengthy code here, but because I want to explain to you my work and to get your help.***


**UPDATE:**

I modified my code regarding assigning the variables to NULL and when I debugged the code, I found that the reader doesn't work and it did not read the following:

<pre lang="c#">    if (reader != null)
                    {
                        if (reader.Read())
                        {
                            username = reader["Username"].ToString();
                            description = reader["Description"].ToString();
                            status = reader["Status"].ToString();
                            sbEmailAddresses.Append(username).Append("@mailserver.com");
                        }
                    }







**更新2:**



在`SendSuggestionStatusToUser(string suggestionID)`方法中,我将断点添加到以下行:






**UPDATE 2:**

In the `SendSuggestionStatusToUser(string suggestionID)` method, I added break point to the following line:

string safetySuggestionID = suggestionID.ToString();





我将断点添加到以下行:





and I added break point to the following line:

cmd.Parameters.AddWithValue("@safetySuggestionID", Convert.ToInt32(HiddenField1.Value));





我发现第一个,safeSuggestionID从传递的值中获取数据。但是,对于第二个,`(HiddenField1.Value)`的值是-1,我不知道为什么。另外,我为以下每一行添加了断点:



And I found that for the first one, the safetySuggestionID got the data from the passed value. However, for the second one the value of `(HiddenField1.Value)`is -1 and I don''t know why. Also, I added break points to each one of the following lines:

SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    if (reader.Read())
                    {
                        username = reader["Username"].ToString();
                        description = reader["Description"].ToString();
                        status = reader["Status"].ToString();
                        sbEmailAddresses.Append(username).Append("@mailserver.com");
                    }
                }





调试器在调试时没有通过它们。它直接转到





And the debugger did not go through them while debugging them. It goes directly to

var sEMailAddresses = sbEmailAddresses.ToString();





我不知道为什么。任何的想法?你能帮我吗?

推荐答案

ConnectionStrings:testConnectionString%>
SelectCommand =SELECT * FROM [SafetySuggestionsStatus]> < / asp:SqlDataSource>

< asp:Button ID =confirmButtonrunat =serverText =Confirm
OnClientClick =javascript:return confirm(''Are您确定要向所有者发送有关安全建议的电子邮件通知吗?'')
OnClick =btnSendStatus_Click/>

< asp:Button ID =OKButton runat =serverText =Close/>
< / asp:Panel>
< / ContentTemplate>
< / asp:UpdatePanel>
ConnectionStrings:testConnectionString %>" SelectCommand="SELECT * FROM [SafetySuggestionsStatus]"></asp:SqlDataSource> <asp:Button ID="confirmButton" runat="server" Text="Confirm" OnClientClick="javascript:return confirm(''Are you sure you want to send an email notification about the safety suggestion to the owner?'')" OnClick="btnSendStatus_Click" /> <asp:Button ID="OKButton" runat="server" Text="Close" /> </asp:Panel> </ContentTemplate> </asp:UpdatePanel>







**代码背后:**




**Code-Behind:**

    protected void lnkSuggestionStatus_Click(object sender, EventArgs e)
        {
            LinkButton lnkSuggestionStatus = sender as LinkButton;

            //var safetySuggestionsId =

            //get reference to the row selected
            GridViewRow gvrow = (GridViewRow)lnkSuggestionStatus.NamingContainer;

            //set the selected index to the selected row so that the selected row will be highlighted
            GridView1.SelectedIndex = gvrow.RowIndex;

            //This HiddenField used to store the value of the ID
            HiddenField1.Value = GridView1.DataKeys[gvrow.RowIndex].Value.ToString();
            //ViewState["Username"] = gvrow.Cells[4].Text;

            //show the modalPopUp
            modalPopUpExtender1.Show();
        }

        public void btnSendStatus_Click(object sender, EventArgs e) {
            //get the ID of the selected suggestion/row
            var statusID = StatusList.SelectedValue;
            var safetySuggestionsID = HiddenField1.Value;

            string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=xxdb;Integrated Security=True";
            //For updating the status of the safety suggestion
            string updateCommand = "UPDATE SafetySuggestionsLog SET StatusID= @statusID where ID=@SafetySuggestionsID";
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
                {
                    cmd.Parameters.AddWithValue("@statusID", Convert.ToInt32(statusID));
                    cmd.Parameters.AddWithValue("@SafetySuggestionsID", Convert.ToInt32(HiddenField1.Value));
                    cmd.ExecuteNonQuery();
                }
                //reset the value of hiddenfield
                HiddenField1.Value = "-1";
            }

            GridView1.DataBind();


            SendSuggestionStatusToUser(safetySuggestionsID);
        }

        


***Note: I know that I should not post a lengthy code here, but because I want to explain to you my work and to get your help.***


**UPDATE:**

I modified my code regarding assigning the variables to NULL and when I debugged the code, I found that the reader doesn't work and it did not read the following:

<pre lang="c#">    if (reader != null)
                    {
                        if (reader.Read())
                        {
                            username = reader["Username"].ToString();
                            description = reader["Description"].ToString();
                            status = reader["Status"].ToString();
                            sbEmailAddresses.Append(username).Append("@mailserver.com");
                        }
                    }







**更新2:**



在`SendSuggestionStatusToUser(string suggestionID)`方法中,我将断点添加到以下行:






**UPDATE 2:**

In the `SendSuggestionStatusToUser(string suggestionID)` method, I added break point to the following line:

string safetySuggestionID = suggestionID.ToString();





我将断点添加到以下行:





and I added break point to the following line:

cmd.Parameters.AddWithValue("@safetySuggestionID", Convert.ToInt32(HiddenField1.Value));





我发现第一个,safeSuggestionID从传递的值中获取数据。但是,对于第二个,`(HiddenField1.Value)`的值是-1,我不知道为什么。另外,我为以下每一行添加了断点:



And I found that for the first one, the safetySuggestionID got the data from the passed value. However, for the second one the value of `(HiddenField1.Value)`is -1 and I don''t know why. Also, I added break points to each one of the following lines:

SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    if (reader.Read())
                    {
                        username = reader["Username"].ToString();
                        description = reader["Description"].ToString();
                        status = reader["Status"].ToString();
                        sbEmailAddresses.Append(username).Append("@mailserver.com");
                    }
                }





调试器在调试时没有通过它们。它直接转到





And the debugger did not go through them while debugging them. It goes directly to

var sEMailAddresses = sbEmailAddresses.ToString();





我不知道为什么。任何的想法?你能帮帮我吗?


string description=string.Empty;



试试这个


try this


这篇关于C#Mail:为什么这个功能无法发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆