Search code examples
c#asp.netemailmailer

How to check if API key of Elastic Email API is correct or incorrect in asp.net and C#


I am using Elastic Email API in my web application project in asp.net c#. when I give USERNAME and API_KEY with other required data, email is sent to destination (I am sending email to myself for testing). And on receiving mail, there is one Lable on my page "Mail is sent successfully"

Now the problem is, if I provide wrong USERNAME and API_KEY, I will get Lable but not mail. I know because I have provided wrong API_KEY.

So how to check if i have provided valid USERNAME and API_KEY so that I can change Lable to "check your data"

My Code:

ElasticEmail.cs

public static string SaveAndTestElasticEmail(string from, string to, string fromName, string subject, string bodyHtml)
        {
            try
            {
                setElasticEmailSettings();
                string channel = System.Configuration.ConfigurationManager.AppSettings["registrationNumber"];
                WebClient client = new WebClient();
                NameValueCollection values = new NameValueCollection();
                values.Add("username", USERNAME);
                values.Add("api_key", API_KEY);
                values.Add("from", from);
                values.Add("from_name", fromName);
                values.Add("subject", subject);
                values.Add("body_html", bodyHtml);
                values.Add("channel", channel);
                values.Add("to", to);
                byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values);
                return Encoding.UTF8.GetString(response);
            }
            catch (Exception ex)
            {
                return null;

            }

        }

If I provide valid API_KEYand I debug my code, I am getting response{[36]} . and if I provide wrong key, then still I will receive response but it is, response{[22]} and I will not get mail.


Solution

  • byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values);
    
    if (response.Length <= 35)
    {
        return null;
    }
    else
    {
        return Encoding.UTF8.GetString(response);
    }