C# Code Snippet - Send Email Using SMTP Server

C# Code Snippet - Send Email Using SMTP Server

C# Code Snippet - Send Email Using SMTP Server

(C-Sharp) C# code snippet connects to SMTP Email Server and send email message. SendEmail send email using SMTP email server.

Bookmark:

C# Code Snippet - Send Email Using SMTP Server

This .Net C# code snippet connects to SMTP Email Server and send email message. To use this function simply provide from email, from name, to email, to name, email subject, email body, body HTML or not, attachments, SMTP server address, login name and login password. Email attachments are passing to function as a string array. To avoid email attachments, simply pass NULL for parameter value. This function uses System.Net.Mail Namespace to process email sending, function returns TRUE if email send out successfully, FALSE otherwise. Modify the exception handling section for your project requirements.

/// <summary>
/// method to send email using SMTP server
/// </summary>
/// <param name="_FromEmail">From email address</param>
/// <param name="_FromName">From name</param>
/// <param name="_ToEmail">To email address</param>
/// <param name="_ToName">To name</param>
/// <param name="_Subject">Email subject</param>
/// <param name="_EmailBody">Email message body</param>
/// <param name="_IsBodyHtml">Is email message body HTML</param>
/// <param name="_Attachments">Email message file attachments</param>
/// <param name="_EmailServer">SMTP email server address</param>
/// <param name="_LoginName">SMTP email server login name</param>
/// <param name="_LoginPassword">SMTP email server login password</param>
/// <returns>TRUE if the email sent successfully, FALSE otherwise</returns>
public bool SendEmail(string _FromEmail, string _FromName, string _ToEmail, string _ToName, string _Subject, string _EmailBody, bool _IsBodyHtml, string[] _Attachments, string _EmailServer, string _LoginName, string _LoginPassword)
{
    try
    {
        // setup email header
        System.Net.Mail.MailMessage _MailMessage = new System.Net.Mail.MailMessage();

        // Set the message sender
        // sets the from address for this e-mail message. 
        _MailMessage.From = new System.Net.Mail.MailAddress(_FromEmail, _FromName);
        // Sets the address collection that contains the recipients of this e-mail message. 
        _MailMessage.To.Add(new System.Net.Mail.MailAddress(_ToEmail, _ToName));

        // sets the message subject.
        _MailMessage.Subject = _Subject;
        // sets the message body. 
        _MailMessage.Body = _EmailBody;
        // sets a value indicating whether the mail message body is in Html. 
        // if this is false then ContentType of the Body content is "text/plain". 
        _MailMessage.IsBodyHtml = _IsBodyHtml;

        // add all the file attachments if we have any
        if (_Attachments != null && _Attachments.Length > 0)
            foreach(string _Attachment in _Attachments)
                _MailMessage.Attachments.Add(new System.Net.Mail.Attachment(_Attachment));

        // SmtpClient Class Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
        System.Net.Mail.SmtpClient _SmtpClient = new System.Net.Mail.SmtpClient(_EmailServer);

        //Specifies how email messages are delivered. Here Email is sent through the network to an SMTP server.
        _SmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

        // Some SMTP server will require that you first authenticate against the server.
        // Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.
        System.Net.NetworkCredential _NetworkCredential = new System.Net.NetworkCredential(_LoginName, _LoginPassword);
        _SmtpClient.UseDefaultCredentials = false;
        _SmtpClient.Credentials = _NetworkCredential;

        //Let's send it
        _SmtpClient.Send(_MailMessage);

        // Do cleanup
        _MailMessage.Dispose();
        _SmtpClient = null;
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        return false;
    }

    return true;
}


Here is a simple example showing how to use above function (SendEmail) to send plain text email using SMTP email server. Notice over here we passing FALSE for HTML body to allow plain text and NULL value as a attachment.

// Send plain text email with one attachment
if (SendEmail("[email protected]", "From name",
    "[email protected]", "To name",
    "email subject", "This is a test email\r\nline2", false, null,
    "mail.yourdomain.com", "login-name", "login-password"))
    Console.WriteLine("Email sent successfully");
else
    Console.WriteLine("Failed to send email");


Here is a simple example showing how to use above function (SendEmail) to send email with HTML contents in the email body using SMTP email server. Notice over here we passing TRUE for HTML body to allow HTML contents and NULL value as a attachment.

// Send plain text email with one attachment
if (SendEmail("[email protected]", "From name",
    "[email protected]", "To name",
    "email subject", "Here is HTML content body<br /><b>This line is bold</b>", true, null,
    "mail.yourdomain.com", "login-name", "login-password"))
    Console.WriteLine("Email sent successfully");
else
    Console.WriteLine("Failed to send email");


Here is a simple example showing how to use above function (SendEmail) to send plain text email with one attachment file using SMTP email server. Notice over here we passing FALSE for HTML body to allow plain text and one file path as a string array to attachment parameter.

// Send plain text email with one attachment
if (SendEmail("[email protected]", "From name",
    "[email protected]", "To name",
    "email subject", "This is a test email\r\nline2", false, new string[] { "c:\\sampleimage.jpg" },
    "mail.yourdomain.com", "login-name", "login-password"))
    Console.WriteLine("Email sent successfully");
else
    Console.WriteLine("Failed to send email");


Here is a simple example showing how to use above function (SendEmail) to send plain text email with more than one attachment file using SMTP email server. Notice over here we passing FALSE for HTML body to allow plain text and two file paths as a string array to attachment parameter.

// Send plain text email with one attachment
if (SendEmail("[email protected]", "From name",
    "[email protected]", "To name",
    "email subject", "This is a test email\r\nline2", false, new string[] { "c:\\sampleimage.jpg", "c:\\sampledoc.doc" },
    "mail.yourdomain.com", "login-name", "login-password"))
    Console.WriteLine("Email sent successfully");
else
    Console.WriteLine("Failed to send email");


C# Keywords Used:

  • SmtpClient
  • MailMessage
  • MailAddress
  • Attachment
  • SmtpDeliveryMethod
  • UseDefaultCredentials
  • NetworkCredential
  • Exception

Code Snippet Information:

  • Applies To: .Net, C#, CLI, Email, SMTP, System.Net.Mail, MailMessage, SMTPClient, Sending emails using .Net, Email attachments, SMTP Authentication, SMTP Delivery Methods
  • Programming Language : C# (C-Sharp)

External Resources:

sushil :: August 23-2011 :: 08:53 AM

It's good but confused...which code should be written in which page...??

Sandesh :: March 11-2011 :: 06:43 AM

If i put my login id in outlook and try to resolve it using ctrl+k, it resolves the login and gives me respective email id. Can i do the same thing using code? i tried to put my login id in MailMessage.To.Add, but it only accepts proper email id. Anyone knows solution for this?

Raghu :: October 10-2011 :: 07:55 AM

Nice ....

Thankyou...

Leave a comment