Skip to content

Commit

Permalink
Add support for inline attachments in SmtpMailer (#413)
Browse files Browse the repository at this point in the history
Enhanced the `Attachment` class by adding a `ContentId` property to support inline content. Updated `SmtpMailer` to handle attachments with non-empty `ContentId` as linked resources, generating RFC-compliant `ContentId` using `MimeKit.Utils.MimeUtils.GenerateMessageId()`. Modified the HTML body to reference the correct `ContentId`. Attachments with empty or whitespace `ContentId` are added as regular attachments.

Co-authored-by: James Hickey <[email protected]>
  • Loading branch information
johnwc and jamesmh authored Dec 16, 2024
1 parent a2e5e5e commit a389780
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
3 changes: 2 additions & 1 deletion Src/Coravel.Mailer/Mail/Attachment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace Coravel.Mailer.Mail
public class Attachment
{
public byte[] Bytes { get; set; }
public string Name { get; set; }
public string Name { get; set; }
public string ContentId { get; set; }
}
}
11 changes: 10 additions & 1 deletion Src/Coravel.Mailer/Mail/Mailers/SmtpMailer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,16 @@ private static void SetMailBody(MessageBody message, IEnumerable<Attachment> att
{
foreach (var attachment in attachments)
{
bodyBuilder.Attachments.Add(attachment.Name, attachment.Bytes);
if (string.IsNullOrWhiteSpace(attachment.ContentId) == false)
{
var image = bodyBuilder.LinkedResources.Add(attachment.Name, attachment.Bytes);
// We do this instead of using their value because RFC states the Content-Id value MUST be in the message id format.
image.ContentId = MimeKit.Utils.MimeUtils.GenerateMessageId();
// Now replace where they applied it in the html template with the updated correct version
bodyBuilder.HtmlBody = bodyBuilder.HtmlBody.Replace($"\"cid:{attachment.ContentId}\"", $"\"cid:{image.ContentId}\"", System.StringComparison.OrdinalIgnoreCase);
}
else
bodyBuilder.Attachments.Add(attachment.Name, attachment.Bytes);
}
}

Expand Down

0 comments on commit a389780

Please sign in to comment.