using Microsoft.Graph.Models; using Microsoft.Graph.Users.Item.SendMail; using SharepointToolbox.Web.Core.Models; using SharepointToolbox.Web.Infrastructure.Auth; namespace SharepointToolbox.Web.Services.Reports; /// /// Delivers a generated report by email through Graph. Uses the client's app-only /// (certificate) Graph client, which has no signed-in user, so it posts to /// /users/{From}/sendMail — the configured sender mailbox must exist in the /// tenant and the app registration must hold the Mail.Send application role. /// public class ReportMailService : IReportMailService { // Graph caps a single sendMail request at ~4 MB total; larger files need an upload // session we don't implement. Reject early with a clear message instead of a 413. private const long MaxAttachmentBytes = 3 * 1024 * 1024; private readonly IAppOnlyContextFactory _appOnly; public ReportMailService(IAppOnlyContextFactory appOnly) { _appOnly = appOnly; } public async Task SendAsync( TenantProfile profile, ScheduledReport schedule, ReportEmailSettings settings, string fileName, string mime, byte[] bytes, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(settings.From)) throw new InvalidOperationException("No sender mailbox (From) configured for report email."); var to = CleanAddresses(settings.To); var cc = CleanAddresses(settings.Cc); if (to.Count == 0 && cc.Count == 0) throw new InvalidOperationException("Report email has no To or Cc recipients."); var message = new Message { Subject = Substitute(settings.Subject, profile, schedule, fileName), Body = new ItemBody { ContentType = BodyType.Html, Content = Substitute(settings.Body, profile, schedule, fileName) }, ToRecipients = to.Select(Recipient).ToList(), CcRecipients = cc.Select(Recipient).ToList(), }; if (bytes.LongLength > MaxAttachmentBytes) throw new InvalidOperationException( $"Report '{fileName}' is {bytes.LongLength / 1024.0 / 1024.0:F1} MB — too large to email " + $"(Graph sendMail limit ~{MaxAttachmentBytes / 1024 / 1024} MB)."); message.Attachments = new List { new FileAttachment { OdataType = "#microsoft.graph.fileAttachment", Name = fileName, ContentType = mime, ContentBytes = bytes, } }; var graph = await _appOnly.CreateGraphClientAsync(profile, ct); await graph.Users[settings.From].SendMail.PostAsync( new SendMailPostRequestBody { Message = message, SaveToSentItems = false }, cancellationToken: ct); } private static List CleanAddresses(IEnumerable raw) => raw.Select(a => a?.Trim() ?? string.Empty) .Where(a => a.Length > 0) .Distinct(StringComparer.OrdinalIgnoreCase) .ToList(); private static Recipient Recipient(string address) => new() { EmailAddress = new EmailAddress { Address = address } }; private static string Substitute(string template, TenantProfile profile, ScheduledReport schedule, string fileName) => (template ?? string.Empty) .Replace("{ReportName}", schedule.Name) .Replace("{ClientName}", profile.Name) .Replace("{ReportType}", schedule.Type.ToString()) .Replace("{FileName}", fileName) .Replace("{DateUtc}", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm")); }