Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ private static SendEmailRequest TemplateBasedRequest()
- Tracking opt-outs management – [`examples/Mailtrap.Example.TrackingOptOut`](examples/Mailtrap.Example.TrackingOptOut/)
- Email logs (list with filters and pagination; get message details with events) – [`examples/Mailtrap.Example.EmailLogs`](examples/Mailtrap.Example.EmailLogs/)
- Email sending statistics – [`examples/Mailtrap.Example.Stats`](examples/Mailtrap.Example.Stats/)
- Webhooks management – [`examples/Mailtrap.Example.Webhooks`](examples/Mailtrap.Example.Webhooks/)
- Webhooks management, including campaigns webhooks – [`examples/Mailtrap.Example.Webhooks`](examples/Mailtrap.Example.Webhooks/)
- Verifying webhook signatures – [`examples/Mailtrap.Example.WebhookSignature`](examples/Mailtrap.Example.WebhookSignature/)

### Inbound Email
Expand All @@ -295,7 +295,7 @@ private static SendEmailRequest TemplateBasedRequest()

### Email Marketing

- Email campaigns management (CRUD, lifecycle actions, and statistics) – [`examples/Mailtrap.Example.EmailCampaigns`](examples/Mailtrap.Example.EmailCampaigns/)
- Email campaigns management (CRUD, lifecycle actions, subscription topic, and statistics) – [`examples/Mailtrap.Example.EmailCampaigns`](examples/Mailtrap.Example.EmailCampaigns/)
- Email Marketing statistics (campaigns and automations) – [`examples/Mailtrap.Example.MarketingStats`](examples/Mailtrap.Example.MarketingStats/)
- Subscription topics (list and get) – [`examples/Mailtrap.Example.SubscriptionTopics`](examples/Mailtrap.Example.SubscriptionTopics/)

Expand Down
24 changes: 23 additions & 1 deletion examples/Mailtrap.Example.EmailCampaigns/EmailCampaigns.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using System.Globalization;
using System.Net;

using Mailtrap;
using Mailtrap.Core.Exceptions;
using Mailtrap.EmailCampaigns;
using Mailtrap.EmailCampaigns.Models;
using Mailtrap.EmailCampaigns.Requests;
using Mailtrap.SubscriptionTopics.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -80,7 +83,10 @@
BodyHtml = "<html><body><h1>Hi {{first_name}}!</h1>" +
"<p><a href=\"__unsubscribe_url__\">Unsubscribe</a></p></body></html>",
MergeTags = ["first_name"]
}
},
// Send the campaign under a subscription topic that covers its sending domain.
// A campaign's topic can be changed later, but not removed.
SubscriptionTopicId = await FindSubscriptionTopicId(mailtrapClient, campaign.DomainId)
};
campaign = await campaignResource.Update(updateRequest);
logger.LogInformation("Updated campaign {Id}.", campaign.Id);
Expand Down Expand Up @@ -147,4 +153,20 @@ internal sealed partial class Program
// Kept outside the top-level statements to stay within the CA1506 coupling limit.
private static string FormatDate(DateTimeOffset date) =>
date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

// The first subscription topic that covers the domain (a topic without a domain covers every domain);
// null when there is none, or when the account has no subscription topics.
private static async Task<long?> FindSubscriptionTopicId(IMailtrapClient mailtrapClient, long domainId)
{
try
{
SubscriptionTopicList topics = await mailtrapClient.SubscriptionTopics().GetAll();

return topics.Data.FirstOrDefault(t => t.DomainId is null || t.DomainId == domainId)?.Id;
}
catch (HttpRequestFailedException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
{
return null;
}
}
}
19 changes: 19 additions & 0 deletions examples/Mailtrap.Example.Webhooks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,25 @@
// The webhook resource becomes invalid after deletion and should not be used anymore
Webhook deletedWebhook = await webhookResource.Delete();
logger.LogInformation("Webhook Deleted: Id={Id}", deletedWebhook.Id);

// Create a "campaigns" webhook: it takes event types but no sending stream.
// "subscription_preferences_update" is available only for campaigns webhooks
// and for email_sending webhooks of the bulk stream.
var campaignsRequest = new CreateWebhookRequest
{
Url = new Uri("https://example.com/webhooks/mailtrap-campaigns"),
WebhookType = WebhookType.Campaigns
};
campaignsRequest.EventTypes.Add(WebhookEventType.Delivery);
campaignsRequest.EventTypes.Add(WebhookEventType.SubscriptionPreferencesUpdate);

CreateWebhookResponse campaignsWebhook = await webhooksResource.Create(campaignsRequest);
logger.LogInformation("Created campaigns Webhook: Id={Id}, EventTypes={EventTypes}",
campaignsWebhook.Id,
string.Join(",", campaignsWebhook.EventTypes));

await accountResource.Webhook(campaignsWebhook.Id).Delete();
logger.LogInformation("Webhook Deleted: Id={Id}", campaignsWebhook.Id);
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,4 +218,16 @@ public sealed record EmailCampaign
[JsonPropertyName("template")]
[JsonPropertyOrder(19)]
public EmailCampaignTemplate? Template { get; set; }

/// <summary>
/// Gets or sets the identifier of the subscription topic the campaign is sent under,
/// as returned by the Subscription Topics endpoints.
/// </summary>
///
/// <value>
/// Subscription topic identifier, or <see langword="null"/> when the campaign has no topic.
/// </value>
[JsonPropertyName("subscription_topic_id")]
[JsonPropertyOrder(20)]
public long? SubscriptionTopicId { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,24 @@ public sealed record CreateEmailCampaignRequest : IValidatable
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IList<long>? ContactSegmentIds { get; set; }

/// <summary>
/// Gets or sets the identifier of the subscription topic the campaign is sent under,
/// as returned by the Subscription Topics endpoints.<br/>
/// The topic must not be deleted and must cover the campaign's sending domain.
/// </summary>
///
/// <value>
/// Subscription topic identifier, or <see langword="null"/> to omit.
/// </value>
///
/// <remarks>
/// For an account without subscription topics, the API ignores this field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The API ignores this field only when subscription topics aren't enabled for the account. An account that has the feature but no topic with this ID gets a 422 "does not exist", so "an account without subscription topics" reads wrong for that case. The same sentence is in UpdateEmailCampaignRequest.

/// </remarks>
[JsonPropertyName("subscription_topic_id")]
[JsonPropertyOrder(11)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? SubscriptionTopicId { get; set; }


/// <inheritdoc/>
public ValidationResult Validate()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,25 @@ public sealed record UpdateEmailCampaignRequest : IValidatable
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IList<long>? ContactSegmentIds { get; set; }

/// <summary>
/// Gets or sets the identifier of the subscription topic the campaign is sent under,
/// as returned by the Subscription Topics endpoints.<br/>
/// The topic must not be deleted and must cover the campaign's sending domain.
/// A campaign's topic can be changed, but not removed.
/// </summary>
///
/// <value>
/// Subscription topic identifier, or <see langword="null"/> to leave unchanged.
/// </value>
///
/// <remarks>
/// For an account without subscription topics, the API ignores this field.
/// </remarks>
[JsonPropertyName("subscription_topic_id")]
[JsonPropertyOrder(11)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? SubscriptionTopicId { get; set; }


/// <inheritdoc/>
public ValidationResult Validate()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ namespace Mailtrap.EmailCampaigns.Validators;

/// <summary>
/// Validator for <see cref="CreateEmailCampaignRequest"/>.<br/>
/// Ensures the campaign name, sending domain identifier, From local part and template subject are provided.
/// Ensures the campaign name, sending domain identifier, From local part and template subject are provided,
/// and that a provided subscription topic identifier is positive.
/// </summary>
public sealed class CreateEmailCampaignRequestValidator : AbstractValidator<CreateEmailCampaignRequest>
{
Expand Down Expand Up @@ -41,5 +42,12 @@ public CreateEmailCampaignRequestValidator()
.NotEmpty()
.WithMessage("'TemplateAttributes.Subject' must not be empty.");
});

When(r => r.SubscriptionTopicId is not null, () =>
{
RuleFor(r => r.SubscriptionTopicId)
.GreaterThan(0)
.WithMessage("'SubscriptionTopicId' must be a positive subscription topic ID.");
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace Mailtrap.EmailCampaigns.Validators;

/// <summary>
/// Validator for <see cref="UpdateEmailCampaignRequest"/>.<br/>
/// All fields are optional; ensures a provided sending domain identifier is positive.
/// All fields are optional; ensures a provided sending domain or subscription topic identifier is positive.
/// </summary>
public sealed class UpdateEmailCampaignRequestValidator : AbstractValidator<UpdateEmailCampaignRequest>
{
Expand All @@ -23,5 +23,12 @@ public UpdateEmailCampaignRequestValidator()
.GreaterThan(0)
.WithMessage("'DomainId' must be a positive sending domain ID.");
});

When(r => r.SubscriptionTopicId is not null, () =>
{
RuleFor(r => r.SubscriptionTopicId)
.GreaterThan(0)
.WithMessage("'SubscriptionTopicId' must be a positive subscription topic ID.");
});
}
}
6 changes: 3 additions & 3 deletions src/Mailtrap.Abstractions/Webhooks/Models/Webhook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public record Webhook
/// </summary>
///
/// <value>
/// Webhook type. Allowed values: "email_sending", "audit_log".
/// Webhook type. Allowed values: "email_sending", "audit_log", "inbound_receiving", "campaigns".
/// </value>
[JsonPropertyName("webhook_type")]
[JsonPropertyOrder(4)]
Expand Down Expand Up @@ -75,7 +75,7 @@ public record Webhook

/// <summary>
/// Gets or sets the domain ID the webhook is scoped to.<br/>
/// Applicable only for <c>email_sending</c> webhooks; <see langword="null"/> means all domains.
/// Applicable only for <c>email_sending</c> and <c>campaigns</c> webhooks; <see langword="null"/> means all domains.
/// </summary>
///
/// <value>
Expand All @@ -87,7 +87,7 @@ public record Webhook

/// <summary>
/// Gets or sets the list of event types the webhook is subscribed to.<br/>
/// Applicable only for <c>email_sending</c> webhooks.
/// Applicable only for <c>email_sending</c> and <c>campaigns</c> webhooks.
/// </summary>
///
/// <value>
Expand Down
13 changes: 12 additions & 1 deletion src/Mailtrap.Abstractions/Webhooks/Models/WebhookEventType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace Mailtrap.Webhooks.Models;


/// <summary>
/// Event type the <c>email_sending</c> webhook can subscribe to.
/// Event type the <c>email_sending</c> and <c>campaigns</c> webhooks can subscribe to.
/// </summary>
public sealed record WebhookEventType : StringEnum<WebhookEventType>
{
Expand Down Expand Up @@ -50,4 +50,15 @@ public sealed record WebhookEventType : StringEnum<WebhookEventType>
/// Gets the value representing "reject" event.
/// </summary>
public static readonly WebhookEventType Reject = Define("reject");

/// <summary>
/// Gets the value representing "subscription_preferences_update" event:
/// a recipient changed their subscription preferences.
/// </summary>
///
/// <remarks>
/// Available only for <c>campaigns</c> webhooks and <c>email_sending</c> webhooks of the bulk stream;
/// the API rejects it for the transactional stream.
/// </remarks>
public static readonly WebhookEventType SubscriptionPreferencesUpdate = Define("subscription_preferences_update");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[should] The live API doesn't accept subscription_preferences_update yet – it quietly drops event types it doesn't know. So today a campaigns webhook created with delivery and this event comes back with only delivery, a webhook with just this event gets a 422 "can't be blank", and a transactional webhook isn't refused. Could you hold this value and the example lines that use it until the API change that adds the event is live, or release them separately from the campaign topic and the campaigns type, which already work?

}
9 changes: 9 additions & 0 deletions src/Mailtrap.Abstractions/Webhooks/Models/WebhookType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,13 @@ public sealed record WebhookType : StringEnum<WebhookType>
/// Represents "inbound_receiving" webhook type.
/// </value>
public static readonly WebhookType InboundReceiving = Define("inbound_receiving");

/// <summary>
/// Gets the value representing "campaigns" webhook type: events of the account's email campaigns.
/// </summary>
///
/// <value>
/// Represents "campaigns" webhook type.
/// </value>
public static readonly WebhookType Campaigns = Define("campaigns");
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public sealed record CreateWebhookRequest : IValidatable
/// </summary>
///
/// <value>
/// Webhook type. Allowed values: "email_sending", "audit_log".
/// Webhook type. Allowed values: "email_sending", "audit_log", "inbound_receiving", "campaigns".
/// </value>
[JsonPropertyName("webhook_type")]
[JsonPropertyOrder(2)]
Expand Down Expand Up @@ -69,7 +69,7 @@ public sealed record CreateWebhookRequest : IValidatable

/// <summary>
/// Gets the list of event types to subscribe to.<br/>
/// Required for <c>email_sending</c> webhook type.
/// Required for <c>email_sending</c> and <c>campaigns</c> webhook types.
/// </summary>
///
/// <value>
Expand All @@ -83,7 +83,7 @@ public sealed record CreateWebhookRequest : IValidatable
/// <summary>
/// Gets or sets the domain ID to scope the webhook to.<br/>
/// When omitted, the webhook applies to all domains.<br/>
/// Applicable only for <c>email_sending</c> webhooks.
/// Applicable only for <c>email_sending</c> and <c>campaigns</c> webhooks.
/// </summary>
///
/// <value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public sealed record UpdateWebhookRequest : IValidatable

/// <summary>
/// Gets or sets the list of event types the webhook subscribes to.<br/>
/// Applicable only for <c>email_sending</c> webhooks.<br/>
/// Applicable only for <c>email_sending</c> and <c>campaigns</c> webhooks.<br/>
/// Leave <see langword="null"/> to keep the existing event types unchanged.
/// </summary>
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ namespace Mailtrap.Webhooks.Validators;
/// <summary>
/// Validator for <see cref="CreateWebhookRequest"/>.<br/>
/// Ensures Url is an absolute URI, WebhookType is set,
/// and that <c>email_sending</c> webhooks specify SendingStream and EventTypes.
/// that <c>email_sending</c> webhooks specify SendingStream and EventTypes,
/// and that <c>campaigns</c> webhooks specify EventTypes and no SendingStream.
/// </summary>
public sealed class CreateWebhookRequestValidator : AbstractValidator<CreateWebhookRequest>
{
Expand Down Expand Up @@ -33,10 +34,20 @@ public CreateWebhookRequestValidator()
RuleFor(r => r.SendingStream)
.NotNull()
.WithMessage("'SendingStream' is required for 'email_sending' webhook type.");
});

When(r => r.WebhookType == WebhookType.Campaigns, () =>
{
RuleFor(r => r.SendingStream)
.Null()
.WithMessage("'SendingStream' must not be set for 'campaigns' webhook type.");
});

When(r => r.WebhookType == WebhookType.EmailSending || r.WebhookType == WebhookType.Campaigns, () =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[could] No test covers the email_sending half of this condition. I dropped r.WebhookType == WebhookType.EmailSending || and every unit and integration test still passed, so an email_sending webhook without event types (and the new interpolated message) isn't checked anywhere. A case next to Validate_CampaignsWebhookWithoutEventTypes_ShouldFail for email_sending would cover it.

{
RuleFor(r => r.EventTypes)
.Must(events => events is { Count: > 0 })
.WithMessage("'EventTypes' must contain at least one event for 'email_sending' webhook type.");
.WithMessage(r => $"'EventTypes' must contain at least one event for '{r.WebhookType}' webhook type.");
Comment thread
Rabsztok marked this conversation as resolved.
Resolved
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public async Task GetAll_Success()
campaign.RecipientTotalCount.Should().BeNull();
campaign.ContactListIds.Should().Equal(55, 56);
campaign.ContactSegmentIds.Should().Equal(12);
campaign.SubscriptionTopicId.Should().BeNull();

// The list endpoint omits template bodies.
campaign.Template.Should().NotBeNull();
Expand Down Expand Up @@ -207,6 +208,7 @@ public async Task GetDetails_Success()
result.Template.MergeTags.Should().Equal("first_name");
result.Template.BodyHtml.Should().Contain("__unsubscribe_url__");
result.Template.BodyText.Should().BeNull();
result.SubscriptionTopicId.Should().Be(12);
}

[Test]
Expand Down Expand Up @@ -237,7 +239,8 @@ public async Task Create_Success()
Subject = "Spring is here — 30% off"
},
ContactListIds = [55, 56],
ContactSegmentIds = [12]
ContactSegmentIds = [12],
SubscriptionTopicId = 12
};

using var responseContent = await Feature.LoadFileToStringContent();
Expand Down Expand Up @@ -412,7 +415,8 @@ public async Task Update_Success()
MergeTags = ["first_name"]
},
ContactListIds = [55],
ContactSegmentIds = []
ContactSegmentIds = [],
SubscriptionTopicId = 15
};

using var responseContent = await Feature.LoadFileToStringContent();
Expand Down Expand Up @@ -458,6 +462,7 @@ public async Task Update_Success()
result.ContactSegmentIds.Should().BeEmpty();
result.Template.Should().NotBeNull();
result.Template!.Subject.Should().Be("New subject");
result.SubscriptionTopicId.Should().Be(15);
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"id": 789,
"subject": "Spring is here — 30% off",
"merge_tags": []
}
},
"subscription_topic_id": null
}
],
"pagination": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"merge_tags": ["first_name"],
"body_html": "<html><body><h1>Hi {{first_name}}!</h1><p><a href=\"__unsubscribe_url__\">Unsubscribe</a></p></body></html>",
"body_text": null
}
},
"subscription_topic_id": 12
}
}
Loading