feat(email): add delivery adapters
CI and Deploy / test (pull_request) Failing after 1m37s
CI and Deploy / deploy (pull_request) Has been skipped

Gmail and Graph request explicit send consent and classify provider rejection separately from uncertain transport failure. IMAP remains read-only; no send API is exposed.
This commit is contained in:
cesnimda
2026-08-09 23:47:21 +02:00
parent 429f427f49
commit e9937accd8
11 changed files with 331 additions and 9 deletions
@@ -6,6 +6,7 @@ using JobTrackerApi.Models;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using JobTrackerApi.Services.EmailProviders;
namespace JobTrackerApi.Services;
@@ -19,12 +20,15 @@ public interface IMicrosoftGraphOAuthService
Task<IReadOnlyList<MicrosoftGraphMessageSummary>> ListMessagesAsync(string ownerUserId, string? query, int maxResults, CancellationToken cancellationToken);
Task<IReadOnlyList<MicrosoftGraphMessageSummary>> ListThreadMessagesAsync(string ownerUserId, string conversationId, CancellationToken cancellationToken);
Task<MicrosoftGraphMessageDetail> GetMessageAsync(string ownerUserId, string messageId, CancellationToken cancellationToken);
Task<MicrosoftGraphSendResult> SendAsync(string ownerUserId, MicrosoftGraphSendRequest request, CancellationToken cancellationToken);
}
public sealed record MicrosoftGraphOAuthExchangeResult(string MailAddress);
public sealed record MicrosoftGraphMessageSummary(string Id, string ConversationId, string Subject, string From, string To, DateTimeOffset? Date, string Snippet);
public sealed record MicrosoftGraphMessageAttachment(string? FileName, string? MimeType, long? SizeBytes, string? GraphAttachmentId, bool Inline);
public sealed record MicrosoftGraphMessageDetail(string Id, string ConversationId, string Subject, string From, string To, DateTimeOffset? Date, string Snippet, string BodyText, string? BodyHtml, IReadOnlyList<string> Labels, IReadOnlyList<MicrosoftGraphMessageAttachment> Attachments);
public sealed record MicrosoftGraphSendRequest(string To, string Subject, string BodyText);
public sealed record MicrosoftGraphSendResult();
internal sealed class MicrosoftGraphTokenResponse
{
@@ -42,7 +46,8 @@ internal sealed class MicrosoftGraphTokenResponse
/// </summary>
public sealed class MicrosoftGraphOAuthService : IMicrosoftGraphOAuthService
{
private const string Scope = "openid email profile offline_access https://graph.microsoft.com/Mail.Read";
public const string SendScope = "https://graph.microsoft.com/Mail.Send";
private const string Scope = $"openid email profile offline_access https://graph.microsoft.com/Mail.Read {SendScope}";
private readonly IConfiguration _cfg;
private readonly JobTrackerContext _db;
private readonly IDataProtector _protector;
@@ -280,6 +285,69 @@ public sealed class MicrosoftGraphOAuthService : IMicrosoftGraphOAuthService
}
}
public async Task<MicrosoftGraphSendResult> SendAsync(string ownerUserId, MicrosoftGraphSendRequest request, CancellationToken cancellationToken)
{
var connection = await _db.MicrosoftGraphConnections.AsNoTracking().FirstOrDefaultAsync(item => item.OwnerUserId == ownerUserId, cancellationToken);
if (connection is null || !HasSendScope(connection.Scope))
throw new EmailProviderDeliveryException("reauthorization_required", false, "Reconnect Outlook and approve send access before sending.");
ValidateSendRequest(request.To, request.Subject, request.BodyText);
var payload = JsonSerializer.Serialize(new
{
message = new
{
subject = request.Subject.Trim(),
body = new { contentType = "Text", content = request.BodyText },
toRecipients = new[] { new { emailAddress = new { address = request.To.Trim() } } },
},
saveToSentItems = true,
});
try
{
var accessToken = await GetValidAccessTokenAsync(ownerUserId, cancellationToken);
var client = _httpClientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using var response = await client.PostAsync(
"https://graph.microsoft.com/v1.0/me/sendMail",
new StringContent(payload, System.Text.Encoding.UTF8, "application/json"),
cancellationToken);
if (!response.IsSuccessStatusCode)
{
var category = response.StatusCode is System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.Forbidden
? "reauthorization_required"
: "provider_rejected";
throw new EmailProviderDeliveryException(category, false, "Microsoft Graph rejected the send request.");
}
return new MicrosoftGraphSendResult();
}
catch (EmailProviderDeliveryException)
{
throw;
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
{
throw new EmailProviderDeliveryException("transport_interrupted", true, "Outlook delivery status is uncertain.", ex);
}
}
public static bool HasSendScope(string? scope)
{
if (string.IsNullOrWhiteSpace(scope)) return false;
return scope.Split(' ', StringSplitOptions.RemoveEmptyEntries).Any(value =>
string.Equals(value, SendScope, StringComparison.OrdinalIgnoreCase) ||
string.Equals(value, "Mail.Send", StringComparison.OrdinalIgnoreCase));
}
private static void ValidateSendRequest(string to, string subject, string bodyText)
{
if (string.IsNullOrWhiteSpace(to)) throw new ArgumentException("Recipient is required.", nameof(to));
if (string.IsNullOrWhiteSpace(subject)) throw new ArgumentException("Subject is required.", nameof(subject));
if (string.IsNullOrWhiteSpace(bodyText)) throw new ArgumentException("Body is required.", nameof(bodyText));
if (to.Length > 320 || subject.Length > 998 || bodyText.Length > 200_000) throw new ArgumentException("Email content exceeds the supported limit.");
}
private static async Task<IReadOnlyList<MicrosoftGraphMessageAttachment>> ListAttachmentsAsync(HttpClient client, string messageId, CancellationToken cancellationToken)
{
var url = $"https://graph.microsoft.com/v1.0/me/messages/{Uri.EscapeDataString(messageId)}/attachments?$select=id,name,contentType,size,isInline";