ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Email

Send an email using the supplied string.

Source

/// <summary>
/// Send an email using the supplied string.
/// </summary>
/// <param name="body">String that will be used i the body of the email.</param>
/// <param name="subject">Subject of the email.</param>
/// <param name="sender">The email address from which the message was sent.</param>
/// <param name="recipient">The receiver of the email.</param> 
/// <param name="server">The server from which the email will be sent.</param>  
/// <returns>A boolean value indicating the success of the email send.</returns>
public static bool Email(this string body, string subject, string sender, string recipient, string server)
{
   try
   {
      // To
      MailMessage mailMsg = new MailMessage();
      mailMsg.To.Add(recipient);
      
      // From
      MailAddress mailAddress = new MailAddress(sender);
      mailMsg.From = mailAddress;

      // Subject and Body
      mailMsg.Subject = subject;
      mailMsg.Body = body;

      // Init SmtpClient and send
      SmtpClient smtpClient = new SmtpClient(server);
      System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
      smtpClient.Credentials = credentials;

      smtpClient.Send(mailMsg);
   }   
   catch (Exception ex)
   {
      return false;
   }

   return true;
}

Example

string myEmailBody = "Hello Jim,\nHow are things in your neck of the woods?\n\nSean";
myEmailBody.Email("Some random message", "from_user@abc.com", "to_user@abc.net", "mail.server.com");

"This is a test email".Email("Some random message", "from_user@abc.com", "to_user@abc.net", "mail.server.com");

Author: Sean Dorsett

Submitted on: 15 apr 2008

Language: C#

Type: System.String

Views: 6628