📧 MailService.cs Documentation

Welcome to the detailed documentation for IrbyImaging.BusinessLogic/SendEmailUtility/MailService.cs. This document provides an in‑depth overview of the classes, methods, dependencies, usage examples, and even a UML diagram to help you understand and integrate the mail functionality seamlessly.


📑 Table of Contents

  1. Overview & Purpose
  2. Key Functional Areas
  3. Dependencies & Technologies
  4. UML Class Diagram
  5. Classes & Data Models
  6. Method Details
  7. Error Handling & Return Types
  8. Third‑Party Integrations
  9. Sample Code & Usage Examples
  10. Configuration & Dependency Injection
  11. Conclusion

🔍 Overview & Purpose

The MailService class centralizes outbound email operations using Microsoft Graph and Azure Identity. It supports:

  • Sending generic emails with attachments
  • Predefined email flows:
    • Help Desk notifications
    • UAR Approver alerts

It also defines SMTPProperties to represent classic SMTP settings, should you need to switch from Graph API to traditional SMTP at runtime.


🚀 Key Functional Areas

  • Authentication: Uses Azure AD ClientSecretCredential to authenticate against Microsoft Graph.
  • Email Creation: Constructs Message objects with HTML bodies, CC fields, and file attachments.
  • Email Sending: Delivers mail via GraphServiceClient’s SendMail endpoint.
  • Helper Methods: Specialized creators for standard, help‑desk, and UAR‑approver emails.

🛠 Dependencies & Technologies

Package/Namespace Purpose
Azure.Identity Client secret credential for Graph authentication
Microsoft.Graph Graph SDK to send emails
Microsoft.Graph.Models Email message & attachment models
Microsoft.AspNetCore.Http Handles uploaded file attachments (IFormFile)
MimeKit, MailKit.Security (Imported, not used in current Graph flows)
System.IO Stream to byte[] conversion for attachments

📐 UML Class Diagram

classDiagram
    direction LR
    class MailService {
        +Task SendEmail(...)
        +Message CreateStandardEmail(...)
        +Task SendEmailHelpDesk(...)
        +Message CreateEmailHelpDesk(...)
        +Task SendEmailUARApprover(...)
        +Message CreateEmailUARApprover(...)
    }
    class SMTPProperties {
        +string SmtpServer
        +int SmtpPort
        +bool EnableSsl
        +string UserName
        +string Password
        +string From
    }
    MailService ..> SMTPProperties : uses (optional)

🧱 Classes & Data Models

📜 MailService

Namespace: IrbyImaging.BusinessLogic.SendEmailUtility
Responsibility:

  • Authenticate with MS Graph
  • Build, attach files, and send email messages

👤 SMTPProperties

A simple POCO to hold traditional SMTP settings:

Property Type Description
SmtpServer string Host address of SMTP server
SmtpPort int Port number (e.g., 587)
EnableSsl bool Toggle SSL/TLS
UserName string Credential user name
Password string Credential password
From string Default “From” email address

🔍 Method Details

1. SendEmail

public Task SendEmail(
    string emailTo,
    string subject,
    string body,
    IEnumerable<IFormFile> filesToAttach,
    bool isBodyHtml = true,
    string emailFrom = null,
    string emailCc = null,
    string clientId = null,
    string tenantId = null,
    string clientSecret = null)

Description
Sends a standard email (with optional attachments) via Microsoft Graph.

Parameters

Name Type Description
emailTo string Primary recipient address
subject string Email subject line
body string HTML or plain‑text body
filesToAttach IEnumerable<IFormFile> List of file uploads (converted to Graph attachments)
isBodyHtml bool Set to true for HTML content (default)
emailFrom string Override “From” address (default: [email protected])
emailCc string CC recipient
clientId string Azure AD App (client) ID
tenantId string Azure AD Tenant ID
clientSecret string Azure AD client secret

Return
Task (completed when send call is done)


2. CreateStandardEmail

public Message CreateStandardEmail(
    string email,
    string subject,
    string body,
    IEnumerable<IFormFile> filesToAttach,
    bool isBodyHtml = true,
    string emailFrom = null,
    string emailCc = null)

Description
Builds a Microsoft.Graph.Models.Message with attachments.

Key Steps

  1. Loop through filesToAttach
  2. Copy to MemoryStream, convert to byte[]
  3. Create FileAttachment objects
  4. Populate Subject, Body, ToRecipients, CcRecipients, and Attachments

3. SendEmailHelpDesk

public Task SendEmailHelpDesk(
    string emailTo,
    string subject,
    string body,
    bool isBodyHtml = true,
    string emailFrom = null,
    string emailCc = null,
    string clientId = null,
    string tenantId = null,
    string clientSecret = null)

Description
Specialized method that sends a help‑desk notification email.

Internals:
Uses CreateEmailHelpDesk to build the Message.


4. SendEmailUARApprover

public Task SendEmailUARApprover(
    string emailTo,
    string subject,
    string body,
    bool isBodyHtml = true,
    string emailFrom = null,
    string emailCc = null,
    string clientId = null,
    string tenantId = null,
    string clientSecret = null)

Description
Sends an email to a UAR Approver with similar defaults as HelpDesk.

Internals:
Calls CreateEmailUARApprover to set up recipients.


5. CreateEmailHelpDesk

public Message CreateEmailHelpDesk(
    string email,
    string subject,
    string body,
    bool isBodyHtml = true,
    string emailFrom = null,
    string emailCc = null)
  • Builds a help‑desk message by setting default CC to [email protected] if none provided.

6. CreateEmailUARApprover

public Message CreateEmailUARApprover(
    string email,
    string subject,
    string body,
    bool isBodyHtml = true,
    string emailFrom = null,
    string emailCc = null)
  • Constructs a UAR Approver email with supplied To/Cc recipients.

⚠️ Error Handling & Return Types

  • Synchronous Blocking: Each SendMail.PostAsync(...).Wait() may throw:
    • ServiceException (Graph API errors)
    • AuthenticationFailedException (Azure Identity)
  • Best Practice: Wrap calls in try/catch or use await to avoid deadlocks.

🔌 Third‑Party Integrations

  • Azure.Identity
    • ClientSecretCredential for secure token acquisition.
  • Microsoft.Graph
    • GraphServiceClient to send mail via Microsoft 365 accounts.
  • Microsoft.AspNetCore.Http
    • Handling IFormFile uploads in web APIs.

💻 Sample Code & Usage Examples

1. Register in DI Container (ASP.NET Core)

// In Startup.cs / Program.cs
services.Configure<SMTPProperties>(Configuration.GetSection("SmtpSettings"));
services.AddTransient<MailService>();

2. Call from a Controller

[ApiController]
public class NotificationsController : ControllerBase
{
    private readonly MailService _mailService;
    private readonly IConfiguration _config;

    public NotificationsController(MailService mailService, IConfiguration config)
    {
        _mailService = mailService;
        _config = config;
    }

    [HttpPost("send-report")]
    public async Task<IActionResult> SendReport([FromForm] List<IFormFile> attachments)
    {
        var clientId     = _config["AzureAd:ClientId"];
        var tenantId     = _config["AzureAd:TenantId"];
        var clientSecret = _config["AzureAd:ClientSecret"];

        await _mailService.SendEmail(
            emailTo: "[email protected]",
            subject: "Monthly Report 📊",
            body: "<h1>Your report is ready!</h1>",
            filesToAttach: attachments,
            isBodyHtml: true,
            emailFrom: null,
            emailCc: "[email protected]",
            clientId: clientId,
            tenantId: tenantId,
            clientSecret: clientSecret
        );

        return Ok("Email sent successfully.");
    }
}

⚙️ Configuration & Dependency Injection

appsettings.json:

"AzureAd": {
  "TenantId": "<your-tenant-id>",
  "ClientId": "<your-client-id>",
  "ClientSecret": "<your-client-secret>"
},
"SmtpSettings": {
  "SmtpServer": "smtp.example.com",
  "SmtpPort": 587,
  "EnableSsl": true,
  "UserName": "smtp_user",
  "Password": "smtp_password",
  "From": "[email protected]"
}

🏁 Conclusion

The MailService and SMTPProperties classes provide a flexible email solution:

  • Leverages Microsoft Graph for enterprise‑grade mailing.
  • Defines helper methods for common workflows (help desk, UAR).
  • Easily extendable to plain SMTP by injecting SMTPProperties.

Integrate this service in your ASP.NET Core application to automate and standardize your outbound email logic with minimal effort. Happy coding! 🎉