开发者

smtpException was unhandled by user code

here is the code.

void sendMail()
{
    MailMessage mail = new MailMessage(开发者_运维技巧);

    mail.To.Add("abc@gmail.com");
    mail.From = new MailAddress("abc@gmail.com", txt_name.Text);
    mail.Subject = txt_subject.Text;
    mail.Body = txt_body.Text;

    SmtpClient smtp = new SmtpClient("smtp.gmail.com");
    smtp.EnableSsl = true;

    NetworkCredential yetki = new NetworkCredential("abc@gmail.com", "11111111");
    smtp.Credentials = yetki;

    smtp.Send(mail);

    Response.Write("mailiniz başarılı bir şekilde gönderilmiştir");
}

protected void btn_gonder_Click(object sender, EventArgs e)
{
    sendMail();
}


Use a try/catch block

void sendMail() {

   try{
      MailMessage mail = new MailMessage();

      mail.To.Add("abc@gmail.com");

      mail.From = new MailAddress("abc@gmail.com", txt_name.Text);

      mail.Subject = txt_subject.Text;

      mail.Body = txt_body.Text;

      SmtpClient smtp = new SmtpClient("smtp.gmail.com");

      smtp.EnableSsl = true;

      NetworkCredential yetki = new NetworkCredential("abc@gmail.com", "11111111");
      smtp.Credentials = yetki;

      smtp.Send(mail);
      Response.Write("mailiniz başarılı bir şekilde gönderilmiştir");
   }
   catch(Exception e){
      Response.Write(e.Message);
   }

}


The error indicating it is unhandled means you didn't catch the exception. Now what you actually do in the catch block to handle the exception is up to you, such as logging it to a file, queuing a retry, or showing a message box. Or trying to do something to prevent the exception in the first place.

protected void btn_gonder_Click(object sender, EventArgs e)
{
  try{
    sendMail();
  }
  catch(Exception ex)
  {

  }
}

Also note you can access ex.Message to see the exception message, or add a break point to the catch block and inspect ex. It is possible there is more you need to do to get it to work with gmail because of the requirements for authentication. I don't know if the network credentials are enough. I've always had trouble with it and resorted to using my ISP's email account that doens't require authentication.


You add a try/catch block to your code and ignore the error, or you post the entire exception message so that we can help you solve the actual problem.


According to this page when sending mail over SSL you should use port 465 i.e.

SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.EnableSsl = true;
smtp.Port = 465;
...

You should probably still wrap the call to Send in a try/catch block and handle any SmtpException that gets thrown if you can do anything about it.

Note you can also put smtpClient configuration in the web.config file (see here for example).


You haven't specified the port number for Gmail which is 587.

smtp.port = 587;

And your problem should be solved. Otherwise your code looks good.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜