Go to Comments





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])@))" +
      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
      RegexOptions.IgnoreCase))
         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("smtp.live.com", 25);
       
Client.EnableSsl = true;
      
Client.Credentials = new System.Net.NetworkCredential("yourmail@hotmail.com", "yourpassword");

     try
     {
       
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!","yourcompanyMail@hotmail.com","recivermail@hotmail.com","subject");








Comments:

User: elyo Comment date: 12/03/2011 05:06:14 p.m.
Testeado y funcionando...
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.