How to write a c# code for sending OTP to your registered mail without database??
Loading
How to write a c# code for sending OTP to your registered mail without database??
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Jul 6, 2023, 2:11 AM EDT
To send an OTP (One-Time Password) to a registered email without using a database in C#, you can utilize a third-party email service provider such as SendGrid or MailKit.
To send an OTP email using SendGrid in C#, you need to have a SendGrid account and install the SendGrid package from NuGet.
using System; using System.Security.Cryptography; using System.Text; using SendGrid; using SendGrid.Helpers.Mail; public static class OtpService { public static async Task SendOtpEmail(string recipientEmail) { // Generate a random OTP string otp = GenerateOtp(); // Create the SendGrid message SendGridMessage message = new SendGridMessage(); message.SetFrom(new EmailAddress("[email protected]", "Your Name")); // Replace with your name and email message.AddTo(new EmailAddress(recipientEmail)); message.SetSubject("OTP Verification"); message.AddContent(MimeType.Text, $"Your OTP is: {otp}"); // Set up your SendGrid API key string apiKey = "YOUR_SENDGRID_API_KEY"; // Replace with your SendGrid API key SendGridClient client = new SendGridClient(apiKey); // Send the email Response response = await client.SendEmailAsync(message); if (response.IsSuccessStatusCode) { Console.WriteLine("OTP sent successfully!"); } else { Console.WriteLine("Failed to send OTP."); } } private static string GenerateOtp() { const int otpLength = 6; // Length of the OTP const string allowedChars = "1234567890"; // Characters allowed in the OTP using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider()) { byte[] byteArray = new byte[otpLength]; provider.GetBytes(byteArray); StringBuilder otpBuilder = new StringBuilder(otpLength); foreach (byte randomByte in byteArray) { otpBuilder.Append(allowedChars[randomByte % allowedChars.Length]); } return otpBuilder.ToString(); } } }Call the SendOtpEmail function with the recipient's email address:
string recipientEmail = "[email protected]"; await OtpService.SendOtpEmail(recipientEmail);