NonInventPurchasingSystem/CPRNIMS.Infrastructure/Helper/SMTPHelper.cs
2026-01-20 07:44:30 +08:00

119 lines
4.7 KiB
C#

using CPRNIMS.Infrastructure.ViewModel.Common;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace CPRNIMS.Infrastructure.Helper
{
public class SMTPHelper
{
private readonly IConfiguration _configuration;
public SMTPHelper(IConfiguration configuration)
{
_configuration = configuration;
}
public bool IsAuthError { get; private set; }
public string EMailTemplate(string contentPath)
{
// Get the physical path to the template folder
string templateFolderPath = Path.Combine(contentPath);
// Read the content of the template file
string body = File.ReadAllText(templateFolderPath);
return body;
}
public string GenerateOTP()
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var otp = new string(Enumerable.Repeat(chars, 8)
.Select(s => s[random.Next(s.Length)])
.ToArray());
return otp;
}
public async Task<bool> SendEmailAsync(EmailMessageDetailsVM emailMessageBody)
{
try
{
if (string.IsNullOrWhiteSpace(emailMessageBody?.Recipient))
{
Console.WriteLine("Email address is null or empty. Cannot send email.");
return false;
}
using (MailMessage myMessage = new MailMessage())
{
// Split the recipient string by semicolon and add each email address individually
var recipients = emailMessageBody.Recipient.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var recipient in recipients)
{
myMessage.To.Add(recipient.Trim());
}
// myMessage.To.Add(emailMessageBody.Recipient);
myMessage.Sender = new MailAddress(emailMessageBody.SenderEmail);
myMessage.From = new MailAddress(emailMessageBody.SenderEmail, emailMessageBody.DisplayName);
var cc = emailMessageBody.CC.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if(cc.Length > 0)
{
foreach (var ccs in cc)
{
myMessage.CC.Add(ccs.Trim());
}
}
myMessage.Subject = emailMessageBody.Subject;
// Ensure the email body is correctly formatted HTML
myMessage.Body = emailMessageBody.Message;
myMessage.IsBodyHtml = true;
if (emailMessageBody.IsCanvass)
{
if (File.Exists(emailMessageBody.AttachPath))
{
Attachment pdfAttachment = new Attachment(emailMessageBody.AttachPath);
pdfAttachment.Name = Path.GetFileName(emailMessageBody.AttachPath);
myMessage.Attachments.Add(pdfAttachment);
}
}
using (SmtpClient smtp = new SmtpClient(emailMessageBody.Server))
{
smtp.Port = emailMessageBody.OutGoingPort;
smtp.UseDefaultCredentials = emailMessageBody.IsSuccess;
smtp.Credentials = new System.Net.NetworkCredential(emailMessageBody.UserName, emailMessageBody.NewPassword);
smtp.EnableSsl = true;
try
{
await smtp.SendMailAsync(myMessage);
Console.WriteLine("Email sent successfully.");
return true;
}
catch (Exception ex)
{
var Message = ex.InnerException?.ToString() ?? ex.Message.ToString();
Console.WriteLine($"Error sending email: {Message}");
return false;
}
}
}
}
catch (Exception ex)
{
IsAuthError = true;
var Message = ex.InnerException?.ToString() ?? ex.Message.ToString();
Console.WriteLine($"Error in SendEmailAsync: {Message}");
return false;
}
}
}
}