C++/CLI Code Snippet - Send Email Using SMTP Server

C++/CLI Code Snippet - Send Email Using SMTP Server

C++/CLI Code Snippet - Send Email Using SMTP Server

C++/CLI code snippet connects to SMTP Email Server and send email message. SendEmail send email using SMTP email server.

Bookmark:

C++/CLI Code Snippet - Send Email Using SMTP Server

This .Net C++/CLI 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>
bool SendEmail(System::String ^_FromEmail, System::String ^_FromName, System::String ^_ToEmail, System::String ^_ToName, System::String ^_Subject, System::String ^_EmailBody, bool _IsBodyHtml, array<System::String^> ^_Attachments, System::String ^_EmailServer, System::String ^_LoginName, System::String ^_LoginPassword)
{
    try
    {
        // setup email header
        System::Net::Mail::MailMessage ^_MailMessage = gcnew System::Net::Mail::MailMessage();

        // Set the message sender
        // sets the from address for this e-mail message. 
        _MailMessage->From = gcnew System::Net::Mail::MailAddress(_FromEmail, _FromName);
        // Sets the address collection that contains the recipients of this e-mail message. 
        _MailMessage->To->Add(gcnew 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 != nullptr && _Attachments->Length > 0)
            for each(System::String ^_Attachment in _Attachments)
                _MailMessage->Attachments->Add(gcnew 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 = gcnew 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 = gcnew System::Net::NetworkCredential(_LoginName, _LoginPassword);
        _SmtpClient->UseDefaultCredentials = false;
        _SmtpClient->Credentials = _NetworkCredential;

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

        // Do cleanup
        delete _MailMessage;
        _SmtpClient = nullptr;
    }
    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("fromemail@yourdomain.com", "From name", "toemail@yourdomain.com", "To name", "email subject", "This is a test email\r\nline2", false, nullptr, "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("fromemail@yourdomain.com", "From name", "toemail@yourdomain.com", "To name", "email subject", "Here is HTML content body <b>This line is bold</b>", true, nullptr, "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("fromemail@yourdomain.com", "From name", "toemail@yourdomain.com", "To name", "email subject", "This is a test email\r\nline2", false, gcnew array<System::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("fromemail@yourdomain.com", "From name", "toemail@yourdomain.com", "To name", "email subject", "This is a test email\r\nline2", false, gcnew array<System::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++/CLI 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++/CLI

External Resources:

Leave a comment