Email Sending in Asp.net Core

Here you learn how to send email in Asp.net Core application, Sending email with SMTPClient is very similar to earlier version of asp.net framework, but here you learn and different class MimeMessage.

Asp.net Core email sending example

This "email sending with attachment" example written in asp.net core 3.1 in razor page, you can use the same code in asp.net core mvc also.

First we create a form that will allow user to input emal id, title, email body and attach a file. This is how probably the form will look like!

send email in asp.net core

Razor Form Design

The following code will help you to create the form in razor view, but you need to make sure you have creating model properties with same names.

<form method="post"  enctype="multipart/form-data">        
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Email" class="control-label"></label>
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Subject" class="control-label"></label>
        <input asp-for="Subject" class="form-control" />
        <span asp-validation-for="Subject" class="text-danger"></span>
    </div>
    <div class="form-group">            
        <textarea asp-for="EmailContent" class="form-control" ></textarea>
        <span asp-validation-for="EmailContent" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input asp-for="FormFile" type="file">
    </div>
    <div class="form-group">
        <input type="submit" value="Send Email" class="btn btn-default" />
    </div>
</form>
Model Design

Now let’s create above properties in page model

[BindProperty]
[Required(ErrorMessage = "Email required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }


[BindProperty]
[Required(ErrorMessage = "Email content required")]
public string EmailContent { get; set; }


[BindProperty]
[Required(ErrorMessage = "Subject line required")]
public string Subject { get; set; }

public IFormFile FormFile { get; set; }

Now you need to install MailKit package from Nuget Package Manager, because in code we use the reference of following two additional namespace.

using MailKit.Net.Smtp;
using MimeKit;

email sending with attachment

Asp net core send email with attachment

MailKit object allow us to attach multiple files with email body.

As you can see we have a IFormFile property in model design, exceptionally like other fields that property does not provide the posted file information

So, when the razor form submitted, the posted file information can be capture from HttpContext object like example below.

We need to create an instance of IHostingEnvironment through constructor dependency injection.

private IHostingEnvironment ihostingEnv;
public emailpageModel(IHostingEnvironment ihostingEnvironment)
{
    ihostingEnv = ihostingEnvironment;
}

Now the above ihostingEnv variable will help us to get the web root ihostingEnv.WebRootPath of current environment in following code.

var postedFile = HttpContext.Request.Form.Files[0];
var path = Path.Combine(ihostingEnv.WebRootPath, "images", postedFile.FileName);
var stream = new FileStream(path, FileMode.Create);
emailBody.Attachments.Add(postedFile.FileName, stream);  

Notice, in above code the Request.Form.Files property contain all posted files information, so if you have multiple file posted from razor form, you can get them all in that property, then convert each file to FileStream object and attach to BodyBuilder.Attachments collection

OnPost Method
public async Task<IActionResult> OnPost()
    {
        MimeMessage mmObj = new MimeMessage();
        // set from email address
        MailboxAddress fromEmail = new MailboxAddress("WebTrainingRoom", "wtr@domain.com");
        mmObj.From.Add(fromEmail);


      // set to email address
        MailboxAddress toEmail = new MailboxAddress("Hello", Email);
        mmObj.To.Add(toEmail);
            
        // Add subject line
        mmObj.Subject = Subject;

        // create email body message.
        BodyBuilder emailBody = new BodyBuilder();
        emailBody.HtmlBody = EmailContent;
        mmObj.Body = emailBody.ToMessageBody();

        var postedFile = HttpContext.Request.Form.Files[0];
        var path = Path.Combine(ihostingEnv.WebRootPath, "images", postedFile.FileName);
        var stream = new FileStream(path, FileMode.Create);
        emailBody.Attachments.Add(postedFile.FileName, stream);                        


        // create SmtpClient object
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Connect("smtp_address_here", 80, true);
        smtpClient.Authenticate("smtp_username", "smtp_password");
        await smtpClient.SendAsync(mmObj);
        smtpClient.Disconnect(true);
        smtpClient.Dispose();
        return RedirectToPage("success", new { msg = "email-sent" });
    }

SMTP client has built-in method SendAsync to send email asynchronously.

SmtpClient smtpClient = new SmtpClient();

await smtpClient.SendAsync(mmObj);

Hope this post was helpful!

You may be interested in following posts:

Asp.Net Core C# Examples | Join Asp.Net MVC Course