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

83 lines
2.8 KiB

using System;
using System.Collections.Generic;
6 months ago
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
6 months ago
namespace Justice.Services
{
6 months ago
public class EmailService
{
private readonly string _smtpServer = "smtp.gmail.com";
private readonly int _smtpPort = 587;
6 months ago
private readonly string _senderEmail = "amritsyangtan1@gmail.com";
private readonly string _senderPassword = "bdcx ycpy cbrr szpm";
// Map incident types to recipient emails
private readonly Dictionary<string, string> _incidentTypeToEmail;
public EmailService()
{
_incidentTypeToEmail = new Dictionary<string, string>
{
6 months ago
{ "Accident", "ambulancemaiti@gmail.com" },
{ "Crime", "crime-authority@example.com" },
{ "Fire", "fire-department@example.com" },
{ "Other", "general-authority@example.com" }
};
}
/// <summary>
6 months ago
/// Gets the recipient email address based on the incident type.
/// </summary>
/// <param name="incidentType">The type of the incident.</param>
/// <returns>The email address of the recipient.</returns>
public string GetRecipientEmail(string incidentType)
{
return _incidentTypeToEmail.TryGetValue(incidentType, out var email) ? email : "amreitsyanf@gmail.com";
}
/// <summary>
/// Sends an email with an optional attachment.
/// </summary>
6 months ago
public async Task<bool> SendEmailWithAttachmentAsync(string recipientEmail, string subject, string body, string attachmentPath)
{
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);
6 months ago
if (!string.IsNullOrWhiteSpace(attachmentPath) && File.Exists(attachmentPath))
{
mailMessage.Attachments.Add(new Attachment(attachmentPath));
}
await smtpClient.SendMailAsync(mailMessage);
}
Console.WriteLine("Email sent successfully.");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Error sending email: {ex.Message}");
return false;
}
}
}
}