SMTP没有发送电子邮件asp.net

时间:2017-01-17 10:07:28

标签: c# asp.net

我有这段代码,前一段时间工作得很好,但现在无法发送生成的密码,

这就是“获取凭据时发生错误。请联系ICT办公室管理员”

任何想法?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class staff_Forgot_Password : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnLogin_Click(object sender, EventArgs e)
    {
        string email = string.Empty;
        string userno = TxtUsername.Text.Trim().Replace("'", "");

        if (string.IsNullOrEmpty(userno))
        {
            LblError.Text = "Username should not be empty";
            return;
        }

        #region generate random password

        Random rand = new Random();
        Random randAlpha = new Random();
        int newpassint = rand.Next(10000, 99999);

        int alphabetPosition = randAlpha.Next(1, 26);
        bool isCap = (alphabetPosition % 2 == 0 ? true : false);
        string theAlphabet = GetTheAlphabet(alphabetPosition, isCap);

        alphabetPosition = randAlpha.Next(1, 26);
        isCap = (alphabetPosition % 2 == 0 ? true : false);
        theAlphabet += GetTheAlphabet(alphabetPosition, isCap);

        alphabetPosition = randAlpha.Next(1, 26);
        isCap = (alphabetPosition % 2 == 0 ? true : false);
        theAlphabet += GetTheAlphabet(alphabetPosition, isCap);

        alphabetPosition = randAlpha.Next(1, 26);
        isCap = (alphabetPosition % 2 == 0 ? true : false);
        theAlphabet += GetTheAlphabet(alphabetPosition, isCap);

        //string newpass = theAlphabet + "#" + newpassint.ToString() + "?" + alphabetPosition.ToString() + "@";
        string newpass = theAlphabet + "#" + newpassint.ToString() + "@" + alphabetPosition.ToString();

        #endregion generate random password

        email = GetStaffEmail(userno);
        bool ok = ResetPassword(userno, newpass);
        if (ok)
        {
            const string subject = "STAFF SELF SERVICE PORTAL CREDENTIALS";
            string msg = "Staff portal credentials reset:<br>New password is <b>" + newpass + "</b>";
            if (SendEmailAlert(msg, email, subject))
            {
                Message("A new password has been generated and sent to your Email.");
                return;
            }
            else
            {
                Message("An error occured while sending you the credentials.Please contact the ICT office administrator.");
            }
        }
        else
        {
            LblError.Text = "Password reset failed, please recheck your staff number and/or consult your administrator";
        }
    }

    protected string GetStaffEmail(string username)
    {
        string rval = string.Empty;
        SqlConnection connToNAV = null;
        try
        {
            using (connToNAV = new SqlConnection(MyComponents.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string sqlStmt = "SELECT [Company E-Mail] FROM [" + MyComponents.Company_Name +
                                     " $Staff-table] WHERE [No_] = @username";
                    cmd.CommandText = sqlStmt;
                    cmd.Connection = connToNAV;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@username", username.Trim());

                    if (connToNAV.State != ConnectionState.Open)
                    {
                        connToNAV.Open();
                    }
                    using (SqlDataReader cmdReader = cmd.ExecuteReader())
                    {
                        if (cmdReader.HasRows == true)
                        {
                            cmdReader.Read();
                            rval = cmdReader["Company E-Mail"].ToString();
                        }
                        else
                        {
                            LblError.Text = "Warning!, password reset failed! contact your administrator!";
                        }
                        cmdReader.Close();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Data.Clear();
        }
        finally
        {
            connToNAV.Close();
        }

        return rval;
    }


    private string GetTheAlphabet(int alphabetPosition, bool isCap)
    {
        string rval = string.Empty;
        switch (alphabetPosition)
        {
            case 1: rval = "A"; break;
            case 2: rval = "B"; break;
            case 3: rval = "C"; break;
            case 4: rval = "D"; break;
            case 5: rval = "E"; break;
            case 6: rval = "F"; break;
            case 7: rval = "G"; break;
            case 8: rval = "H"; break;
            case 9: rval = "I"; break;
            case 10: rval = "J"; break;
            case 11: rval = "K"; break;
            case 12: rval = "L"; break;
            case 13: rval = "M"; break;
            case 14: rval = "N"; break;
            case 15: rval = "O"; break;
            case 16: rval = "P"; break;
            case 17: rval = "Q"; break;
            case 18: rval = "R"; break;
            case 19: rval = "S"; break;
            case 20: rval = "T"; break;
            case 21: rval = "U"; break;
            case 22: rval = "V"; break;
            case 23: rval = "W"; break;
            case 24: rval = "X"; break;
            case 25: rval = "Y"; break;
            default: rval = "Z"; break;
        }
        return isCap ? rval : rval.ToLower();
    }

    public static bool SendEmailAlert(string body, string recepient, string subject)
    {
        Boolean x = false;

        string a = "";
        try
        {

            string SMTPHost = "smtp.gmail.com";
            string fromAddress = "myemail@domain.com";
            string toAddress = recepient;
            System.Net.Mail.MailMessage mail_ = new System.Net.Mail.MailMessage();
            mail_.To.Add(toAddress);
            mail_.Subject = subject;
            mail_.From = new System.Net.Mail.MailAddress(fromAddress);
            mail_.Body = body;
            mail_.IsBodyHtml = true;

            var smtp = new SmtpClient("smtp.gmail.com", 465)
            {
                Credentials = new NetworkCredential("myemail@domain.com", "mypassword"),
                EnableSsl = true
            };
            smtp.Send(mail_);

            x = true;
            a = "Sent";

        }
        catch (Exception ex2)
        {
            a = ex2.ToString();
            ex2.Data.Clear();
        }
        return x;
    }


    private bool ResetPassword(string userno, string newpass)
    {
        bool rval = false;
        SqlConnection connToNAV = null;
        try
        {
            using (connToNAV = new SqlConnection(MyComponents.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string sqlStmt = "UPDATE [" + MyComponents.Company_Name + " $Staff-table] ";
                    sqlStmt += "SET [Portal Password] = @Portal_Password,[Changed Password] = 1 ";
                    sqlStmt += "WHERE (1=1) AND ([No_] = @StaffNo) ";

                    if (connToNAV.State != ConnectionState.Open)
                    {
                        connToNAV.Open();
                    }
                    cmd.CommandText = sqlStmt;
                    cmd.Connection = connToNAV;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Portal_Password", newpass);
                    cmd.Parameters.AddWithValue("@StaffNo", userno);
                    int rst = cmd.ExecuteNonQuery();
                    if (rst == 1)
                    {
                        rval = true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Data.Clear();
        }
        finally
        {
            connToNAV.Close();
        }
        return rval;
    }

    public void Message(string strMsg)
    {
        string strScript = null;
        strScript = "<script>";
        strScript = strScript + "alert('" + strMsg + "');";
        strScript = strScript + "</script>";
        Page.RegisterStartupScript("ClientScript", strScript.ToString());
    }

}using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class staff_Forgot_Password : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnLogin_Click(object sender, EventArgs e)
    {
        string email = string.Empty;
        string userno = TxtUsername.Text.Trim().Replace("'", "");

        if (string.IsNullOrEmpty(userno))
        {
            LblError.Text = "Username should not be empty";
            return;
        }

        #region generate random password

        Random rand = new Random();
        Random randAlpha = new Random();
        int newpassint = rand.Next(10000, 99999);

        int alphabetPosition = randAlpha.Next(1, 26);
        bool isCap = (alphabetPosition % 2 == 0 ? true : false);
        string theAlphabet = GetTheAlphabet(alphabetPosition, isCap);

        alphabetPosition = randAlpha.Next(1, 26);
        isCap = (alphabetPosition % 2 == 0 ? true : false);
        theAlphabet += GetTheAlphabet(alphabetPosition, isCap);

        alphabetPosition = randAlpha.Next(1, 26);
        isCap = (alphabetPosition % 2 == 0 ? true : false);
        theAlphabet += GetTheAlphabet(alphabetPosition, isCap);

        alphabetPosition = randAlpha.Next(1, 26);
        isCap = (alphabetPosition % 2 == 0 ? true : false);
        theAlphabet += GetTheAlphabet(alphabetPosition, isCap);

        //string newpass = theAlphabet + "#" + newpassint.ToString() + "?" + alphabetPosition.ToString() + "@";
        string newpass = theAlphabet + "#" + newpassint.ToString() + "@" + alphabetPosition.ToString();

        #endregion generate random password

        email = GetStaffEmail(userno);
        bool ok = ResetPassword(userno, newpass);
        if (ok)
        {
            const string subject = "STAFF SELF SERVICE PORTAL CREDENTIALS";
            string msg = "Staff portal credentials reset:<br>New password is <b>" + newpass + "</b>";
            if (SendEmailAlert(msg, email, subject))
            {
                Message("A new password has been generated and sent to your Email.");
                return;
            }
            else
            {
                Message("An error occured while sending you the credentials.Please contact the ICT office administrator.");
            }
        }
        else
        {
            LblError.Text = "Password reset failed, please recheck your staff number and/or consult your administrator";
        }
    }

    protected string GetStaffEmail(string username)
    {
        string rval = string.Empty;
        SqlConnection connToNAV = null;
        try
        {
            using (connToNAV = new SqlConnection(MyComponents.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string sqlStmt = "SELECT [Company E-Mail] FROM [" + MyComponents.Company_Name +
                                     " $Staff-table] WHERE [No_] = @username";
                    cmd.CommandText = sqlStmt;
                    cmd.Connection = connToNAV;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@username", username.Trim());

                    if (connToNAV.State != ConnectionState.Open)
                    {
                        connToNAV.Open();
                    }
                    using (SqlDataReader cmdReader = cmd.ExecuteReader())
                    {
                        if (cmdReader.HasRows == true)
                        {
                            cmdReader.Read();
                            rval = cmdReader["Company E-Mail"].ToString();
                        }
                        else
                        {
                            LblError.Text = "Warning!, password reset failed! contact your administrator!";
                        }
                        cmdReader.Close();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Data.Clear();
        }
        finally
        {
            connToNAV.Close();
        }

        return rval;
    }


    private string GetTheAlphabet(int alphabetPosition, bool isCap)
    {
        string rval = string.Empty;
        switch (alphabetPosition)
        {
            case 1: rval = "A"; break;
            case 2: rval = "B"; break;
            case 3: rval = "C"; break;
            case 4: rval = "D"; break;
            case 5: rval = "E"; break;
            case 6: rval = "F"; break;
            case 7: rval = "G"; break;
            case 8: rval = "H"; break;
            case 9: rval = "I"; break;
            case 10: rval = "J"; break;
            case 11: rval = "K"; break;
            case 12: rval = "L"; break;
            case 13: rval = "M"; break;
            case 14: rval = "N"; break;
            case 15: rval = "O"; break;
            case 16: rval = "P"; break;
            case 17: rval = "Q"; break;
            case 18: rval = "R"; break;
            case 19: rval = "S"; break;
            case 20: rval = "T"; break;
            case 21: rval = "U"; break;
            case 22: rval = "V"; break;
            case 23: rval = "W"; break;
            case 24: rval = "X"; break;
            case 25: rval = "Y"; break;
            default: rval = "Z"; break;
        }
        return isCap ? rval : rval.ToLower();
    }

    public static bool SendEmailAlert(string body, string recepient, string subject)
    {
        Boolean x = false;

        string a = "";
        try
        {

            string SMTPHost = "smtp.gmail.com";
            string fromAddress = "myemail@domain.com";
            string toAddress = recepient;
            System.Net.Mail.MailMessage mail_ = new System.Net.Mail.MailMessage();
            mail_.To.Add(toAddress);
            mail_.Subject = subject;
            mail_.From = new System.Net.Mail.MailAddress(fromAddress);
            mail_.Body = body;
            mail_.IsBodyHtml = true;

            var smtp = new SmtpClient("smtp.gmail.com", 465)
            {
                Credentials = new NetworkCredential("myemail@domain.com", "mypassword"),
                EnableSsl = true
            };
            smtp.Send(mail_);

            x = true;
            a = "Sent";

        }
        catch (Exception ex2)
        {
            a = ex2.ToString();
            ex2.Data.Clear();
        }
        return x;
    }


    private bool ResetPassword(string userno, string newpass)
    {
        bool rval = false;
        SqlConnection connToNAV = null;
        try
        {
            using (connToNAV = new SqlConnection(MyComponents.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string sqlStmt = "UPDATE [" + MyComponents.Company_Name + " $Staff-table] ";
                    sqlStmt += "SET [Portal Password] = @Portal_Password,[Changed Password] = 1 ";
                    sqlStmt += "WHERE (1=1) AND ([No_] = @StaffNo) ";

                    if (connToNAV.State != ConnectionState.Open)
                    {
                        connToNAV.Open();
                    }
                    cmd.CommandText = sqlStmt;
                    cmd.Connection = connToNAV;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Portal_Password", newpass);
                    cmd.Parameters.AddWithValue("@StaffNo", userno);
                    int rst = cmd.ExecuteNonQuery();
                    if (rst == 1)
                    {
                        rval = true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Data.Clear();
        }
        finally
        {
            connToNAV.Close();
        }
        return rval;
    }

    public void Message(string strMsg)
    {
        string strScript = null;
        strScript = "<script>";
        strScript = strScript + "alert('" + strMsg + "');";
        strScript = strScript + "</script>";
        Page.RegisterStartupScript("ClientScript", strScript.ToString());
    }

}

1 个答案:

答案 0 :(得分:0)

SMTPHost有时候不能正常工作smtp.gmail.com所以你可以试试

string SMTPHost = "yourdomainname.com";
var smtp = new SmtpClient("yourdomainname.com", 587) // Offline
var smtp = new SmtpClient("yourdomainname.com", 25) // Online