简体   繁体   中英

error in sending email on button click in asp.net c#

I am using visual studio 2012 and asp.net framework 4.5. I want to create a form that whenever the user clicks the submit button an email be should be sent to me. I am using google smtp settings in my coding but I get an error like this "Failure Sending mail". I am pasting my coding for reference

protected void Button1_Click1(object sender, EventArgs e)
 {   
    MailMessage mailmessage = new MailMessage()
    {
        Subject = txtName.Text.ToString().Trim(),
        Body = txtComment.Text.ToString().Trim(),
        IsBodyHtml = false
    };

    mailmessage.To.Add(new MailAddress(Label1.Text));
    mailmessage.To.Add("myusername.com");
    SmtpClient smtpClient = new SmtpClient();
    smtpClient.SendAsync(mailmessage, null);

    Response.Write("Your mail has been sent successfuly");
    Label1.Text = "Your mail has been successfully sent..!!";
    this.txtComment.Text = "";
    this.txtName.Text = "";

web config file

<system.net>
<mailSettings>
  <smtp from="myusername.com">
    <network host="smtp.gmail.com"
     port="465" 
     userName=""
     password=""
     enableSsl="true"/>
  </smtp>
</mailSettings>

I have tried the port as 587 but I get the same error.

As somebody already suggested, try checking the Smtp Client credentials before sending the mail. Also i had some problems in the past with SmtpClient.SendAsync . Try to use SmtpClient.Send instead. Otherwise i see really no problem in your code.

Edit: It seems you created 2 SmtpClients. One in page load and one in buttonClick method. Does the second one know the credentials too?

    <system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="Your Email">
      <network defaultCredentials="false" host="smtp.gmail.com" port="587" userName="Your Email" password="Your Password"></network>
    </smtp>
  </mailSettings>
</system.net>

Try above code in web config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM