You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Seekers/Helpers/EmailService.cs

79 lines
2.8 KiB

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace ChildGuard.Services
{
public class EmailService
{
private readonly string _smtpServer = "smtp.gmail.com";
private readonly int _smtpPort = 587;
private readonly string _senderEmail = "amritsyangtan1@gmail.com"; // Replace with your email
private readonly string _senderPassword = "bdcx ycpy cbrr szpm"; // Replace with your app password
private readonly Dictionary<string, string> _incidentTypeToEmail;
public EmailService()
{
// Map incident types to authority emails
_incidentTypeToEmail = new Dictionary<string, string>
{
{ "Accident", "amreitsyanf@gmail.com" },
{ "Crime", "crime-authority@example.com" },
{ "Fire", "fire-department@example.com" },
{ "Other", "general-authority@example.com" }
};
}
/// <summary>
/// Sends an email using SMTP.
/// </summary>
/// <param name="recipientEmail">Recipient's email address.</param>
/// <param name="subject">Email subject.</param>
/// <param name="body">Email body.</param>
/// <returns>True if successful, otherwise false.</returns>
public async Task<bool> SendEmailAsync(string recipientEmail, string subject, string body)
{
try
{
using (var smtpClient = new SmtpClient(_smtpServer, _smtpPort))
{
smtpClient.Credentials = new NetworkCredential(_senderEmail, _senderPassword);
smtpClient.EnableSsl = true;
var mailMessage = new MailMessage
{
From = new MailAddress(_senderEmail),
Subject = subject,
Body = body,
IsBodyHtml = true
};
mailMessage.To.Add(recipientEmail);
await smtpClient.SendMailAsync(mailMessage);
}
Console.WriteLine("Email sent successfully.");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Error sending email: {ex.Message}");
return false;
}
}
/// <summary>
/// Gets the recipient email based on the incident type.
/// </summary>
/// <param name="incidentType">Incident type.</param>
/// <returns>Recipient email address.</returns>
public string GetRecipientEmail(string incidentType)
{
return _incidentTypeToEmail.TryGetValue(incidentType, out var email) ? email : "default-authority@example.com";
}
}
}