如何在.net中使用SmtpClient发送邮件?

时间:2013-02-08 17:10:23

标签: c# smtp smtpclient

我有以下代码无效:

public static void SendMail(string content, string title, List<string> address)
{
   SmtpClient client = new SmtpClient(Server,Port);
   client.Port = Port;
   client.Host = Server;
   client.EnableSsl = false;
   client.Timeout = 10000;
   client.DeliveryMethod = SmtpDeliveryMethod.Network;
   client.UseDefaultCredentials = false;
   client.Credentials = new System.Net.NetworkCredential(Username, Password);

   foreach(string to in address)
   {
      MailMessage mm = new MailMessage(From, to, title, content);
      mm.BodyEncoding = UTF8Encoding.UTF8;
      mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

      client.Send(mm);
   }
   client.Dispose();
}

我收到以下错误:

  

邮箱不可用。服务器响应是:您必须提供用户名和密码才能通过此服务发送邮件

您可以看到我正在传递用户名和密码。为什么我仍然遇到这个问题?

1 个答案:

答案 0 :(得分:2)

这里我使用的是使用gmail服务器的例子

MailMessage mail = new MailMessage();
        mail.To.Add(textBox1.Text);

        mail.From = new MailAddress("Yourgmailid");
        mail.Subject = "Email using Gmail";

        string Body = "Hi, this mail is to test sending mail" +
                      "using Gmail in ASP.NET";
        mail.Body = Body;

        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; 
        smtp.Credentials = new System.Net.NetworkCredential
             ("Yourgmailid, "Password");

        smtp.EnableSsl = true;
        smtp.Send(mail);