Tuesday, August 19, 2025

Send emails using SendGrid using C#

 public static bool SendMail(EmailDTO emailDTO, bool showOEEFooter, bool isSCECHSponsor = false)
        {
            try
            {
                var apiKey = Utility.GetAppSettingsValue(MOECSAppSettings.SENDGRID_APIKEY);
                var sendGridClient = new SendGridClient(apiKey);

                var mailMessage = new SendGridMessage();

                string fromAddress = Utility.GetAppSettingsValue(MOECSAppSettings.SENDGRID_FROM_ADDRESS);
                mailMessage.From = new EmailAddress(fromAddress, fromAddress);

                string environment = Utility.GetAppSettingsValue(MOECSAppSettings.ENVIRONMENT)?.ToLower();

                if (isSCECHSponsor)
                {
                    mailMessage.AddReplyTo(Utility.GetAppSettingsValue(MOECSAppSettings.SCECH_FROM_ADDRESS));
                }

                List<EmailAddress> toEmails;
                if (environment == ApplicationSettings.MOECS_PRODUCTION)
                {
                    mailMessage.AddTo(new EmailAddress(emailDTO.ToAddress));
                    mailMessage.Subject = emailDTO.Subject;

                    toEmails = new List<EmailAddress> { new EmailAddress(emailDTO.ToAddress) };
                }
                else
                {
                    string fallbackToAddress = Utility.GetAppSettingsValue(MOECSAppSettings.TO_ADDRESS);

                    var fallbackEmails = new List<EmailAddress>();
                    if (emailDTO.ToAddress.Contains(";"))
                    {
                        fallbackEmails = emailDTO.ToAddress.Split(';').Select(_ => new EmailAddress(fallbackToAddress)).ToList();
                    }
                    else if (emailDTO.ToAddress.Contains(","))
                    {
                        fallbackEmails = emailDTO.ToAddress.Split(',').Select(_ => new EmailAddress(fallbackToAddress)).ToList();
                    }
                    else
                    {
                        fallbackEmails.Add(new EmailAddress(fallbackToAddress));
                    }

                    mailMessage.AddTos(fallbackEmails);
                    mailMessage.Subject = $"{environment.ToUpper()} - {emailDTO.Subject}";

                    toEmails = fallbackEmails;
                }

                //string bcc = Utility.GetAppSettingsValue(MOECSAppSettings.BCC_ADDRESS)?.Trim();
                //if (!string.IsNullOrEmpty(bcc))
                //{
                //    mailMessage.AddBcc(new EmailAddress(bcc));
                //}

                var ccEmails = !string.IsNullOrEmpty(emailDTO.CCAddress)
                   ? emailDTO.CCAddress.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)
                   .Select(e => new EmailAddress(e.Trim())).ToList() : new List<EmailAddress>();

                var bccEmails = !string.IsNullOrEmpty(Utility.GetAppSettingsValue(MOECSAppSettings.BCC_ADDRESS))
                    ? Utility.GetAppSettingsValue(MOECSAppSettings.BCC_ADDRESS)
                    .Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(e => new EmailAddress(e.Trim())).ToList() : new List<EmailAddress>();

                ccEmails = ccEmails.Where(cc => !toEmails.Any(to => to.Email.Equals(cc.Email, StringComparison.OrdinalIgnoreCase))).ToList();

                bccEmails = bccEmails.Where(bcc => !toEmails.Any(to => to.Email.Equals(bcc.Email, StringComparison.OrdinalIgnoreCase)) &&
                                                   !ccEmails.Any(cc => cc.Email.Equals(bcc.Email, StringComparison.OrdinalIgnoreCase))).ToList();

                if (ccEmails.Any())
                {
                    mailMessage.AddCcs(ccEmails);
                }

                if (bccEmails.Any())
                {
                    mailMessage.AddBccs(bccEmails);
                }

                string bodyContent = formatMessage(emailDTO.FullName, emailDTO.Body, showOEEFooter, emailDTO.TemplateID, isSCECHSponsor);
                mailMessage.PlainTextContent = bodyContent;
                mailMessage.HtmlContent = bodyContent;

                if (emailDTO.Attachment != null)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        emailDTO.Attachment.CopyTo(memoryStream);
                        byte[] fileBytes = memoryStream.ToArray();
                        string base64File = Convert.ToBase64String(fileBytes);

                        mailMessage.AddAttachment(new Attachment
                        {
                            Content = base64File,
                            Filename = emailDTO.AttachmentFileName,
                            Type = MediaTypeNames.Application.Octet,
                            Disposition = "attachment"
                        });
                    }
                }

                var response = sendGridClient.SendEmailAsync(mailMessage).GetAwaiter().GetResult();

                if (!response.IsSuccessStatusCode)
                {
                    string errorBody = response.Body.ReadAsStringAsync().GetAwaiter().GetResult();
                    LoggerUtility.WriteLog($"SendGrid Error: {response.StatusCode} - {errorBody}", System.Diagnostics.TraceEventType.Error);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                LoggerUtility.WriteLog($"Exception: {ex.Message}", System.Diagnostics.TraceEventType.Error);
                return false;
            }
        }


  public static bool SendMail(EmailDTO emailDTO)
        {
            return SendMail(emailDTO, true);
        }

  private static string formatMessage(string fullName, string messageBody, bool showOEEFooter, int templateID, bool isSCECHSponsor)
        {
            string content = string.Empty;
            TextInfo txtInfo = new CultureInfo("en-US", false).TextInfo;

            string footer = string.Empty;

            if (showOEEFooter == true)
            {
                footer = CacheUtil.GetMessageDescription(MOECSMessage.OEE_ADDRESS_CONTACT_HTML);
            }

            if (isSCECHSponsor)
            {
                footer = CacheUtil.GetMessageDescription(MOECSMessage.SCECH_EMAIL_FOOTER);
            }
            else
            {
                //attach no reply message to the footer
                footer = footer + CacheUtil.GetMessageDescription(MOECSMessage.NOREPLY_EMAIL_FOOTER);
            }

            if (templateID > 0)
            {
                footer = footer + "<br/><br/>EmailID: " + templateID;
            }

            if (!string.IsNullOrEmpty(fullName))
            { content = string.Format("Dear {0}<br/><br/>{1}", txtInfo.ToTitleCase(fullName.ToLower()+":"), messageBody); }
            else
            { content = messageBody; }

            content = string.Format("{0} {1}", content, footer);

            return content;
        }

 public static string GetAppSettingsValue(String key)
        {
            return ConfigurationManager.AppSettings.Get(key);
        }