-
Notifications
You must be signed in to change notification settings - Fork 416
Expand file tree
/
Copy pathMessagesController.cs
More file actions
651 lines (572 loc) · 30.1 KB
/
MessagesController.cs
File metadata and controls
651 lines (572 loc) · 30.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Rnwood.Smtp4dev.ApiModel;
using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using Message = Rnwood.Smtp4dev.DbModel.Message;
using Rnwood.Smtp4dev.Server;
using Rnwood.Smtp4dev.Data;
using Rnwood.Smtp4dev.DbModel;
using NSwag.Annotations;
using Rnwood.Smtp4dev.Server.Settings;
using Org.BouncyCastle.Cms;
using StreamLib;
using System.Text;
using Rnwood.SmtpServer;
using Microsoft.AspNetCore.Http;
using MimeKit;
using HtmlAgilityPack;
using Serilog;
namespace Rnwood.Smtp4dev.Controllers
{
[Route("api/[controller]")]
[ApiController]
[UseEtagFilterAttribute]
public class MessagesController : Controller
{
private readonly ILogger log = Log.ForContext<MessagesController>();
public MessagesController(IMessagesRepository messagesRepository, ISmtp4devServer server, MimeProcessingService mimeProcessingService)
{
this.messagesRepository = messagesRepository;
this.server = server;
this.mimeProcessingService = mimeProcessingService;
}
private const int CACHE_DURATION = 31556926;
private readonly IMessagesRepository messagesRepository;
private readonly ISmtp4devServer server;
private readonly MimeProcessingService mimeProcessingService;
/// <summary>
/// Returns all new messages in the INBOX folder since the provided message ID. Returns only the summary without message content.
/// </summary>
/// <param name="lastSeenMessageId">If not specified all recently received messages will be returned up to the page limit.</param>
/// <param name="mailboxName">Mailbox name. If not specified, defaults to the mailboxName with name 'Default'</param>
/// <param name="pageSize">Max number of messages to retrieve. The most recent X are returned.</param>
/// <returns></returns>
[HttpGet("new")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(MessageSummary[]), Description = "")]
public MessageSummary[] GetNewSummaries(Guid? lastSeenMessageId, string mailboxName = MailboxOptions.DEFAULTNAME, int pageSize = 50)
{
return messagesRepository.GetMessageSummaries(mailboxName, MailboxFolder.INBOX)
.OrderByDescending(m => m.ReceivedDate)
.ThenByDescending(m => m.Id)
.AsEnumerable()
.TakeWhile(m => m.Id != lastSeenMessageId)
.Select(m => new MessageSummary(m))
.Take(pageSize)
.ToArray();
}
/// <summary>
/// Returns a list of message summaries including basic details but not the content.
/// </summary>
/// <param name="searchTerms">Case insensitive term to search for in subject, from, to, cc, body content, and attachment filenames</param>
/// <param name="mailboxName">Mailbox name. If not specified, defaults to the mailboxName with name 'Default'</param>
/// <param name="folderName">Folder name (INBOX, Sent). If not specified, returns all messages in mailbox</param>
/// <param name="sortColumn">Property name from response type to sort by</param>
/// <param name="sortIsDescending">True if sort should be descending</param>
/// <param name="page">Page number to retrieve</param>
/// <param name="pageSize">Max number of items to retrieve</param>
/// <returns></returns>
[HttpGet]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(ApiModel.PagedResult<MessageSummary>), Description = "")]
public ApiModel.PagedResult<MessageSummary> GetSummaries(string searchTerms, string mailboxName = MailboxOptions.DEFAULTNAME, string folderName = MailboxFolder.INBOX, string sortColumn = "receivedDate",
bool sortIsDescending = true, int page = 1,
int pageSize = 5)
{
IQueryable<DbModel.Projections.MessageSummaryProjection> query = messagesRepository.GetMessageSummaries(mailboxName, folderName);
query = query.OrderBy(sortColumn + (sortIsDescending ? " DESC" : ""));
if (!string.IsNullOrEmpty(searchTerms))
{
var searchTermsLower = searchTerms.ToLower();
// Enhanced search using database fields - no need for message limits
query = query.Where(m =>
// Basic fields
m.Subject.ToLower().Contains(searchTermsLower) ||
m.From.ToLower().Contains(searchTermsLower) ||
m.To.ToLower().Contains(searchTermsLower) ||
// Extended fields from database - need to access them through the Message entity
(m.MimeMetadata != null && m.MimeMetadata.ToLower().Contains(searchTermsLower)) ||
(m.BodyText != null && m.BodyText.ToLower().Contains(searchTermsLower))
);
}
return query
.Select(m => new MessageSummary(m))
.GetPaged(page, pageSize);
}
private async Task<Message> GetDbMessage(Guid id, bool tracked)
{
return (await this.messagesRepository.TryGetMessageById(id, tracked)) ??
throw new FileNotFoundException($"Message with id {id} was not found.");
}
/// <summary>
/// Returns the full message details for a message.
/// </summary>
/// <param name="id">The message ID to get.</param>
/// <returns></returns>
[HttpGet("{id}")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(ApiModel.Message), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message does not exist")]
public async Task<ApiModel.Message> GetMessage(Guid id)
{
return new ApiModel.Message(await GetDbMessage(id, false));
}
private const int MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024; // 10 MB per file
private async Task<List<Server.AttachmentInfo>> ProcessAttachments(List<IFormFile> attachments)
{
if (attachments == null || attachments.Count == 0)
{
return null;
}
var attachmentInfos = new List<Server.AttachmentInfo>();
foreach (var file in attachments)
{
// Validate file size
if (file.Length > MAX_ATTACHMENT_SIZE)
{
throw new ArgumentException($"Attachment '{file.FileName}' exceeds maximum size of {MAX_ATTACHMENT_SIZE / (1024 * 1024)} MB");
}
var memoryStream = new MemoryStream();
try
{
await file.CopyToAsync(memoryStream);
memoryStream.Position = 0;
attachmentInfos.Add(new Server.AttachmentInfo
{
FileName = file.FileName,
ContentType = file.ContentType ?? "application/octet-stream",
Content = memoryStream
});
}
catch (Exception ex) when (ex is IOException || ex is ArgumentException)
{
// Clean up on error
memoryStream.Dispose();
foreach (var info in attachmentInfos)
{
info.Content?.Dispose();
}
log.Error(ex, "Failed to process attachment: {fileName}", file.FileName);
throw;
}
}
return attachmentInfos;
}
/// <summary>
/// Replies to the message with the specified ID using the configured relay SMTP server.
/// Accepts either text/html (for body only) or multipart/form-data (for body with optional attachments).
/// </summary>
/// <param name="id">The Id of the message to reply to</param>
/// <param name="to">List of email addresses separated by commas</param>
/// <param name="cc">List of email addresses separated by commas</param>
/// <param name="bcc">List of email addresses separated by commas</param>
/// <param name="from">Email address</param>
/// <param name="deliverToAll">True if the message should be delivered to the CC and BCC recipients in addition to the TO recipients. When false, the message is only delivered to the TO recipients, but the message headers will show the specified other recipients.</param>
/// <param name="subject">The subject of message</param>
/// <param name="bodyHtml">HTML body content (when using multipart/form-data, or as body when using text/html)</param>
/// <param name="attachments">Optional files to attach (when using multipart/form-data)</param>
/// <returns></returns>
[HttpPost("{id}/reply")]
[Consumes("text/html", "multipart/form-data")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(void), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message does not exist")]
[SwaggerResponse(System.Net.HttpStatusCode.InternalServerError, typeof(void), Description = "If message fails to send.")]
public async Task<IActionResult> Reply(
Guid id,
string to,
string cc,
string bcc,
string from,
bool deliverToAll,
string subject,
[FromForm] string bodyHtml = null,
[FromForm] List<IFormFile> attachments = null)
{
// Handle different content types
if (HttpContext.Request.ContentType?.StartsWith("text/html") == true)
{
bodyHtml = await HttpContext.Request.Body.ReadStringAsync(Encoding.UTF8);
}
var origMessage = new ApiModel.Message(await GetDbMessage(id, false));
var origMessageId = origMessage.Headers.FirstOrDefault(h => h.Name.Equals("Message-Id", StringComparison.OrdinalIgnoreCase))?.Value ?? "";
Dictionary<string, string> headers = new Dictionary<string, string>();
headers["References"] = (
origMessageId
+ " " +
origMessage.Headers.FirstOrDefault(h => h.Name.Equals("References"))?.Value ?? "").Trim();
if (!string.IsNullOrEmpty(origMessageId))
{
headers["In-Reply-To"] = origMessageId;
}
var toRecips = to?.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
var ccRecips = cc?.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
var bccRecips = bcc?.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
List<string> envelopeRecips = deliverToAll ? [.. toRecips, .. ccRecips, .. bccRecips] : [.. toRecips];
// Process attachments if provided
var attachmentInfos = await ProcessAttachments(attachments);
this.server.Send(headers,
toRecips,
ccRecips,
from, envelopeRecips.Distinct().ToArray(), subject, bodyHtml, attachmentInfos);
return Ok();
}
/// <summary>
/// Sends a message via the configured upstream/relay SMTP server.
/// Accepts either text/html (for body only) or multipart/form-data (for body with optional attachments).
/// </summary>
/// <param name="to">List of email addresses separated by commas</param>
/// <param name="cc">List of email addresses separated by commas</param>
/// <param name="bcc">List of email addresses separated by commas</param>
/// <param name="from">Email address</param>
/// <param name="deliverToAll">True if the message should be delivered to the CC and BCC recipients in addition to the TO recipients. When false, the message is only delivered to the TO recipients, but the message headers will show the specified other recipients.</param>
/// <param name="subject">The subject of message</param>
/// <param name="bodyHtml">HTML body content (when using multipart/form-data)</param>
/// <param name="attachments">Optional files to attach (when using multipart/form-data)</param>
/// <returns></returns>
[HttpPost("send")]
[Consumes("text/html", "multipart/form-data")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(void), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.InternalServerError, typeof(void), Description = "If message fails to send.")]
public async Task<IActionResult> Send(
string to,
string cc,
string bcc,
string from,
bool deliverToAll,
string subject,
[FromForm] string bodyHtml = null,
[FromForm] List<IFormFile> attachments = null)
{
// Handle different content types
if (HttpContext.Request.ContentType?.StartsWith("text/html") == true)
{
bodyHtml = await HttpContext.Request.Body.ReadStringAsync(Encoding.UTF8);
}
Dictionary<string, string> headers = new Dictionary<string, string>();
var toRecips = to?.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
var ccRecips = cc?.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
var bccRecips = bcc?.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
List<string> envelopeRecips = deliverToAll ? [.. toRecips, .. ccRecips, .. bccRecips] : [.. toRecips];
// Process attachments if provided
var attachmentInfos = await ProcessAttachments(attachments);
this.server.Send(headers,
toRecips,
ccRecips,
from, envelopeRecips.Distinct().ToArray(), subject, bodyHtml, attachmentInfos);
return Ok();
}
/// <summary>
/// Marks a single message as read
/// </summary>
/// <param name="id">The ID of the message to mark read.</param>
/// <returns></returns>
[HttpPost("{id}/markRead")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(void), Description = "")]
public Task MarkMessageRead(Guid id)
{
return messagesRepository.MarkMessageRead(id);
}
/// <summary>
/// Marks all messages as read.
/// </summary>
/// <returns></returns>
[HttpPost("markAllRead")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(void), Description = "")]
public Task MarkAllRead(string mailboxName = MailboxOptions.DEFAULTNAME)
{
return messagesRepository.MarkAllMessagesRead(mailboxName);
}
/// <summary>
/// Downloads message in .eml (message/rfc822) format.
/// </summary>
/// <param name="id">The ID of the message to download</param>
/// <returns></returns>
[HttpGet("{id}/download")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(FileStreamResult), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<FileStreamResult> DownloadMessage(Guid id)
{
Message result = await GetDbMessage(id, false);
return new FileStreamResult(new MemoryStream(result.Data), "message/rfc822") { FileDownloadName = $"{id}.eml" };
}
/// <summary>
/// Attempt to relay the specified message either to the original recipients or to those specified.
/// </summary>
/// <param name="id">The ID of the message to relay.</param>
/// <param name="options"></param>
/// <returns></returns>
[HttpPost("{id}/relay")]
public async Task<IActionResult> RelayMessage(Guid id, [FromBody] MessageRelayOptions options)
{
var message = await GetDbMessage(id, true);
var relayResult = server.TryRelayMessage(message,
options?.OverrideRecipientAddresses?.Length > 0
? options?.OverrideRecipientAddresses.Select(a => MailboxAddress.Parse(a)).ToArray()
: null);
if (relayResult.Exceptions.Any())
{
var relayErrorSummary = string.Join(". ", relayResult.Exceptions.Select(e => e.Key.Address + ": " + e.Value.Message));
return Problem("Failed to relay to recipients: " + relayErrorSummary);
}
if (relayResult.WasRelayed)
{
foreach (var relay in relayResult.RelayRecipients)
{
message.AddRelay(new MessageRelay { SendDate = relay.RelayDate, To = relay.Email });
}
messagesRepository.DbContext.SaveChanges();
}
return Ok();
}
/// <summary>
/// Returns the MIME part contents for the specified message and part.
/// </summary>
/// <param name="id">Message ID</param>
/// <param name="partid">Part ID</param>
/// <returns></returns>
[HttpGet("{id}/part/{partid}/content")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message or part does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<FileStreamResult> GetPartContent(Guid id, string partid, bool download=false)
{
return ApiModel.Message.GetPartContent(await GetMessage(id), partid, download);
}
/// <summary>
/// Returns the source text of MIME part contents for the specified message and part.
/// </summary>
/// <param name="id">Message ID</param>
/// <param name="partid">Part ID</param>
/// <returns></returns>
[HttpGet("{id}/part/{partid}/source")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message or part does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<string> GetPartSource(Guid id, string partid)
{
return ApiModel.Message.GetPartContentAsText(await GetMessage(id), partid);
}
/// <summary>
/// Returns the raw source of MIME part contents for the specified message and part.
/// </summary>
/// RAW source is before any content decoding steps like base64.
/// <param name="id">Message ID</param>
/// <param name="partid">Part ID</param>
/// <returns></returns>
[HttpGet("{id}/part/{partid}/raw")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message or part does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<string> GetPartSourceRaw(Guid id, string partid)
{
return ApiModel.Message.GetPartSource(await GetMessage(id), partid);
}
/// <summary>
/// Returns the raw source text of the specified message.
/// </summary>
/// RAW source is before any content decoding steps like base64.
/// <param name="id">Message ID</param>
/// <returns></returns>
[HttpGet("{id}/raw")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message does not exist")]
public async Task<string> GetMessageSourceRaw(Guid id)
{
ApiModel.Message message = await GetMessage(id);
var encoding = message.MimeMessage?.Body?.ContentType.CharsetEncoding ?? ApiModel.Message.GetSessionEncodingOrAssumed(message);
return encoding.GetString(message.Data);
}
/// <summary>
/// Returns the source text of the specified message.
/// </summary>
/// <param name="id">Message ID</param>
/// <returns></returns>
[HttpGet("{id}/source")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<string> GetMessageSource(Guid id)
{
ApiModel.Message message = await GetMessage(id);
return message.MimeMessage?.HtmlBody ?? message.MimeMessage?.TextBody ?? "";
}
/// <summary>
/// Returns the plain text body of the specified message if one exists.
/// </summary>
/// <param name="id">The ID of the message to get body of.</param>
/// <returns></returns>
[HttpGet("{id}/plaintext")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message or part does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<ActionResult<string>> GetMessagePlainText(Guid id)
{
ApiModel.Message message = await GetMessage(id);
if (message.MimeMessage == null)
{
return Content(ApiModel.Message.GetSessionEncodingOrAssumed(message).GetString(message.Data));
}
string plaintext = message.MimeMessage?.TextBody;
if (plaintext == null)
{
return NotFound("MIME message does not have a plain text body");
}
return plaintext;
}
/// <summary>
/// Returns the HTML text body of the specified message if one exists.
/// </summary>
/// <param name="id">The ID of the message to get body of.</param>
/// <returns></returns>
[HttpGet("{id}/html")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string), Description = "")]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, typeof(void), Description = "If the message or part does not exist")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = CACHE_DURATION)]
public async Task<ActionResult<string>> GetMessageHtml(Guid id)
{
ApiModel.Message message = await GetMessage(id);
string html = message.MimeMessage?.HtmlBody;
if (html == null)
{
return NotFound("Message does not have a HTML body");
}
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection imageElements = doc.DocumentNode.SelectNodes("//img[starts-with(@src, 'cid:')]");
if (imageElements != null)
{
foreach (HtmlNode imageElement in imageElements)
{
string cid = imageElement.Attributes["src"].Value.Replace("cid:", "", StringComparison.OrdinalIgnoreCase);
var part = message.Parts.Flatten(p => p.ChildParts).FirstOrDefault(p => p.ContentId == cid);
imageElement.Attributes["src"].Value = $"api/Messages/{id.ToString()}/part/{part?.Id ?? "notfound"}/content";
}
}
return doc.DocumentNode.OuterHtml;
}
/// <summary>
/// Deletes the specified message.
/// </summary>
/// <param name="id">Message ID</param>
/// <returns></returns>
[HttpDelete("{id}")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(void), Description = "")]
public async Task Delete(Guid id)
{
log.Information("Deleting message. MessageId: {messageId}", id);
await messagesRepository.DeleteMessage(id);
}
/// <summary>
/// Imports a single EML file as a new message.
/// </summary>
/// <param name="mailboxName">Mailbox name to import the message into</param>
/// <param name="folderName">Folder name to import the message into (e.g. INBOX, Sent). Defaults to INBOX.</param>
/// <returns>The ID of the imported message</returns>
[HttpPut]
[Consumes("message/rfc822")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(Guid), Description = "ID of the imported message")]
[SwaggerResponse(System.Net.HttpStatusCode.BadRequest, typeof(void), Description = "If the EML content is invalid")]
public async Task<ActionResult<Guid>> ImportMessage(string mailboxName = MailboxOptions.DEFAULTNAME, string folderName = MailboxFolder.INBOX)
{
try
{
// Read EML content from request body
byte[] emlData;
using (var stream = new MemoryStream())
{
await HttpContext.Request.Body.CopyToAsync(stream);
emlData = stream.ToArray();
}
if (emlData.Length == 0)
{
return BadRequest("EML content is empty");
}
// Parse EML file using MimeKit to extract basic info
using var emlStream = new MemoryStream(emlData);
var mimeMessage = await MimeMessage.LoadAsync(emlStream);
// Create ImportedMessage instance
var importedMessage = new ImportedMessage(emlData);
// Extract recipients from the EML file
var recipients = new List<string>();
if (mimeMessage.To?.Any() == true)
{
recipients.AddRange(mimeMessage.To.OfType<MailboxAddress>().Select(a => a.Address));
}
if (mimeMessage.Cc?.Any() == true)
{
recipients.AddRange(mimeMessage.Cc.OfType<MailboxAddress>().Select(a => a.Address));
}
if (mimeMessage.Bcc?.Any() == true)
{
recipients.AddRange(mimeMessage.Bcc.OfType<MailboxAddress>().Select(a => a.Address));
}
// If no recipients found, use a default one
if (!recipients.Any())
{
recipients.Add("imported@localhost");
}
// Set up the ImportedMessage properties
foreach (var recipient in recipients)
{
importedMessage.AddRecipient(recipient);
}
importedMessage.From = mimeMessage.From?.OfType<MailboxAddress>().FirstOrDefault()?.Address ?? "imported@localhost";
// Convert using existing MessageConverter
var messageConverter = new MessageConverter(mimeProcessingService);
var dbMessage = await messageConverter.ConvertAsync(importedMessage, recipients.ToArray());
// Set the mailbox
var dbContext = messagesRepository.DbContext;
var mailbox = await dbContext.Mailboxes.FirstOrDefaultAsync(m => m.Name == mailboxName);
if (mailbox == null)
{
mailbox = new Mailbox { Name = mailboxName };
dbContext.Mailboxes.Add(mailbox);
await dbContext.SaveChangesAsync();
}
dbMessage.Mailbox = mailbox;
dbMessage.MailboxFolder = await dbContext.MailboxFolders.FirstOrDefaultAsync(f => f.Mailbox.Name == mailboxName && f.Name == folderName);
dbMessage.IsUnread = true;
// Add to database
dbContext.Messages.Add(dbMessage);
await dbContext.SaveChangesAsync();
return Ok(dbMessage.Id);
}
catch (Exception ex)
{
log.Error(ex, "Failed to import EML file. ExceptionType: {exceptionType}", ex.GetType().Name);
return BadRequest($"Failed to import EML: {ex.Message}");
}
}
/// <summary>
/// Deletes all messages.
/// </summary>
/// <returns></returns>
[HttpDelete("*")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(void), Description = "")]
public async Task DeleteAll(string mailboxName = MailboxOptions.DEFAULTNAME)
{
log.Information("Deleting all messages. Mailbox: {mailboxName}", mailboxName);
await messagesRepository.DeleteAllMessages(mailboxName);
}
/// <summary>
/// Returns available folders for the specified mailbox.
/// </summary>
/// <param name="mailboxName">Mailbox name. If not specified, defaults to the mailboxName with name 'Default'</param>
/// <returns></returns>
[HttpGet("folders")]
[SwaggerResponse(System.Net.HttpStatusCode.OK, typeof(string[]), Description = "")]
public string[] GetFolders(string mailboxName = MailboxOptions.DEFAULTNAME)
{
using var dbContext = messagesRepository.DbContext;
return dbContext.MailboxFolders
.Where(f => f.Mailbox.Name == mailboxName)
.Select(f => f.Name)
.OrderBy(f => f == MailboxFolder.INBOX ? 0 : f == MailboxFolder.SENT ? 1 : 2).ThenBy(f => f)
.ToArray();
}
}
}