Microsoft Learn

LinkedResource Class

Represents a resource, such as an image, that is embedded in an MailMessage object and displayed by the mail client.

The LinkedResource class is used to embed content like images, CSS files, or other media within an MailMessage. This allows the content to be displayed directly within the email body by most modern email clients, rather than being sent as a separate attachment.

Syntax

Namespace: System.Net.Mail

Assembly: System.Net.Mail.dll

public class LinkedResource : IDisposable

Constructors

  • LinkedResource(Stream contentStream)
    Initializes a new instance of the LinkedResource class with the specified content stream.
  • LinkedResource(Stream contentStream, ContentType contentType)
    Initializes a new instance of the LinkedResource class with the specified content stream and content type.
  • LinkedResource(string fileName)
    Initializes a new instance of the LinkedResource class with the specified file name.
  • LinkedResource(string fileName, ContentType contentType)
    Initializes a new instance of the LinkedResource class with the specified file name and content type.
  • LinkedResource(string fileName, string mediaType)
    Initializes a new instance of the LinkedResource class with the specified file name and media type.

Properties

  • ContentDisposition { get; }
    Gets the content disposition for this resource.
  • ContentId { get; set; }
    Gets or sets the content ID for this resource. This is used to link the resource from the HTML body.
  • ContentType { get; set; }
    Gets or sets the content type of this resource.
  • LinkedBaseUri { get; set; }
    Gets or sets the base URI for resolving relative URIs within the linked resource.
  • TransferEncoding { get; set; }
    Gets or sets the transfer encoding for this resource.

Methods

  • Dispose()
    Releases the unmanaged resources used by the LinkedResource and optionally releases the managed resources.
  • Dispose(bool disposing)
    Releases the unmanaged resources used by the LinkedResource and optionally releases the managed resources.

Remarks

When you create a LinkedResource, you typically associate it with an Attachment object. The ContentId property is crucial for embedding images within HTML. For example, in your HTML, you would reference an image like this:

<img src="cid:MyImageContentId" alt="Embedded Image" />

Where MyImageContentId matches the ContentId set on the LinkedResource.

The ContentType property should be set to the correct MIME type of the resource (e.g., "image/png", "image/jpeg", "text/css").

The LinkedResource class implements IDisposable, so it's important to call its Dispose() method when you are finished with it, or use a using statement to ensure proper resource management.

Examples

The following C# code example demonstrates how to create an HTML email with an embedded image using the LinkedResource class.

using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;

public class EmailSender
{
    public static void SendEmailWithImage()
    {
        // --- Configuration ---
        string fromAddress = "sender@example.com";
        string toAddress = "recipient@example.com";
        string subject = "Email with Embedded Image";
        string smtpHost = "smtp.example.com";
        int smtpPort = 587; // Or your SMTP port
        string smtpUser = "username";
        string smtpPass = "password";

        // --- Create MailMessage ---
        MailMessage mailMessage = new MailMessage(fromAddress, toAddress, subject, "");
        mailMessage.IsBodyHtml = true; // Crucial for HTML emails

        // --- Load and Embed Image ---
        string imagePath = @"C:\Path\To\Your\Image.jpg"; // Replace with your image file path
        string imageContentId = "embeddedImage"; // Unique ID for the image

        try
        {
            // Create a LinkedResource from the image file
            LinkedResource inlineImage = new LinkedResource(imagePath, MediaTypeNames.Image.Jpeg);
            inlineImage.ContentId = imageContentId;
            inlineImage.TransferEncoding = TransferEncoding.Base64; // Often good for images

            // --- Create HTML Body ---
            string htmlBody = $@"
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Embedded Image Example</title>
                </head>
                <body>
                    <h1>Hello from .NET!</h1>
                    <p>Please see the image embedded below:</p>
                    <img src=""cid:{imageContentId}"" alt=""An example image"" />
                    <p>Best regards,<br />The .NET Email Sender</p>
                </body>
                </html>";

            mailMessage.Body = htmlBody;

            // Attach the linked resource to the email
            mailMessage.LinkedResources.Add(inlineImage);

            // --- Send Email ---
            using (SmtpClient smtpClient = new SmtpClient(smtpHost, smtpPort))
            {
                smtpClient.EnableSsl = true; // Or false depending on your SMTP server
                smtpClient.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPass);

                smtpClient.Send(mailMessage);
                Console.WriteLine("Email sent successfully!");
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"Error: Image file not found at {imagePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending email: {ex.Message}");
        }
        finally
        {
            // Clean up the MailMessage
            if (mailMessage != null)
            {
                mailMessage.Dispose();
            }
        }
    }

    // To run this example:
    // 1. Replace placeholder values (addresses, SMTP details, image path).
    // 2. Ensure you have a valid image file at the specified path.
    // 3. Make sure your SMTP server settings are correct.
    // 4. Uncomment the following line in your Main method to call SendEmailWithImage():
    //    SendEmailWithImage();
}