Skip to content

Instantly share code, notes, and snippets.

@HammadMaqbool
Last active March 18, 2025 08:01
Show Gist options
  • Select an option

  • Save HammadMaqbool/b5229d7b0be73dac3aa8f007ae20c28d to your computer and use it in GitHub Desktop.

Select an option

Save HammadMaqbool/b5229d7b0be73dac3aa8f007ae20c28d to your computer and use it in GitHub Desktop.
EMail OTP System using C#.NET
using System.Net.Mail;
using System.Net;
namespace ConsoleAppTest;
class EmailSystem
{
private readonly string smtpHost;
private readonly int smtpPort;
private readonly string smtpUser;
private readonly string smtpPass;
private readonly bool enableSsl;
public EmailSystem(string host, int port, string user, string pass, bool ssl = true)
{
smtpHost = host;
smtpPort = port;
smtpUser = user;
smtpPass = pass;
enableSsl = ssl;
}
public async Task<bool> SendEmailAsync(string toEmail, string subject, string body, bool isHtml = true)
{
try
{
using (SmtpClient smtp = new SmtpClient(smtpHost, smtpPort))
{
smtp.Credentials = new NetworkCredential(smtpUser, smtpPass);
smtp.EnableSsl = enableSsl;
MailMessage mail = new MailMessage
{
From = new MailAddress(smtpUser),
Subject = subject,
Body = body,
IsBodyHtml = isHtml
};
mail.To.Add(toEmail);
await smtp.SendMailAsync(mail);
return true;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error sending email: {ex.Message}");
return false;
}
}
}
using ConsoleAppTest;
Console.WriteLine("Welcome to OTP Program");
Random R = new();
int Number = R.Next(100000,999999);
EmailSystem emailSystem = new("smtp.gmail.com", 587, "SendFromGMailID", "YourPasswordORKey");
var flag = await emailSystem.SendEmailAsync("SendToEmail", "OTP", $"Your OTP is {Number}");
Console.WriteLine("Please enter your OTP to login");
int userOTP = int.Parse(Console.ReadLine());
if(userOTP == Number)
{
Console.WriteLine("Login Successful");
}
else
{
Console.WriteLine("invalid OTP");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment