> ## Documentation Index
> Fetch the complete documentation index at: https://docs.paubox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Email client

> Full reference for the Paubox C# SDK Email API client: sending messages, bulk sending, delivery tracking, dynamic templates, and error handling.

## Instantiation

```csharp theme={null}
// Direct credentials
var emailLib = new EmailLibrary("YOUR_API_KEY", "YOUR_USERNAME");

// IConfiguration (ASP.NET Core)
var emailLib = new EmailLibrary(configuration);
```

See [Authentication](/csharp-sdk/authentication) for both approaches. Use `IEmailLibrary` for dependency injection.

## Building a message

```csharp theme={null}
var message = new Message
{
    Recipients = new[] { "alice@example.com" },          // required
    Cc         = new[] { "manager@example.com" },        // optional
    Bcc        = new[] { "audit@example.com" },          // optional
    Header = new Header
    {
        From    = "sender@yourdomain.com",               // required
        Subject = "Your results are ready",              // required
        ReplyTo = "support@yourdomain.com",              // optional
        CustomHeaders = new Dictionary<string, string>   // optional
        {
            { "X-Custom-Header", "value" }
        }
    },
    Content = new Content
    {
        PlainText = "Plain text body.",                  // at least one required
        HtmlText  = "<p>HTML body.</p>"                  // optional; auto base64-encoded
    },
    Attachments          = new List<Attachment> { attachment },  // optional
    AllowNonTLS          = false,                        // optional; default false
    ForceSecureNotification = "true"                     // optional; "true" or "false"
};
```

### Attachments

```csharp theme={null}
byte[] fileBytes = File.ReadAllBytes("report.pdf");

var attachment = new Attachment
{
    FileName    = "report.pdf",
    ContentType = "application/pdf",
    Content     = Convert.ToBase64String(fileBytes)
};

message.Attachments = new List<Attachment> { attachment };
```

## Send a message

```csharp theme={null}
SendMessageResponse response = emailLib.SendMessage(message);

Console.WriteLine("Tracking ID: " + response.SourceTrackingId);
```

The `SendMessageResponse` includes:

| Property           | Description                                   |
| ------------------ | --------------------------------------------- |
| `SourceTrackingId` | Use to check delivery status                  |
| `Data`             | Raw response data                             |
| `Errors`           | List of `Error` objects if the request failed |

## Send bulk messages

Send up to 50 messages in a single API call. Each message gets its own tracking ID.

```csharp theme={null}
var messages = new[]
{
    new Message
    {
        Recipients = new[] { "alice@example.com" },
        Header  = new Header { From = "f@yourdomain.com", Subject = "Hi Alice" },
        Content = new Content { PlainText = "Hello Alice" }
    },
    new Message
    {
        Recipients = new[] { "bob@example.com" },
        Header  = new Header { From = "f@yourdomain.com", Subject = "Hi Bob" },
        Content = new Content { PlainText = "Hello Bob" }
    }
};

SendBulkMessagesResponse bulkResponse = emailLib.SendBulkMessages(messages);

foreach (var msg in bulkResponse.Messages)
{
    Console.WriteLine($"Tracking ID: {msg.SourceTrackingId}");
}
```

## Check delivery status

```csharp theme={null}
GetEmailDispositionResponse disposition =
    emailLib.GetEmailDisposition(response.SourceTrackingId);

foreach (var delivery in disposition.Data.Message.MessageDeliveries)
{
    Console.WriteLine($"{delivery.Recipient} → {delivery.Status.DeliveryStatus}");
}
```

Common `DeliveryStatus` values: `delivered`, `opened`, `failed`, `pending`.

## Dynamic templates

Templates use [Handlebars](https://handlebarsjs.com) syntax (`{{variable_name}}`).

### Create a template

```csharp theme={null}
DynamicTemplateResponse created = emailLib.CreateDynamicTemplate(
    templateName: "appointment-confirmation",
    templatePath: @"C:\templates\appointment.html"
);
```

### List templates

```csharp theme={null}
List<DynamicTemplateSummary> templates = emailLib.ListDynamicTemplates();
foreach (var t in templates)
    Console.WriteLine($"{t.Id}: {t.Name}");
```

### Get a template

```csharp theme={null}
GetDynamicTemplateResponse tmpl = emailLib.GetDynamicTemplate(templateId);
```

### Update a template

```csharp theme={null}
DynamicTemplateResponse updated = emailLib.UpdateDynamicTemplate(
    templateId:   123,
    templateName: "appointment-confirmation-v2",
    templatePath: @"C:\templates\appointment-v2.html"
);
```

### Delete a template

```csharp theme={null}
DeleteDynamicTemplateResponse deleted = emailLib.DeleteDynamicTemplate(templateId);
```

### Send a templated message

```csharp theme={null}
var templatedMsg = new TemplatedMessage
{
    Recipients    = new[] { "jane@example.com" },
    Header        = new Header { From = "appointments@yourclinic.com", Subject = "Your appointment" },
    TemplateName  = "appointment-confirmation",
    TemplateValues = new Dictionary<string, object>
    {
        { "first_name", "Jane" },
        { "date",       "2024-03-15" },
        { "time",       "2:00 PM" }
    }
};

SendMessageResponse response = emailLib.SendTemplatedMessage(templatedMsg);
```

## Error handling

All methods throw `SystemException` on API errors. The exception message contains the raw JSON response body:

```csharp theme={null}
try
{
    SendMessageResponse response = emailLib.SendMessage(message);
}
catch (SystemException ex)
{
    // ex.Message contains the raw JSON error response
    Console.WriteLine("API error: " + ex.Message);

    // Parse if needed:
    // var error = JsonSerializer.Deserialize<ErrorResponse>(ex.Message);
}
```
