Send Email Messages via MailGun and SendGrid

Sending Messages using MailGun and SendGrid

Aspose.Email provides the ability to send email messages using MailGun or SendGrid services. Its unified API allows you to initialize a client, prepare and send the email message.

First, it’s important to set up options depending on which service is going to be used for sending messages. DeliveryServiceOptions class will help you with that. The following code sample shows how to set up options for the services.

MailGun client options:

string domain = "YOUR_MAILGUN_DOMEN";
string privApiKey = "YOUR_MAILGUN_PRIVATE_API_KEY";
var opt = new MailgunClientOptions { Domain = domain, ApiKey = privApiKey };

SendGrid client options:

string privApiKey = "YOUR_SENDGRID_PRIVATE_API_KEY";
var opt = new SendGridClientOptions { ApiKey = privApiKey };

To prepare and send a message, use the following code sample and steps:

  1. Create an instance of the IDeliveryServiceClient interface.
  2. Create a new eml message using the MailMessage class. Specify its properties.
  3. Use the Send method of the client object to send the email. The result of the send operation is stored in the resp variable.
  4. If the sending operation was not successful (resp.Successful is false), the code enters a foreach loop to iterate over the ErrorMessages collection of the resp object. Each error message is printed to the console using Console.WriteLine.
IDeliveryServiceClient client = DeliveryServiceClientFactory.Get(opt);

MailMessage eml = new MailMessage(fromAddress, toAddress, subject, body);

var resp = client.Send(eml);

if (!resp.Successful)
{
    foreach (var error in resp.ErrorMessages)
    {
        Console.WriteLine(error);
    }
}

Sending Messages Asynchronously

MailMessage eml = new MailMessage(fromAddress, toAddress, subject, body);

var sendTask = client.SendAsync(eml);
sendTask.Wait();

if (!sendTask.Result.Successful)
{
    foreach (var error in sendTask.Result.ErrorMessages)
    {
        Console.WriteLine(error);
    }
}