Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revise e-mail sending #20

Merged
merged 20 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
77 changes: 45 additions & 32 deletions TRENZ.Lib.RazorMail.Core/Core/MailTemplateBase.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;

using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.StaticFiles;
Expand All @@ -10,25 +11,29 @@ namespace TRENZ.Lib.RazorMail.Core;

public abstract class MailTemplateBase<T> : RazorPage<T>
{
internal const string AttachmentsKey = "Attachments";
internal const string SubjectKey = "Subject";
internal const string ContentRootPathKey = "ContentRootPath";

public Dictionary<string, MailAttachment> Attachments
{
get
{
if (this.ViewData.TryGetValue("Attachments", out var dict))
if (ViewData.TryGetValue(AttachmentsKey, out var dict))
return (Dictionary<string, MailAttachment>)dict!;

dict = new Dictionary<string, MailAttachment>();

this.ViewData["Attachments"] = dict;
ViewData[AttachmentsKey] = dict;

return (Dictionary<string, MailAttachment>)dict;
}
}

public string? Subject
{
get => this.ViewData["Subject"] as string;
set => this.ViewData["Subject"] = value;
get => ViewData[SubjectKey] as string;
set => ViewData[SubjectKey] = value;
}

public string InlineFile(string filename)
Expand All @@ -43,47 +48,55 @@ public string InlineFile(string filename, byte[] fileData)
public void AttachFile(string filename, byte[] fileData)
=> _AttachFile(filename, fileData, ContentDisposition.Attachment);

private string _AttachFile(string filename, ContentDisposition contentDisposition)
private string _AttachFile(string fileName, ContentDisposition contentDisposition)
{
var contentRootPath = TempData["ContentRootPath"] as string ??
throw new InvalidOperationException(nameof(TempData));

var viewPath = this.Path.TrimStart('/');
var viewPath = Path.TrimStart('/');

var parentDir = System.IO.Path.GetDirectoryName(viewPath) ?? throw new ArgumentException(nameof(this.Path));

var absolutePath = System.IO.Path.Combine(contentRootPath, parentDir, filename);
var absolutePath = System.IO.Path.Combine(contentRootPath, parentDir, fileName);

return _AttachFile(filename, System.IO.File.ReadAllBytes(absolutePath), contentDisposition);
return _AttachFile(fileName, File.ReadAllBytes(absolutePath), contentDisposition);
}

private string _AttachFile(string filename, byte[] fileData, ContentDisposition contentDisposition)
private string _AttachFile(string fileName, byte[] fileData, ContentDisposition contentDisposition)
{
if (!new FileExtensionContentTypeProvider().TryGetContentType(filename, out var contentType))
throw new NotSupportedException($"Couldn't figure out content type for {filename}");

if (!Attachments.ContainsKey(filename))
{
var attachment = new MailAttachment(fileData, filename, contentType);
if (!new FileExtensionContentTypeProvider().TryGetContentType(fileName, out var contentType))
throw new NotSupportedException($"Couldn't figure out content type for {fileName}");

switch (contentDisposition)
{
case ContentDisposition.Inline:
attachment.ContentId = filename;
attachment.Inline = true;
var cid = $"cid:{fileName}";
if (Attachments.ContainsKey(fileName))
return cid;

break;
case ContentDisposition.Attachment:
attachment.Inline = false;

break;
default:
break;
}
var attachment = new MailAttachment
{
FileName = fileName,
FileData = fileData,
ContentType = contentType,
};

Attachments[filename] = attachment;
switch (contentDisposition)
{
case ContentDisposition.Inline:
attachment.ContentId = fileName;
attachment.Inline = true;

break;
case ContentDisposition.Attachment:
attachment.Inline = false;

break;
case ContentDisposition.Unset:
break;
default:
throw new ArgumentOutOfRangeException(nameof(contentDisposition), contentDisposition, "Unknown content disposition");
}

return $"cid:{filename}";
Attachments[fileName] = attachment;

return cid;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;

using TRENZ.Lib.RazorMail.Interfaces;
using TRENZ.Lib.RazorMail.Services;

namespace TRENZ.Lib.RazorMail.Extensions;
Expand All @@ -11,7 +12,7 @@ public static IServiceCollection AddRazorEmailRenderer(this IServiceCollection s
services.AddMvcCore()
.AddRazorViewEngine();

services.AddTransient<IRazorEmailRenderer, RazorEmailRenderer>();
services.AddTransient<IMailRenderer, MailRenderer>();

return services;
}
Expand Down
54 changes: 54 additions & 0 deletions TRENZ.Lib.RazorMail.Core/Interfaces/IMailClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using TRENZ.Lib.RazorMail.Models;

namespace TRENZ.Lib.RazorMail.Interfaces;

/// <summary>
/// Represents a client that sends email messages and stores default From, To, CC, BCC, and Reply-To addresses.
/// </summary>
public interface IMailClient
{
/// <summary>
/// The default "From" address. Can be overriden by the message.
/// </summary>
/// <remarks>
/// If this is <see langword="null"/>, it must be set in the <see cref="MailMessage"/>, otherwise
/// <see cref="SendAsync"/> will throw a <see cref="System.InvalidOperationException"/>.
/// </remarks>
MailAddress? DefaultFrom { get; set; }

/// <summary>
/// The default set of recipients. Will be added to the message recipients.
/// </summary>
IEnumerable<MailAddress> DefaultRecipients { get; set; }

/// <summary>
/// The default set of CC recipients. Will be added to the message CC recipients.
/// </summary>
IEnumerable<MailAddress> DefaultCc { get; set; }

/// <summary>
/// The default set of BCC recipients. Will be added to the message BCC recipients.
/// </summary>
IEnumerable<MailAddress> DefaultBcc { get; set; }

/// <summary>
/// The default set of reply-to addresses. Will be added to the message reply-to addresses.
/// </summary>
IEnumerable<MailAddress> DefaultReplyTo { get; set; }

/// <summary>
/// Sends an email message asynchronously.
/// </summary>
/// <param name="message">The message to send.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// Adds the Default* properties from this sender to the message and validates if the mail contains a From address,
/// at least one recipient and a body.
/// </remarks>
Task SendAsync(MailMessage message, CancellationToken cancellationToken = default);
}
11 changes: 11 additions & 0 deletions TRENZ.Lib.RazorMail.Core/Interfaces/IMailRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Threading;
using System.Threading.Tasks;

using TRENZ.Lib.RazorMail.Models;

namespace TRENZ.Lib.RazorMail.Interfaces;

public interface IMailRenderer
{
Task<MailContent> RenderAsync<TModel>(string viewName, TModel model, CancellationToken cancellationToken = default);
}
4 changes: 2 additions & 2 deletions TRENZ.Lib.RazorMail.Core/Models/ContentDisposition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace TRENZ.Lib.RazorMail.Models;

public enum ContentDisposition
{
Unknown = 0,
Unset = 0,
Inline,
Attachment
}
}
58 changes: 30 additions & 28 deletions TRENZ.Lib.RazorMail.Core/Models/MailAddress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,46 @@

namespace TRENZ.Lib.RazorMail.Models;

/// <summary>
/// Represents an e-mail address with an optional display name.
/// </summary>
[DebuggerDisplay("Email = {Email}, Name = {Name}")]
public class MailAddress
{
public MailAddress(string email)
private static string _ValidateEmail(string email)
{
_ValidateEmail(email);
if (!email.Contains('@'))
throw new FormatException($"E-mail address '{email}' doesn't look valid");

Email = email;
return email;
}

public MailAddress(string email, string name)
{
_ValidateEmail(email);
/// <summary>
/// Creates a new instance of the <see cref="MailAddress"/> class with the specified e-mail address.
/// </summary>
/// <param name="address">The e-mail address.</param>
public MailAddress(string address) => Email = _ValidateEmail(address);

Email = email;
Name = name;
}
/// <summary>
/// Creates a new instance of the <see cref="MailAddress"/> class with the specified e-mail address and display name.
/// </summary>
/// <param name="address">The e-mail address.</param>
/// <param name="displayName">The display name of the e-mail address.</param>
public MailAddress(string address, string displayName) : this(address) => Name = displayName;

private static void _ValidateEmail(string email)
{
if (!email.Contains("@"))
throw new FormatException($"E-mail address '{email}' doesn't look valid");
}

public string Email { get; set; }
public string Name { get; set; } = "";
/// <summary>
/// The actual e-mail address.
/// </summary>
public string Email { get; }

public static implicit operator string(MailAddress address)
=> address.Email;
/// <summary>
/// The display name of the e-mail address.
/// </summary>
public string? Name { get; init; }

public static implicit operator MailAddress(string address)
=> new MailAddress(address, "");
public static implicit operator string(MailAddress address) => address.Email;

public override string ToString()
{
if (string.IsNullOrWhiteSpace(Name))
return Email;
public static implicit operator MailAddress(string address) => new(address);

return $"{Name} <{Email}>";
}
}
public override string ToString() => string.IsNullOrWhiteSpace(Name) ? Email : $"{Name} <{Email}>";
}
38 changes: 25 additions & 13 deletions TRENZ.Lib.RazorMail.Core/Models/MailAttachment.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
using System.IO;

namespace TRENZ.Lib.RazorMail.Models;
namespace TRENZ.Lib.RazorMail.Models;

/// <summary>
/// A mail attachment.
/// </summary>
public class MailAttachment
{
public byte[] FileData { get; set; }
public string Filename { get; set; }
public string ContentType { get; set; }
/// <summary>
/// The data of the file.
/// </summary>
public required byte[] FileData { get; set; }

/// <summary>
/// The name of the file.
/// </summary>
public required string FileName { get; set; }

public MailAttachment(byte[] fileData, string filename, string contentType)
{
FileData = fileData;
Filename = filename;
ContentType = contentType;
}
/// <summary>
/// The content type of the file.
/// </summary>
public required string ContentType { get; set; }

/// <summary>
/// The content ID of the attachment.
/// </summary>
public string? ContentId { get; set; }

/// <summary>
/// Whether the attachment should be displayed inline.
/// </summary>
public bool Inline { get; set; }
}
}
25 changes: 25 additions & 0 deletions TRENZ.Lib.RazorMail.Core/Models/MailContent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Collections.Generic;

namespace TRENZ.Lib.RazorMail.Models;

/// <summary>
/// This class gets returned from the isolated template after it has been
/// rendered, and separates the various portions of the e-mail.
/// </summary>
public class MailContent
{
/// <summary>
/// The subject of the mail.
/// </summary>
public string? Subject { get; set; }

/// <summary>
/// The HTML body of the mail.
/// </summary>
public required string HtmlBody { get; set; }

/// <summary>
/// Attachments for the mail.
/// </summary>
public IDictionary<string, MailAttachment> Attachments { get; init; } = new Dictionary<string, MailAttachment>();
}
Loading
Loading