SendGrid C# Library

repository·main·Indexed 22 days ago

https://github.com/sendgrid/sendgrid-csharp

A high-level .NET wrapper for the Twilio SendGrid Web API v3. It enables developers to send emails and manage SendGrid resources programmatically using the SendGrid NuGet package. The library includes support for Dependency Injection via SendGrid.Extensions.DependencyInjection, a Mail helper for constructing messages, and example projects for ASP.NET, Event Webhook consumers, and Inbound Parse Webhook handlers.

Tokens
59K
Snippets
183
Records
202
Agent score
76%

What's inside sendgrid-csharp

  1. Manage IP Access Settings

    main

    IP Access Management allows you to control which IP addresses can access your account via the UI or API. You can whitelist specific IPs, ranges, or wildcards.

    Warning: Removing your own IP address from the whitelist may prevent you from accessing your account.

  2. Manage Inbound Parse Settings

    main

    The Inbound Parse Webhook allows you to have incoming emails parsed (extracting content and attachments) and POSTed to a URL of your choice. You can manage these settings by hostname.

    Available Operations:

    • Create: POST /user/webhooks/parse/settings
    • Retrieve All: GET /user/webhooks/parse/settings
    • Update Specific: PATCH /user/webhooks/parse/settings/{hostname}
    • Retrieve Specific: GET /user/webhooks/parse/settings/{hostname}
    • Delete Specific: DELETE /user/webhooks/parse/settings/{hostname}
  3. Manage API key permissions with SendGridPermissionsBuilder

    main

    The SendGridPermissionsBuilder is used to define the scopes for new or existing API keys. You can add permissions using SendGridPermission enums, which by default include all associated scopes.

    Key capabilities include:

    • Granular Scopes: Use ScopeOptions.ReadOnly to limit a permission to read-only access.
    • Exclusion Filters: Use .Exclude(predicate) to ensure certain scopes (like api_keys) are never included, even if requested by a permission enum.
    • Manual Scope Inclusion: Use .Include(IEnumerable<string>) or .Include(params string[]) to add specific raw scope strings directly.
    • Integration: Use the CreateApiKey extension method on SendGridClient to commit the builder's configuration to a new API key.
    var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
    var client = new SendGridClient(apiKey);
    var builder = new SendGridPermissionsBuilder();
    
    // Example: Add Alerts (all scopes) and Marketing Campaigns (read-only)
    builder.AddPermissionsFor(SendGridPermission.Alerts);
    builder.AddPermissionsFor(SendGridPermission.MarketingCampaigns, ScopeOptions.ReadOnly);
    
    await client.CreateApiKey(builder, "Alerts & Read-Only Marketing Campaigns API Key");
  4. Manage transactional template versions

    main

    Transactional templates can have multiple versions, each with its own subject and content. Users can have up to 300 versions across all templates.

    Create a new version

    Use POST /templates/{template_id}/versions to create a new version for a specific template.

    Edit a version

    Use PATCH /templates/{template_id}/versions/{version_id} to update an existing version.

    Retrieve a version

    Use GET /templates/{template_id}/versions/{version_id} to fetch details of a specific version.

    Delete a version

    Use DELETE /templates/{template_id}/versions/{version_id} to remove a version.

    Activate a version

    Use POST /templates/{template_id}/versions/{version_id}/activate to make a specific version the active one for the template.

    // Example: Create a new version
    string data = @"{
      'active': 1, 
      'html_content': '<%body%>', 
      'name': 'example_version_name', 
      'plain_content': '<%body%>', 
      'subject': '<%subject%>'
    }";
    var json = JsonConvert.DeserializeObject<Object>(data);
    data = json.ToString();
    var template_id = "test_url_param";
    var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "templates/" + template_id + "/versions", requestBody: data);
    
    // Example: Activate a version
    var template_id = "test_url_param";
    var version_id = "test_url_param";
    var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "templates/" + template_id + "/versions/" + version_id + "/activate");
  5. Configure Transient Fault Handling (Retries)

    main

    By default, retry behavior is disabled. To handle transient errors (500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout), you must instantiate SendGridClient using SendGridClientOptions and configure ReliabilitySettings.

    ReliabilitySettings Parameters:

    • RetryCount: Number of retries (in addition to the initial attempt). Max is 5. Setting 1 results in 2 total attempts.
    • MinimumBackOff: Minimum time to wait between retries.
    • MaximumBackOff: Maximum time to wait between retries (Max 30 seconds).
    • DeltaBackOff: Random delta used for exponential delay calculation to avoid synchronized retries.
    var options = new SendGridClientOptions
    {
        ApiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY"),
        ReliabilitySettings = new ReliabilitySettings(2, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(3))
    };
    
    var client = new SendGridClient(options);
  6. Manage IP Pools

    main
    IP Pools allow you to group dedicated Twilio SendGrid IP addresses together (e.g., separate pools for transactional and marketing email) to maintain separate reputations. Each user can create up to 10 different IP pools. IP pools can only be used with authenticated IP addresses. If an IP pool is not specified for an email, it will use any available IP, including those in pools.
  7. Deploy the Inbound Parse Webhook handler locally

    main

    To run the Inbound Parse listener on your local machine, follow these steps:

    1. Clone and Prepare: Clone the repository and navigate to the example directory.
      git clone https://github.com/sendgrid/sendgrid-csharp.git
      cd sendgrid-csharp/examples/inbound-webhook-handler
      dotnet restore
    2. Run the Listener: Start the project using the Inbound.csproj file.
      dotnet run --project .\Src\Inbound\Inbound.csproj
    3. Expose via ngrok: Since the server starts on a local port, use ngrok to create a public URL for SendGrid to hit.
      ngrok http PORT_NUMBER
    4. Configure SendGrid: Update your SendGrid Incoming Parse settings:
      • HOSTNAME: Use the domain where you configured MX records (e.g., inbound.yourdomain.com).
      • URL: Use the ngrok URL appended with /inbound (e.g., http://XXXXXXX.ngrok.io/inbound).

    Once configured, sending an email to [anything]@inbound.yourdomain.com will trigger the listener.

    # Clone and prepare
    git clone https://github.com/sendgrid/sendgrid-csharp.git
    cd sendgrid-csharp/examples/inbound-webhook-handler
    dotnet restore
    
    # Run the listener
    dotnet run --project .\Src\Inbound\Inbound.csproj
    
    # Expose to the internet
    ngrok http PORT_NUMBER
  8. Setup Twilio Email (Pilot)

    main

    To use the Twilio Email client, you must first obtain a Twilio account and set up environment variables for authentication. The TwilioEmailClient provides the same interface as the SendGrid client.

    Authentication Options:

    1. API Key and Secret
    2. Account SID and Auth Token

    Environment Variable Setup (Linux/Mac):

    echo "export TWILIO_API_KEY='YOUR_TWILIO_API_KEY'" > twilio.env
    echo "export TWILIO_API_SECRET='YOUR_TWILIO_API_SECRET'" >> twilio.env
    source ./twilio.env

    Environment Variable Setup (Windows):

    setx TWILIO_API_KEY "YOUR_TWILIO_API_KEY"
    setx TWILIO_API_SECRET "YOUR_TWILIO_API_SECRET"
    // Using API Key/Secret
    var mailClient = new TwilioEmailClient(Environment.GetEnvironmentVariable("TWILIO_API_KEY"), Environment.GetEnvironmentVariable("TWILIO_API_SECRET"));
    
    // OR using Account SID/Auth Token
    var mailClient = new TwilioEmailClient(Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"), Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN"));
  9. Quick Start with the Example Project

    main

    To see the Mail helper in action, you can run the ExampleCoreProject.

    Prerequisites: Ensure you have set your SENDGRID_API_KEY environment variable before running the project.

    Steps:

    1. Navigate to the ExampleCoreProject directory.
    2. Run the project (e.g., via dotnet run or by clicking Start in your IDE).
    3. Observe how the Mail object is instantiated and used to send an email.