Send OTP via SMS and Email using Azure Communication Services with ASP.NET Core | Step-by-Step Guide

This diagram represents the architecture of the ASP.NET Core OTP Service using Azure Communication Services (ACS) for sending OTPs via SMS and Email.

This guide walks you through the process of sending One-Time Passwords (OTPs) via both SMS and Email using Azure Communication Services (ACS) integrated with an ASP.NET Core Web API. You'll learn how to:

  • Set up Azure Communication Services for SMS and Email.
  • Build an ASP.NET Core API to handle OTP requests.
  • Implement OTP generation and delivery through SMS and Email.
By the end of this guide, you'll have a fully functional solution for sending OTPs via SMS and Email using Azure's powerful communication platform.

1. Overview

This guide will walk you through the process of setting up Azure Communication Services (ACS), integrating it with ASP.NET Core, and sending OTPs via both SMS and Email.

Prerequisites

  • Azure Subscription
  • Azure Communication Services (ACS) Resource
  • Phone Number Purchased in ACS (For SMS)
  • Email Feature Enabled in ACS (For Email OTPs)
  • ASP.NET Core Web API
  • .NET 6 or later

2. Setting Up Azure Communication Services (ACS)

Step 1: Create ACS Resource

1️⃣ Log in to the Azure Portal.
2️⃣ Search for "Azure Communication Services" and create a new resource.
3️⃣ Copy the Connection String from the Keys section.
4️⃣ Purchase a Phone Number under Phone Numbers (Required for SMS).

Step 2: Enable Email Feature in ACS

1️⃣ Navigate to Azure Communication ServicesEmail.
2️⃣ Click Set Up Email → Follow the steps to link an email domain.
3️⃣ Obtain the Email Connection String under the Keys section.


3. Setting Up an ASP.NET Core Project

Step 1: Create a New ASP.NET Core Web API Project

Run the following command in the terminal:

dotnet new webapi -n OtpService
cd OtpService

Step 2: Install Required NuGet Packages

Run the following command to install Azure SDKs:

dotnet add package Azure.Communication.Sms
dotnet add package Azure.Communication.Email

4. Implementing OTP Service in ASP.NET Core

Step 1: Configure ACS in appsettings.json

{
  "AzureCommunicationServices": {
    "SmsConnectionString": "your_sms_connection_string",
    "EmailConnectionString": "your_email_connection_string",
    "SenderPhoneNumber": "+1234567890",
    "SenderEmail": "noreply@yourdomain.com"
  }
}

Step 2: Create OtpService.cs

using Azure.Communication.Sms;
using Azure.Communication.Email;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;

public class OtpService
{
    private readonly string _smsConnectionString;
    private readonly string _emailConnectionString;
    private readonly string _senderPhoneNumber;
    private readonly string _senderEmail;

    public OtpService(IConfiguration configuration)
    {
        _smsConnectionString = configuration["AzureCommunicationServices:SmsConnectionString"];
        _emailConnectionString = configuration["AzureCommunicationServices:EmailConnectionString"];
        _senderPhoneNumber = configuration["AzureCommunicationServices:SenderPhoneNumber"];
        _senderEmail = configuration["AzureCommunicationServices:SenderEmail"];
    }

    public async Task SendOtpSmsAsync(string phoneNumber, string otp)
    {
        SmsClient smsClient = new SmsClient(_smsConnectionString);
        await smsClient.SendAsync(
            from: _senderPhoneNumber,
            to: phoneNumber,
            message: $"Your OTP code is: {otp}"
        );
    }

    public async Task SendOtpEmailAsync(string email, string otp)
    {
        EmailClient emailClient = new EmailClient(_emailConnectionString);
        var emailMessage = new EmailMessage(
            senderAddress: _senderEmail,
            recipientAddress: email,
            subject: "Your OTP Code",
            htmlContent: $"<p>Your OTP code is: <strong>{otp}</strong></p>"
        );
        await emailClient.SendAsync(emailMessage);
    }
}

Step 3: Create OtpController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

[ApiController]
[Route("api/otp")]
public class OtpController : ControllerBase
{
    private readonly OtpService _otpService;

    public OtpController(OtpService otpService)
    {
        _otpService = otpService;
    }

    [HttpPost("send-sms")]
    public async Task<IActionResult> SendSms([FromBody] OtpRequest request)
    {
        var otp = new Random().Next(100000, 999999).ToString();
        await _otpService.SendOtpSmsAsync(request.PhoneNumber, otp);
        return Ok(new { message = "OTP sent via SMS", otp });
    }

    [HttpPost("send-email")]
    public async Task<IActionResult> SendEmail([FromBody] OtpRequest request)
    {
        var otp = new Random().Next(100000, 999999).ToString();
        await _otpService.SendOtpEmailAsync(request.Email, otp);
        return Ok(new { message = "OTP sent via Email", otp });
    }
}

public class OtpRequest
{
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
}

Step 4: Register OtpService in Program.cs

Modify Program.cs to inject OtpService:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<OtpService>();
builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

5. Testing the API using Postman

Test OTP via SMS

  • Endpoint: POST http://localhost:5000/api/otp/send-sms
  • Body (JSON):
{
  "phoneNumber": "+1234567890"
}

Test OTP via Email

  • Endpoint: POST http://localhost:5000/api/otp/send-email
  • Body (JSON):
{
  "email": "user@example.com"
}

6. Running the Application

Start the ASP.NET Core API:

dotnet run

You should see logs confirming OTPs sent via SMS and Email.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example