---
title: "How to sent email as async in C#?"  
description: "How to sent email as async in C#?"  
author: "ICSM Computer"  
published: 2025-05-05  
updated: 2025-05-05  
canonical: https://www.mindstick.com/interview/34076/how-to-sent-email-as-async-in-c-sharp  
category: "c#"  
tags: ["c#", ".net", "core framework"]  
reading_time: 4 minutes  

---

# How to sent email as async in C#?

Here's a clean and **async** `MailService` **class** implementation that wraps your mail-sending logic. This is a modern, reusable class using `System.Net.Mail`, ideal for dependency injection or standalone usage.

## MailService.cs

```cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

public class MailResponse
{
    public bool IsSend { get; set; }
    public string ErrorMessage { get; set; }
}

public class MailService
{
    private readonly string _smtpServer;
    private readonly int _smtpPort;
    private readonly string _smtpUsername;
    private readonly string _smtpPassword;
    private readonly bool _enableSsl;

    public MailService(string smtpServer, int smtpPort, string smtpUsername, string smtpPassword, bool enableSsl)
    {
        _smtpServer = smtpServer;
        _smtpPort = smtpPort;
        _smtpUsername = smtpUsername;
        _smtpPassword = smtpPassword;
        _enableSsl = enableSsl;
    }

    public async Task<MailResponse> SendMailAsync(
        string to,
        string from,
        string subject,
        string mailBody,
        string portalName,
        string cc = null,
        string bcc = null,
        IList<string> attachments = null)
    {
        var response = new MailResponse();

        if (!Validate())
        {
            response.IsSend = false;
            response.ErrorMessage = "Validation failed.";
            return response;
        }

        try
        {
            mailBody = mailBody.Replace("\r\n", "\n").Replace("\n", "\r\n");

            using (var mail = new MailMessage())
            {
                mail.From = new MailAddress(from.Trim(), portalName);
                mail.Subject = subject.Trim();
                mail.Body = mailBody.Trim();
                mail.IsBodyHtml = true;

                foreach (var address in to.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                    mail.To.Add(address.Trim());

                if (!string.IsNullOrEmpty(cc))
                {
                    foreach (var address in cc.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                        mail.CC.Add(address.Trim());
                }

                if (!string.IsNullOrEmpty(bcc))
                {
                    foreach (var address in bcc.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                        mail.Bcc.Add(address.Trim());
                }

                if (attachments != null)
                {
                    foreach (var filePath in attachments)
                        mail.Attachments.Add(new Attachment(filePath));
                }

                using (var smtp = new SmtpClient(_smtpServer, _smtpPort))
                {
                    smtp.Credentials = new NetworkCredential(_smtpUsername, _smtpPassword);
                    smtp.EnableSsl = _enableSsl;

                    await smtp.SendMailAsync(mail);
                    response.IsSend = true;
                }
            }
        }
        catch (Exception ex)
        {
            response.IsSend = false;
            response.ErrorMessage = $"Exception while sending mail:\n{ex.Message}";
            MSError.Trace(ex); // Optional: your custom error logger
        }

        return response;
    }

    private bool Validate()
    {
        // Your existing validation logic
        return true;
    }
}
```

Now call it

```cs
var mailService = new MailService(
    smtpServer: "dedrelay.secureserver.net",
    smtpPort: 25,
    smtpUsername: "you@example.com",
    smtpPassword: "your-password",
    enableSsl: false
);

var response = await mailService.SendMailAsync(
    to: "recipient@example.com",
    from: "you@example.com",
    subject: "Test Subject",
    mailBody: "<h1>Hello World</h1>",
    portalName: "MyPortal",
    cc: "cc@example.com",
    bcc: "bcc@example.com",
    attachments: new List<string> { "C:\\temp\\file.pdf" }
);

if (response.IsSend)
{
    Console.WriteLine("Email sent!");
}
else
{
    Console.WriteLine("Failed: " + response.ErrorMessage);
}
```

## Answers

### Answer by ICSM Computer

Here's a clean and **async** `MailService` **class** implementation that wraps your mail-sending logic. This is a modern, reusable class using `System.Net.Mail`, ideal for dependency injection or standalone usage.

## MailService.cs

```cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

public class MailResponse
{
    public bool IsSend { get; set; }
    public string ErrorMessage { get; set; }
}

public class MailService
{
    private readonly string _smtpServer;
    private readonly int _smtpPort;
    private readonly string _smtpUsername;
    private readonly string _smtpPassword;
    private readonly bool _enableSsl;

    public MailService(string smtpServer, int smtpPort, string smtpUsername, string smtpPassword, bool enableSsl)
    {
        _smtpServer = smtpServer;
        _smtpPort = smtpPort;
        _smtpUsername = smtpUsername;
        _smtpPassword = smtpPassword;
        _enableSsl = enableSsl;
    }

    public async Task<MailResponse> SendMailAsync(
        string to,
        string from,
        string subject,
        string mailBody,
        string portalName,
        string cc = null,
        string bcc = null,
        IList<string> attachments = null)
    {
        var response = new MailResponse();

        if (!Validate())
        {
            response.IsSend = false;
            response.ErrorMessage = "Validation failed.";
            return response;
        }

        try
        {
            mailBody = mailBody.Replace("\r\n", "\n").Replace("\n", "\r\n");

            using (var mail = new MailMessage())
            {
                mail.From = new MailAddress(from.Trim(), portalName);
                mail.Subject = subject.Trim();
                mail.Body = mailBody.Trim();
                mail.IsBodyHtml = true;

                foreach (var address in to.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                    mail.To.Add(address.Trim());

                if (!string.IsNullOrEmpty(cc))
                {
                    foreach (var address in cc.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                        mail.CC.Add(address.Trim());
                }

                if (!string.IsNullOrEmpty(bcc))
                {
                    foreach (var address in bcc.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                        mail.Bcc.Add(address.Trim());
                }

                if (attachments != null)
                {
                    foreach (var filePath in attachments)
                        mail.Attachments.Add(new Attachment(filePath));
                }

                using (var smtp = new SmtpClient(_smtpServer, _smtpPort))
                {
                    smtp.Credentials = new NetworkCredential(_smtpUsername, _smtpPassword);
                    smtp.EnableSsl = _enableSsl;

                    await smtp.SendMailAsync(mail);
                    response.IsSend = true;
                }
            }
        }
        catch (Exception ex)
        {
            response.IsSend = false;
            response.ErrorMessage = $"Exception while sending mail:\n{ex.Message}";
            MSError.Trace(ex); // Optional: your custom error logger
        }

        return response;
    }

    private bool Validate()
    {
        // Your existing validation logic
        return true;
    }
}
```

Now call it

```cs
var mailService = new MailService(
    smtpServer: "dedrelay.secureserver.net",
    smtpPort: 25,
    smtpUsername: "you@example.com",
    smtpPassword: "your-password",
    enableSsl: false
);

var response = await mailService.SendMailAsync(
    to: "recipient@example.com",
    from: "you@example.com",
    subject: "Test Subject",
    mailBody: "<h1>Hello World</h1>",
    portalName: "MyPortal",
    cc: "cc@example.com",
    bcc: "bcc@example.com",
    attachments: new List<string> { "C:\\temp\\file.pdf" }
);

if (response.IsSend)
{
    Console.WriteLine("Email sent!");
}
else
{
    Console.WriteLine("Failed: " + response.ErrorMessage);
}
```


---

Original Source: https://www.mindstick.com/interview/34076/how-to-sent-email-as-async-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
