How to send email using c#

Created: 12/03/2011 03:06:59 p.m.

How to send email using c#.

First what we need to do is include Mail namespace:

using System.Net.Mail;

and now we just need to add some code to our class:
we will make a function so we can use it later in our project
this funciton will recive  4 parameters: our message body, sender mail, reciver mail, and subject...
and return true or false (sended or error)

public static bool SendMail(string message, string mailFrom, string mailTo, string subject)
    // If you whant to verify EMAIL string just use this:
    if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(mailFrom) || string.IsNullOrEmpty(mailTo)
    || string.IsNullOrEmpty(subject) || !Regex.IsMatch(mailFrom,
     @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
         return false;

       //  Our mail
     MailMessage ourMessage= new MailMessage();
     ourMessage.To.Add(new MailAddress(mailTo));
      ourMessage.From = new MailAddress(mailFrom);
     ourMessage.Body = message;
    ourMessage.IsBodyHtml = true;
       ourMessage.Subject = subject;

SmtpClient (Class)
      //  Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

       SmtpClient Client = new SmtpClient("", 25);
Client.EnableSsl = true;
Client.Credentials = new System.Net.NetworkCredential("", "yourpassword");

Client.Send(ourMessage);    // Try to send your mail.
         return true;                           // Mail sended
     catch (Exception ex)
          return false;                           // Send error

// using our function

        SendMail("mail body!","","","subject");


User: Bob Comment date: 16/03/2011 10:48:39 a.m.
ok :)
User: Rakshith Comment date: 30/03/2012 03:19:38 a.m.
childrens can do this....
where is attachment file add................
User: Maksim Comment date: 01/04/2012 06:58:16 p.m.
What file do you need?, there are only a simple code to send an e-mail...
User: wel Comment date: 17/04/2012 10:31:49 p.m.
is there another way to send mail without inputting username and password?
User: Maksim Comment date: 23/04/2012 02:10:20 p.m.
Hello, i dont think so, to prevent spam, gmail  and live require identification. But maby yo can do it by setting up your own email server, i dont know how to configure that, this is another way.

Go to Comments