ASP.NET Core  

Email Sending Feature Using ASP.NET Core API + Angular Form

Sending emails from a web application is a common requirement. It can be used for:

  • Contact forms

  • Password reset

  • Notifications

  • Email verification

In this tutorial, we will build a complete email sending feature using:

  • ASP.NET Core Web API for backend

  • Angular Form for frontend

  • SMTP with MailKit

  • Validation and HTML content support

This tutorial is beginner-friendly, practical, and uses clean code practices.

What You Will Build

  1. Angular form to collect user inputs (name, email, message)

  2. ASP.NET Core backend API to receive form data

  3. Email sent using SMTP (supports Gmail, Outlook, or any SMTP server)

  4. HTML email template for professional look

  5. Feedback to user on success or failure

Part 1: Backend Implementation(ASP.NET Core)

Step 1: Create ASP.NET Core API Project

dotnet new webapi -n EmailApi
cd EmailApi

Step 2: Install MailKit

dotnet add package MailKit

MailKit is a popular library for sending emails using SMTP.

Step 3: Configure SMTP Settings

Add your SMTP configuration in appsettings.json:

"Email": {
  "From": "[email protected]",
  "SmtpServer": "smtp.gmail.com",
  "Port": 587,
  "Username": "[email protected]",
  "Password": "your-email-password"
}

Note: For Gmail, you may need an App Password if 2FA is enabled.

Step 4: Create Email DTO

Models/EmailDto.cs

public class EmailDto
{
    public string Name { get; set; }
    public string FromEmail { get; set; }
    public string Subject { get; set; }
    public string Message { get; set; }
}

Step 5: Create Email Service

Services/EmailService.cs

using MailKit.Net.Smtp;
using MimeKit;

public class EmailService
{
    private readonly IConfiguration _config;

    public EmailService(IConfiguration config)
    {
        _config = config;
    }

    public async Task SendEmailAsync(EmailDto dto)
    {
        var email = new MimeMessage();
        email.From.Add(MailboxAddress.Parse(_config["Email:From"]));
        email.To.Add(MailboxAddress.Parse(_config["Email:From"])); // Send to your own inbox
        email.Subject = dto.Subject;

        // HTML Body
        email.Body = new BodyBuilder
        {
            HtmlBody = $@"
                <h2>Contact Form Submission</h2>
                <p><strong>Name:</strong> {dto.Name}</p>
                <p><strong>Email:</strong> {dto.FromEmail}</p>
                <p><strong>Message:</strong><br>{dto.Message}</p>"
        }.ToMessageBody();

        using var smtp = new SmtpClient();
        await smtp.ConnectAsync(_config["Email:SmtpServer"], int.Parse(_config["Email:Port"]), false);
        await smtp.AuthenticateAsync(_config["Email:Username"], _config["Email:Password"]);
        await smtp.SendAsync(email);
        await smtp.DisconnectAsync(true);
    }
}

Step 6: Create Controller

Controllers/EmailController.cs

[ApiController]
[Route("api/[controller]")]
public class EmailController : ControllerBase
{
    private readonly EmailService _emailService;

    public EmailController(EmailService emailService)
    {
        _emailService = emailService;
    }

    [HttpPost("send")]
    public async Task<IActionResult> SendEmail([FromBody] EmailDto dto)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        await _emailService.SendEmailAsync(dto);
        return Ok(new { Message = "Email sent successfully!" });
    }
}

Step 7: Register EmailService in Program.cs

builder.Services.AddSingleton<EmailService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Part 2: Frontend Implementation (Angular)

Step 1: Create Angular Form

Generate a component:

ng generate component contact-form

contact-form.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-contact-form',
  templateUrl: './contact-form.component.html'
})
export class ContactFormComponent {

  contactForm: FormGroup;
  message: string = '';

  constructor(private fb: FormBuilder, private http: HttpClient) {
    this.contactForm = this.fb.group({
      name: ['', Validators.required],
      fromEmail: ['', [Validators.required, Validators.email]],
      subject: ['', Validators.required],
      message: ['', Validators.required]
    });
  }

  submit() {
    if (this.contactForm.invalid) return;

    this.http.post('https://localhost:5001/api/email/send', this.contactForm.value)
      .subscribe({
        next: (res: any) => this.message = res.message,
        error: (err) => this.message = 'Failed to send email'
      });
  }
}

contact-form.component.html

<h2>Contact Us</h2>
<form [formGroup]="contactForm" (ngSubmit)="submit()">
  <input formControlName="name" placeholder="Name" />
  <input formControlName="fromEmail" placeholder="Email" />
  <input formControlName="subject" placeholder="Subject" />
  <textarea formControlName="message" placeholder="Message"></textarea>
  <button type="submit">Send Email</button>
</form>

<p>{{ message }}</p>

Step 2: Add ReactiveFormsModule and HttpClientModule

app.module.ts

import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    ReactiveFormsModule,
    HttpClientModule,
    ...
  ],
})
export class AppModule {}

Part 3: Testing the email feature

  1. Run ASP.NET Core API (dotnet run)

  2. Run Angular app (ng serve)

  3. Fill out the contact form and submit

  4. Check your inbox for the HTML email

Expected result:

  • Properly formatted email

  • Subject, sender, and message displayed

  • No plain text fallback needed

Part 4: Optional Enhancement

  1. CC/BCC support – send emails to multiple recipients

  2. Attachment support – use BodyBuilder.Attachments

  3. Custom HTML templates – load from a file for branding

  4. Email logging – store sent emails in the database

  5. Validation – prevent spam or empty fields

Conclusion

You now have a complete email sending feature using:

  • ASP.NET Core Web API

  • MailKit for SMTP

  • Angular form for frontend input

  • HTML templates for professional emails

This system can be used for contact forms, notifications, or user interactions in any full-stack application.