using BuddyFinance.Integration.Logging; using BuddyFinance.Integration.Models.Enums; using BuddyFinance.Integration.Notifications; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BuddyFinance.Integration { public class NotificationsIntegrator { // private readonly Logger _logger = new Logger(); public bool SendOtp(string otp, string number) { var body = $"You are about to create a profile on Buddy Finance. Use OTP: {otp}"; return SendSMS(number, body); } public bool SendSMS(string to, string body, int? initiativeid = null) { // send SMS var sent = false; #region Variables string userId = ConfigurationManager.AppSettings["SMSPortalUserID"]; string pwd = ConfigurationManager.AppSettings["SMSPortalPassword"]; string postURL = ConfigurationManager.AppSettings["SMSPortalPostURL"]; StringBuilder postData = new StringBuilder(); string message = string.Empty; HttpWebRequest request = null; #endregion try { to = string.Join(",", to.Split('/').ToArray()); // Prepare POST data postData.Append("type=sendparam"); postData.Append("&username=" + userId); postData.Append("&password=" + pwd); postData.Append("&numto=" + to); postData.Append("&data1=" + body); byte[] data = new System.Text.ASCIIEncoding().GetBytes(postData.ToString()); request = (HttpWebRequest)WebRequest.Create(postURL); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; // Write data to stream using (Stream str = request.GetRequestStream()) { str.Write(data, 0, data.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { message = reader.ReadToEnd(); XDocument xdoc = XDocument.Parse(message); var success = xdoc.Root.Element("call_result").Element("result").Value == "True"; var reason = xdoc.Root.Element("call_result").Element("error").Value; if (success) { sent = true; // Log(LogTypeEnum type, string logDescription, int userId, string ipaddress, string userAgent) Logger.Log(LogTypeEnum.Information, "Successfully sent SMS to " + to, 0, "", ""); } else { //LogError((LogTypeEnum type ,string description,int userid, string ipaddress, //string useragent)) Logger.Log(LogTypeEnum.Error, "Failed to send an SMS to " + to + ". Reason: " + reason, 0, "", ""); // "",""); } } } } catch (Exception ex) { Logger.LogError(ex, 0, "", ""); } return sent; } public bool SendEmail(string to, string body, string subject, List attachments) { //send email bool sent; try { using (var smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"])) { var mail = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["NoReplyEmail"], ConfigurationManager.AppSettings["NoReplyName"]) }; var address = to.Split(';'); foreach (var addr in address.Where(addr => !string.IsNullOrEmpty(addr))) { mail.To.Add(new MailAddress(addr)); } if (attachments != null && attachments.Any()) { foreach (var attachment in attachments) { mail.Attachments.Add(new Attachment(new MemoryStream(attachment.Contents), attachment.Name ?? "RBKFileAttachment.pdf")); } } var credentials = new NetworkCredential(ConfigurationManager.AppSettings["SmtpUsername"], ConfigurationManager.AppSettings["SmtpPassword"]); smtpClient.Credentials = credentials; //smtpClient.EnableSsl = true; smtpClient.Port = 587; mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; mail.BodyEncoding = Encoding.UTF8; mail.SubjectEncoding = Encoding.Default; var now = DateTime.Now; mail.Headers.Add("Message-Id", String.Concat("<", now.ToString("yyMMdd"), ".", now.ToString("HHmmss"), "@buddyfinance.co.za>")); mail.Headers.Add("Content-Type", "multipart/mixed;"); smtpClient.Send(mail); Logger.Log(LogTypeEnum.Information, "Email sent successfully to " + to + ", subject: " + subject, 0, "", ""); sent = true; } } catch (Exception ex) { // _logger.Log(LogTypeEnum. "Failed to send Email to " + to + ", subject: " + subject, user, ipaddress, useragent); Logger.LogError(ex, 0, "", ""); sent = false; } return sent; } public async Task SendEmailSendGridAsync(string to, string body, string subject, List attachments) { bool sent; try { var mail = new MailMessage { From = new MailAddress( ConfigurationManager.AppSettings["NoReplyEmail"], ConfigurationManager.AppSettings["NoReplyName"] ) }; var address = to.Split(';'); foreach (var addr in address.Where(addr => !string.IsNullOrEmpty(addr))) { mail.To.Add(new MailAddress(addr)); } if (attachments != null && attachments.Any()) { foreach (var attachment in attachments) { mail.Attachments.Add(new Attachment(new MemoryStream(attachment.Contents), attachment.Name ?? "RBKFileAttachment.pdf")); } } mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; mail.BodyEncoding = Encoding.UTF8; mail.SubjectEncoding = Encoding.Default; var key = ConfigurationManager.AppSettings["SendGridKey"]; var now = DateTime.Now; mail.Headers.Add("Message-Id", String.Concat("<", now.ToString("yyMMdd"), ".", now.ToString("HHmmss"), "@buddyfinance.co.za>")); mail.Headers.Add("Content-Type", "multipart/mixed;"); var client = new SmtpClient(host: "smtp.sendgrid.net", port: 587) { Credentials = new NetworkCredential( userName: "apikey", // the userName is the exact string "apikey" and not the API key itself. password: key ) }; await client.SendMailAsync(mail); Logger.Log(LogTypeEnum.Information, "Email sent successfully to " + to + ", subject: " + subject, 0, "", ""); sent = true; } catch (Exception ex) { // _logger.Log(LogTypeEnum. "Failed to send Email to " + to + ", subject: " + subject, user, ipaddress, useragent); Logger.LogError(ex, 0, "", ""); sent = false; } return sent; } } }