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
7 changes: 7 additions & 0 deletions Mailtrap.sln
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mailtrap.Example.Factory",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mailtrap.Example.Contact", "examples\Mailtrap.Example.Contact\Mailtrap.Example.Contact.csproj", "{3F8D2B21-5C6E-4A9A-9C3B-9F1D2A7B8C64}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mailtrap.Example.ContactImports", "examples\Mailtrap.Example.ContactImports\Mailtrap.Example.ContactImports.csproj", "{E7B8C1F2-9A3D-4C2E-8B7A-6D2F3A1E4B5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -167,6 +169,10 @@ Global
{3F8D2B21-5C6E-4A9A-9C3B-9F1D2A7B8C64}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3F8D2B21-5C6E-4A9A-9C3B-9F1D2A7B8C64}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3F8D2B21-5C6E-4A9A-9C3B-9F1D2A7B8C64}.Release|Any CPU.Build.0 = Release|Any CPU
{E7B8C1F2-9A3D-4C2E-8B7A-6D2F3A1E4B5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7B8C1F2-9A3D-4C2E-8B7A-6D2F3A1E4B5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7B8C1F2-9A3D-4C2E-8B7A-6D2F3A1E4B5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7B8C1F2-9A3D-4C2E-8B7A-6D2F3A1E4B5C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -190,6 +196,7 @@ Global
{F6357CAB-06C6-4603-99E7-1EDB79ACA8E8} = {09E18837-1DDE-4EAF-80EC-DA55557C81EB}
{AB1237F4-D074-4D3C-9AE4-6794BD30EA71} = {09E18837-1DDE-4EAF-80EC-DA55557C81EB}
{3F8D2B21-5C6E-4A9A-9C3B-9F1D2A7B8C64} = {09E18837-1DDE-4EAF-80EC-DA55557C81EB}
{E7B8C1F2-9A3D-4C2E-8B7A-6D2F3A1E4B5C} = {09E18837-1DDE-4EAF-80EC-DA55557C81EB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0FF614CC-FEBC-4C66-B3FC-FCB73EE511D7}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" VersionOverride="9.0.8" />
<PackageReference Include="System.Text.Json" VersionOverride="9.0.7" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
69 changes: 69 additions & 0 deletions examples/Mailtrap.Example.ContactImports/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using Mailtrap;
using Mailtrap.Accounts;
using Mailtrap.Contacts;
using Mailtrap.Contacts.Requests;
using Mailtrap.ContactImports;
using Mailtrap.ContactImports.Models;
using Mailtrap.ContactImports.Requests;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;



HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);

IConfigurationSection config = hostBuilder.Configuration.GetSection("Mailtrap");

hostBuilder.Services.AddMailtrapClient(config);

using IHost host = hostBuilder.Build();

ILogger<Program> logger = host.Services.GetRequiredService<ILogger<Program>>();
IMailtrapClient mailtrapClient = host.Services.GetRequiredService<IMailtrapClient>();

try
{
var accountId = 12345;
IAccountResource accountResource = mailtrapClient.Account(accountId);

// Get resource for contacts collection
IContactCollectionResource contactsResource = accountResource.Contacts();

//Get resource for contact imports collection
IContactsImportCollectionResource contactsImportsResource = contactsResource.Imports();

// Prepare list of contacts to import
var contactImportList = new List<ContactImportRequest>
{
new("alice@mailtrap.io"),
new("bob@mailtrap.io"),
new("charlie@mailtrap.io"),
};

// Create contacts import request
var importRequest = new ContactsImportRequest(contactImportList);

// Import contacts in bulk
ContactsImport importResponse = await contactsImportsResource.Create(importRequest);
logger.LogInformation("Created contact import: {Import}", importResponse);

// Get resource for specific contact import
IContactsImportResource contactsImportResource = contactsResource.Import(importResponse.Id);

// Get details of specific contact import
ContactsImport contactsImportDetails = await contactsImportResource.GetDetails();
logger.LogInformation("Contacts Import Details: {Details}", contactsImportDetails);

if (contactsImportDetails.Status == ContactsImportStatus.Failed)
{
logger.LogWarning("Import failed!");
}
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred during API call.");
Environment.FailFast(ex.Message);
throw;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"Project": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
17 changes: 17 additions & 0 deletions examples/Mailtrap.Example.ContactImports/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"System": "Warning",
"Microsoft": "Warning"
},
"Debug": {
"LogLevel": {
"Default": "Debug"
}
}
},
"Mailtrap": {
"ApiToken": "<API_KEY>"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace Mailtrap.ContactImports;

/// <summary>
/// Represents Contact imports collection resource.
/// </summary>
public interface IContactsImportCollectionResource : IRestResource
{
/// <summary>
/// Import contacts in bulk with support for custom fields and list management.
/// Existing contacts with matching email addresses will be updated automatically.
/// You can import up to 50,000 contacts per request.
/// The import process runs asynchronously - use the returned
/// import ID to check the status and results.
/// List all contacts with details into <paramref name="request"/>.
/// </summary>
///
/// <param name="request">
/// Request containing contact list for import.
/// </param>
///
/// <param name="cancellationToken">
/// Token to control operation cancellation.
/// </param>
///
/// <returns>
/// Contact import id and status.
/// </returns>
public Task<ContactsImport> Create(ContactsImportRequest request, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace Mailtrap.ContactImports;

/// <summary>
/// Represents Contact import resource.
/// </summary>
public interface IContactsImportResource : IRestResource
{
/// <summary>
/// Gets details of the contact import, represented by the current resource instance.
/// </summary>
///
/// <param name="cancellationToken">
/// Token to control operation cancellation.
/// </param>
///
/// <returns>
/// Requested contact import details.
/// </returns>
public Task<ContactsImport> GetDetails(CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
namespace Mailtrap.ContactImports.Models;

/// <summary>
/// Generic response object for contact imports operations.
/// </summary>
public record ContactsImport
{
/// <summary>
/// Gets created contact imports identifier.
/// </summary>
///
/// <value>
/// Contact imports identifier.
/// </value>
[JsonPropertyName("id")]
[JsonPropertyOrder(1)]
[JsonRequired]
public long Id { get; set; }

/// <summary>
/// Gets contact imports status.
/// </summary>
///
/// <value>
/// Contact imports status.
/// </value>
[JsonPropertyName("status")]
[JsonPropertyOrder(2)]
public ContactsImportStatus Status { get; set; } = ContactsImportStatus.Unknown;

/// <summary>
/// Gets count of created contacts.
/// </summary>
///
/// <value>
/// Count of created contacts.
/// </value>
[JsonPropertyName("created_contacts_count")]
[JsonPropertyOrder(3)]
public long? CreatedContactsCount { get; set; }

/// <summary>
/// Gets count of updated contacts.
/// </summary>
///
/// <value>
/// Count of updated contacts.
/// </value>
[JsonPropertyName("updated_contacts_count")]
[JsonPropertyOrder(4)]
public long? UpdatedContactsCount { get; set; }

/// <summary>
/// Gets count of contacts over limit.
/// </summary>
///
/// <value>
/// Count of contacts over limit.
/// </value>
[JsonPropertyName("contacts_over_limit_count")]
[JsonPropertyOrder(5)]
public long? ContactsOverLimitCount { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace Mailtrap.ContactImports.Models;


/// <summary>
/// Represents status of the contact imports.
/// </summary>
public sealed record ContactsImportStatus : StringEnum<ContactsImportStatus>
{
/// <summary>
/// Gets the value representing "created" status.
/// </summary>
///
/// <value>
/// Represents "created" status.
/// </value>
public static ContactsImportStatus Created { get; } = Define("created");

/// <summary>
/// Gets the value representing "started" status.
/// </summary>
///
/// <value>
/// Represents "started" status.
/// </value>
public static ContactsImportStatus Started { get; } = Define("started");

/// <summary>
/// Gets the value representing "finished" status.
/// </summary>
///
/// <value>
/// Represents "finished" status.
/// </value>
public static ContactsImportStatus Finished { get; } = Define("finished");

/// <summary>
/// Gets the value representing "failed" status.
/// </summary>
///
/// <value>
/// Represents "failed" status.
/// </value>
public static ContactsImportStatus Failed { get; } = Define("failed");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
namespace Mailtrap.ContactImports.Requests;

/// <summary>
/// Generic request object for contact CRUD operations.
/// </summary>
public record ContactsImportRequest : IValidatable
{
/// <summary>
/// Gets contact collection for import.
/// </summary>
///
/// <value>
/// Contact collection for import.
/// </value>
[JsonPropertyName("contacts")]
[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
public IList<ContactImportRequest> Contacts { get; } = [];

/// <summary>
/// Primary instance constructor.
/// </summary>
///
/// <param name="contacts">
/// Collection of contacts to import.
/// </param>
///
/// /// <remarks>
/// Each contact in the <paramref name="contacts"/> must include a valid email.
/// Size and item-level constraints are validated by <see cref="Validate"/>.
/// </remarks>
///
/// <exception cref="ArgumentNullException">
/// When <paramref name="contacts"/> is <see langword="null"/> or empty.
/// </exception>
/// <para>
/// Use <see cref="Validate"/> to ensure the count is within the allowed range
/// (currently 1–50,000) and each contact satisfies per-item rules.
/// </para>
public ContactsImportRequest(IEnumerable<ContactImportRequest> contacts)
{
Ensure.NotNullOrEmpty(contacts, nameof(contacts));

// Defensive copy to prevent post-ctor mutation.
Contacts = contacts is List<ContactImportRequest> list
? new List<ContactImportRequest>(list) // defensive copy when already a List<T>
: new List<ContactImportRequest>(contacts); // otherwise enumerate once
}

/// <summary>
/// Parameterless instance constructor for serializers.
/// </summary>
public ContactsImportRequest() { }

/// <inheritdoc/>
public ValidationResult Validate()
{
return ContactsImportRequestValidator.Instance
.Validate(this)
.ToMailtrapValidationResult();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace Mailtrap.ContactImports.Validators;


/// <summary>
/// Validator for Create/Update contact requests.<br />
/// Ensures contact's email is not empty and length is within the allowed range.
/// </summary>
internal sealed class ContactsImportRequestValidator : AbstractValidator<ContactsImportRequest>
{
public const int MaxContactsPerRequest = 50_000;
public const int MinContactsPerRequest = 1;
/// <summary>
/// Static validator instance for reuse.
/// </summary>
public static ContactsImportRequestValidator Instance { get; } = new();

/// <summary>
/// Primary constructor.
/// </summary>
public ContactsImportRequestValidator()
{
RuleFor(r => r.Contacts)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Must(list => list != null && list.Count is >= MinContactsPerRequest and <= MaxContactsPerRequest);

RuleForEach(r => r.Contacts)
.NotNull()
.SetValidator(ContactRequestValidator.Instance);
}
}
Loading