How to Send Email with Attachment in ASP.NET Core MVC

SPONSOR AD

How to Send Email with Attachment in ASP.NET Core MVC

In this article, I will discuss How to Send an Email with an Attachment in ASP.NET Core MVC Application with Examples. Please read our previous article discussing HTML to PDF Conversion in ASP.NET Core MVC Applications with Examples. Let’s continue with the application we worked on in previous articles.

How to Send Email with Attachment in ASP.NET Core MVC

Sending an email with an attachment in ASP.NET Core MVC involves a few important steps. The process typically includes creating the email message, attaching the file(s), and sending the email via an SMTP server. Below is a basic guide to help you set up and send an email with an attachment:

  • Set Up SMTP Configuration: You need to configure your SMTP settings in your appsettings.json or another configuration file. This includes the SMTP server address, port, and credentials.
  • Create Email Message: Use the MailMessage class to create your email. Set properties like To, From, Subject, and Body.
  • Attach File: Create an Attachment object. Attach the file to the MailMessage object using the Attachments collection.
  • Send Email: Use the SmtpClient class. Call the Send method or SendAsync for asynchronous operation.
  • Error Handling: Implement proper error handling to manage issues like server unavailability or authentication errors.
  • Logging: Maintain logs for sent emails for future reference and debugging.
Setup SMTP Client

First, make sure you have an SMTP client to send emails. If you’re using a Gmail account, you’ll need to configure it to allow less secure apps. This can typically be done in the appsettings.json file of your ASP.NET Core application. Add the following configuration to your appsettings.json file:

"EmailSettings": {
    "MailServer": "smtp.gmail.com",
    "MailPort": 587,
    "SenderName": "Your Application Name",
    "FromEmail": "yourgmail@gmail.com",
    "Password": "yourAppPassword"
}

Replace yourgmail@gmail.com and yourAppPassword with your actual Gmail ID and app password. Using our Gmail Password, we cannot send emails through our ASP.NET Core Application. For this, we need to create an App Password. Please read the following article, where I have explained how to generate an App Password.

SPONSOR AD

Configuring Email Service in ASP.NET Core

Create Email Service

Create a service to handle email sending. So, create a class file named EmailService.cs and then copy and paste the following code.

using System.Net.Mail;
using System.Net;

namespace FileUploadInMVC.Models
{
    public interface ISenderEmail
    {
        Task SendEmailAsync(string ToEmail, string Subject, string Body, Stream attachmentStream, string attachmentName, bool IsBodyHtml = false);
    }

    public class EmailService : ISenderEmail
    {
        private readonly IConfiguration _configuration;
        public EmailService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public Task SendEmailAsync(string ToEmail, string Subject, string Body, Stream attachmentStream, string attachmentName, bool IsBodyHtml = false)
        {
            string MailServer = _configuration["EmailSettings:MailServer"] ?? string.Empty;
            string FromEmail = _configuration["EmailSettings:FromEmail"] ?? string.Empty;
            string Password = _configuration["EmailSettings:Password"] ?? string.Empty;
            int Port = int.Parse(_configuration["EmailSettings:MailPort"]);

            var client = new SmtpClient(MailServer, Port)
            {
                Credentials = new NetworkCredential(FromEmail, Password),
                EnableSsl = true,
            };

            MailMessage mailMessage = new MailMessage(FromEmail, ToEmail, Subject, Body)
            {
                IsBodyHtml = IsBodyHtml
            };

            if (attachmentStream != null)
            {
                mailMessage.Attachments.Add(new Attachment(attachmentStream, attachmentName));
            }

            return client.SendMailAsync(mailMessage);
        }
    }
}

Register Email Service:

In Program.cs, register your email service as follows:

builder.Services.AddTransient<ISenderEmail, EmailService>();

Inject the EmailService into your MVC controller:

Next, we need to inject the EmailService into the FileUpload controller. So, add the following code to the FileUpload Controller.

private readonly ISenderEmail _emailService;

public FileUploadController(ISenderEmail emailService)
{
    _emailService = emailService;
}

Next, add the following action method, which will send an email with an attachment.

public async Task<IActionResult> SendEmailWithAttachment()
{
    // Sample invoice data
    // Here, we have hardcoded the data,
    // In Real-time you will get the data from the database
    var invoice = new Invoice
    {
        InvoiceNumber = "INV-DOTNET-1001",
        Date = DateTime.Now,
        CustomerName = "Pranaya Rout",
        Items = new List<InvoiceItem>
                {
                    new InvoiceItem { ItemName = "Item 1", Quantity = 2, UnitPrice = 15.0m },
                    new InvoiceItem { ItemName = "Item 2", Quantity = 3, UnitPrice = 10.0m },
                    new InvoiceItem { ItemName = "Item 3", Quantity = 1, UnitPrice = 35.0m }
                },
        PaymentMode = "COD"
    };

    //Set the Total Amount
    invoice.TotalAmount = invoice.Items.Sum(x => x.TotalPrice);

    //Create an Instance of PDFService
    PDFService pdfService = new PDFService();

    //Call the GeneratePDF method passing the Invoice Data
    var pdfFile = pdfService.GeneratePDF(invoice);

    var stream = new MemoryStream(pdfFile);
    string Subject = "Product Invoice";
    string Body = "Please find the attached invoice";
    await _emailService.SendEmailAsync("toemailid", Subject, Body, stream, "attachment.pdf");

    return View();
}

Once we send the email with the attachment, we need to display a message to the user. So, add the following SendEmailWithAttachment.cshtml view within the Views/FileUpload folder and then copy and paste the following code:

SPONSOR AD
@{
    ViewData["Title"] = "SendEmailWithAttachment";
}

<h1>Email Sent With Attachment to Your Email Id</h1>
Link to the Send Email with Attachment

In your view, create a link to the controller action that sends the email with an attachment. So, modify the DownloadPDF.cshtml view as follows to provide a link to the GeneratePDFFromView action method.

@{
    ViewData["Title"] = "DownloadPDF";
}

<h1>Download PDF</h1>
<a href="@Url.Action("GenerateInvoicePDF", "FileUpload")">Download Invoice</a>
<br/>
<h1>Download Password Protected PDF</h1>
<a href="@Url.Action("GeneratePasswordProtectedInvoicePDF", "FileUpload")">Download Password Protected Invoice</a>
<br />
<h1>Generate PDF from View</h1>
<a href="@Url.Action("GenerateProtectedPDF", "FileUpload")">Generate PDF From View</a>
<br />
<h1>Send Email With Attachment</h1>
<a href="@Url.Action("SendEmailWithAttachment", "FileUpload")">Send Email With Attachment</a>
Run and Test

Run your application and navigate to the URL FileUpload/DownloadPDF, which should open the following page. Click on the Send Email With Attachment link, as shown in the image below, to trigger the Send Email with Attachment functionality.

How to Send an Email with an Attachment in the ASP.NET Core MVC Application with Examples

Now, if you check the Email ID, then you should see the Email with the Attachment as shown in the image below:

How to Send an Email with an Attachment in the ASP.NET Core MVC Application with Examples

Now, if you want to generate the PDF from View and then send that PDF as an attachment, then you need to modify the SendEmailWithAttachment action method as follows:

public async Task<IActionResult> SendEmailWithAttachment()
{
    // Sample invoice data
    // Here, we have hardcoded the data,
    // In Real-time you will get the data from the database
    var invoice = new Invoice
    {
        InvoiceNumber = "INV-DOTNET-1001",
        Date = DateTime.Now,
        CustomerName = "Pranaya Rout",
        Items = new List<InvoiceItem>
                {
                    new InvoiceItem { ItemName = "Item 1", Quantity = 2, UnitPrice = 15.0m },
                    new InvoiceItem { ItemName = "Item 2", Quantity = 3, UnitPrice = 10.0m },
                    new InvoiceItem { ItemName = "Item 3", Quantity = 1, UnitPrice = 35.0m }
                },
        PaymentMode = "COD"
    };

    //Set the Total Amount
    invoice.TotalAmount = invoice.Items.Sum(x => x.TotalPrice);

    var report = new ViewAsPdf("GeneratePDFFromView", invoice)
    {
        FileName = "UnprotectedReport.pdf"
    };

    //Conver View to byte Array
    var binaryPdf = report.BuildFile(ControllerContext).Result;

    var stream = new MemoryStream(binaryPdf);
    string Subject = "Product Invoice";
    string Body = "Please find the attached invoice";
    await _emailService.SendEmailAsync("ToEmailId", Subject, Body, stream, "attachment.pdf");

    return View();
}

Now, run the application and test it, and it should work as expected.

When to Send Email with Attachment?
  • User-Triggered Events: When a user completes an action that requires an email response, like submitting a form that generates a PDF report.
  • System-Triggered Notifications: Automatically send emails responding to certain system events, like a weekly report, backup confirmations, or alert notifications.
  • Scheduled Tasks: For periodic emails, such as daily summaries or monthly newsletters with attached documents.
  • Confirmation or Follow-Up Emails: After a user has performed an important action, like registration or order placement, where an attachment might be necessary (e.g., a receipt, ticket, or informational document).

In the next article, I will discuss the ASP.NET Core MVC Request Life Cycle with examples. In this article, I try to explain How to Send an Email with an Attachment in the ASP.NET Core MVC Application with Examples. I hope you enjoy this article on How to Send Email with Attachment in ASP.NET Core MVC.

SPONSOR AD
SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *