【问题标题】:Failure sending message in smtp/The SMTP server requires a secure connection or the client was not authenticated在 smtp 中发送消息失败/SMTP 服务器需要安全连接或客户端未通过身份验证
【发布时间】:2013-09-01 12:37:26
【问题描述】:

我正在尝试重置密码和恢复密码功能。因此,我使用 smtp 方式发送邮件。但是,我的 try catch 出错了。

Error Occured: Failure sending mail.

我也不确定应该在 web.config 文件的哪个部分添加此连接代码

<network host="smtp.gmail.com" enableSsl="true"  />

下面是我在使用 smtp 逻辑时与 Azure 数据库的连接。

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string uniqueCode = string.Empty;
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            // get the records matching the supplied username or email id.         
            cmd = new SqlCommand("select * from MemberAccount where nric COLLATE Latin1_general_CS_AS=@nric or email COLLATE Latin1_general_CS_AS=@email", con);

            cmd.Parameters.AddWithValue("@nric", Convert.ToString(txtUserName.Text.Trim()));
            cmd.Parameters.AddWithValue("@email", Convert.ToString(txtEmailId.Text.Trim()));
            dr = cmd.ExecuteReader();
            cmd.Dispose();
            if (dr.HasRows)
            {
                dr.Read();
                //generate unique code
                uniqueCode = Convert.ToString(System.Guid.NewGuid());
                //Updating an unique random code in then UniquCode field of the database table
                cmd = new SqlCommand("update MemberAccount set UniqueCode=@uniqueCode where nric=@nric or email=@email", con);
                cmd.Parameters.AddWithValue("@uniqueCode", uniqueCode);
                cmd.Parameters.AddWithValue("@nric", txtUserName.Text.Trim());
                cmd.Parameters.AddWithValue("@email", txtEmailId.Text.Trim());

                StringBuilder strBody = new StringBuilder();
                //Passing emailid,username and generated unique code via querystring. For testing pass your localhost number and while making online pass your domain name instead of localhost path.
                strBody.Append("<a href=http://sipolice.azurewebsites.net/MemberRecoverPassword.aspx" + txtEmailId.Text + "&uName=" + txtUserName.Text + "&uCode=" + uniqueCode + ">Click here to change your password</a>");
                // sbody.Append("&uCode=" + uniqueCode + "&uName=" + txtUserName.Text + ">Click here to change your password</a>");

                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("SenderEmailIAddress@hotmail.com", dr["email"].ToString(), "Reset Your Password", strBody.ToString());
                //pasing the Gmail credentials to send the email
                System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("SenderEmailIAddress@hotmail.com", "SenderPassword");

                System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient("smtp.hotmail.com", 587);

                mailclient.EnableSsl = true;
                mailclient.Credentials = mailAuthenticaion;
                mail.IsBodyHtml = true;
                mailclient.Send(mail);
                dr.Close();
                dr.Dispose();
                cmd.ExecuteReader();
                cmd.Dispose();
                con.Close();
                lblStatus.Text = "Reset password link has been sent to your email address";
                txtEmailId.Text = string.Empty;
                txtUserName.Text = string.Empty;
            }
            else
            {
                lblStatus.Text = "Please enter valid email address or username";
                txtEmailId.Text = string.Empty;
                txtUserName.Text = string.Empty;
                con.Close();
                return;
            }
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Error Occured: " + ex.Message.ToString();
        }
        finally
        {
            cmd.Dispose();
        }
    }

更新 我才明白为什么它不能工作。由于我的帐户信息不正确,它不起作用

【问题讨论】:

  • 你能给我们来自错误而不是消息的堆栈跟踪吗?或者只是完全的例外。包括异常类型等
  • 请问如何从错误中获取stacktrace?
  • try { } catch(Exception ex) { System.IO.File.WriteAllText(@"C:\output.txt", ex.ToString()); }
  • 我收到此错误访问路径“C:\output.txt”被拒绝。
  • System.IO.File.WriteAllText(System.IO.Path.Combine(Server.MapPath("~/App_Data/"), "output.txt"), ex.ToString()); 并确保您的 asp.net 站点在执行前有一个 App_Data 文件夹。

标签: c# asp.net email azure smtp


【解决方案1】:

为什么会有这么多废话代码。以简单的方式尝试。,

例如:

在您的 Web.Config / App.Config 中:

      <system.net>
        <mailSettings>
          <smtp from="Your Email ID">
            <network host="Your Host Namecom" defaultCredentials="false" password="*********" userName="Your User Name"  enableSsl="true" />
          </smtp>
        </mailSettings>
      </system.net>

在你的代码背后:

        private void SendMail(string Address, string Body)
        {
            try
            {
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(Address);
                mailMessage.Subject = "Your Subject";
                mailMessage.IsBodyHtml = true;
                mailMessage.Body = Body;
                SmtpClient smtpClient = new SmtpClient(); // This will take the Credentioals from the WEB/APP Config 
                smtpClient.Send(mailMessage);
            }
            catch (Exception ex)
            {
                Extention.Log(ex.Message + "/=> " + ex.StackTrace);
            }
        }

像这样调用函数:

SendMail("To Address Email Id", strBody.ToString());

它会起作用的:)

【讨论】:

  • IMO 对我来说似乎有点太简单了。因为我必须在发送任何电子邮件之前检查我的数据库并查询它。
【解决方案2】:

我在您的代码中看到您使用的是 hotmail smtp。对于我的网站,我也使用该服务器。

如果您使用这些服务器,您必须知道您的凭据是您的 hotmail 登录名。邮件的发件人也必须是同一个地址。

我编写了一个快速脚本来发送邮件并对其进行了测试。成功了:

using (var client = new System.Net.Mail.SmtpClient("smtp.live.com", 25))
{
    client.Credentials = new System.Net.NetworkCredential("example@hotmail.com", "******");
    client.EnableSsl = true;

    var from = new System.Net.Mail.MailAddress("example@hotmail.com", "Your name");
    var to = new System.Net.Mail.MailAddress("target@example.com", "Receiver name");

    var message = new System.Net.Mail.MailMessage(from, to);
    message.Subject = "Test mail";
    message.Body = "Content";
    client.Send(message);
}

如果您在代码中指定所有 SMTP 信息,则您的 web.config 中不需要它。


Microsoft smtp(hotmail/live/outlook 等)

主机: smtp.live.com
端口: 587 或如果 587 被阻止 25
TSL/SSL:
身份验证: 您的 hotmail/live/outlook 帐户
发件人: 始终是您的 hotmail/live/outlook 地址

Gmail smtp

主机: smtp.gmail.com
端口: 465
TSL/SSL:
身份验证:您的 gmail 帐户
发件人:始终是您的 gmail 地址

【讨论】:

  • 我没有指定我的 smtp 信息。从我的代码中,我必须在发送任何消息之前检查并查询我的数据库,看看用户名是否匹配。
  • 你确实指定了你的smtp信息:你的mailAuthenticaion包含你的hotmail地址,你的mailclient包含你的hotmail smtp地址。
  • gmail和hotmail的smtp配置代码一样吗?但是我应该如何以及使用我的代码的哪一部分来替换它?
猜你喜欢
  • 2023-03-21
  • 2011-05-28
  • 1970-01-01
  • 2017-12-02
  • 2012-03-06
  • 2015-11-26
相关资源
最近更新 更多