简体   繁体   中英

How to send mail using SmtpClient in .net?

I have the following code which is not working:

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();
}

I am getting the following error:

Mailbox unavailable. The server response was: You must give your username and password to send mail through this service

You can see that I am passing a username and password. Why am I still getting this issue?

here i am using example of using gmail server

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);

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