2026-07-15

Adding an attachment to email using C#

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Adding an attachment to email using C#

Adding Attachments to Emails in C#: A Practical Guide

Sending emails is a fundamental task in modern application development, whether you are building a backend service or an internal communication tool. While sending plain text or HTML bodies is straightforward, adding attachments significantly increases the utility of your message. If you are working with C# and the System.Net.Mail namespace, adding files as attachments requires understanding how to correctly manage file streams within the MailMessage object.

Many developers encountering this task run into issues because simply referencing a file path isn't enough; you need to provide an actual stream of data that the SMTP server can process as an attachment. As we explore how to achieve this, we’ll look at the exact steps required using C#.

The Challenge: Attaching Files in .NET Mail

The code snippet you provided demonstrates a solid foundation for sending emails via an external provider like Gmail using SmtpClient. However, adding an attachment requires leveraging the MailMessage class's specific methods designed to handle file data. To attach a file, you must convert the file into a stream and pass that stream to the Attachment object.

The core concept is to use System.IO classes to open the file and read its contents into a memory stream, which is then attached to the email message. This process ensures that the entire file content is transmitted correctly over the network.

Step-by-Step Implementation with C#

To successfully add an attachment, we need to introduce file handling logic before sending the message. This involves opening the file and using a FileStream to feed the data into the email system.

Here is a complete example demonstrating how to attach a local file (e.g., a PDF or image) to an outgoing email in C#.

using System.Net.Mail;
using System.Net;
using System.IO; // Essential for file operations

public class EmailSender
{
    public void SendEmailWithAttachment(string fromEmail, string toEmail, string subject, string body, string attachmentPath)
    {
        try
        {
            // 1. Setup Mail Addresses and Credentials (as in your example)
            var fromAddress = new MailAddress(fromEmail, "From Name");
            var toAddress = new MailAddress(toEmail, "To Name");
            const string fromPassword = "your_app_password"; // Use secure storage for passwords!

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            // 2. Create the MailMessage
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                // 3. Create the Attachment object
                var attachment = new Attachment(attachmentPath);
                
                // 4. Add the attachment to the message
                message.Attachments.Add(attachment);

                // 5. Send the email
                smtp.Send(message);
                Console.WriteLine("Email sent successfully with attachment!");
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"Error: Attachment file not found at {attachmentPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred during email sending: {ex.Message}");
        }
    }
}

// Example usage:
// var sender = new EmailSender();
// sender.SendEmailWithAttachment("sender@example.com", "recipient@example.com", "Test", "Hello!", "C:\\path\\to\\your\\file.pdf");

Best Practices for File Handling and Security

When dealing with file attachments in C#, two critical aspects must be addressed: file stream management and security.

1. Stream Management: Notice how the example above uses new Attachment(attachmentPath). While this is convenient, for larger files or complex scenarios, manually reading the file into a stream using FileStream offers more control over memory usage and error handling. When you use streams, ensure that the FileStream is properly disposed of using a using block to release system resources immediately after the operation is complete.

2. Security First: Never hardcode passwords directly into your source code, as demonstrated by the placeholder "your_app_password". For any production application, utilize secure methods for storing credentials, such as environment variables or dedicated secret management services. This principle of securing data access is crucial in all development stacks, including when architecting solutions similar to those found on https://laravelcompany.com.

Conclusion

Adding attachments to emails in C# is achievable by correctly integrating file I/O operations with the MailMessage class. By focusing on robust file stream management and adhering to security best practices regarding credentials, you can reliably build powerful communication systems. Mastering these details transforms a simple email sender into a versatile application capable of handling rich data transfer.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.