Advertisement
nahidjamalli

Mail Sender

Apr 12th, 2020
3,803
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.67 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Configuration;
  8. using System.Net.Mail;
  9. using System.Reflection;
  10. using System.Threading;
  11.  
  12. namespace Bsixmail
  13. {
  14.  
  15.     public class BsixMailer
  16.     {
  17.         static void Main(string[] args)
  18.         {
  19.             // example with approval
  20.             //var _Base = _config.GetSection("BsixMail").GetSection("UrlBase").Value;
  21.             var mailer = new BsixMailer();
  22.             mailer.BuildBody(new
  23.             {
  24.                 Message = "hello from bsix aproval",
  25.                 UrlApprove = string.Format("{0}/{1}/{2}", "_Base", "Approve", "yes"),
  26.                 UrlReject = string.Format("{0}/{1}/{2}", "_Base", "Approve", "no")
  27.             }, "default.txt") // <--- your template mail located inside BsixMail folder
  28.                 .EmailTo("mailto@example.com")
  29.                 .EmailSubject("This is subject")
  30.                 .Send();
  31.  
  32.             // example
  33.             mailer.BuildBody(new
  34.             {
  35.                 Message = "hello from bsix"
  36.             }, "default.txt")  // <--- your template mail located inside BsixMail folder
  37.                 .EmailTo("mailto@example.com")
  38.                 .EmailSubject("This is subject")
  39.                 .SendBackground(); // <--- background task email
  40.         }
  41.         #region Property
  42.         private SmtpSection MailConfig = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
  43.         private string folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BsixMail");
  44.         private string Body { get; set; }
  45.         private List<string> To { get; set; }
  46.         private List<string> CC { get; set; }
  47.         private List<string> Bcc { get; set; }
  48.         private string Subject { get; set; }
  49.         private List<Attachment> Attachment { get; set; }
  50.         private MailPriority Priority { get; set; }
  51.  
  52.         #endregion
  53.  
  54.         #region Build Body
  55.         public BsixMailer BuildBody(object yourObject, string yourTemplate)
  56.         {
  57.             string body = string.Empty;
  58.  
  59.             if (string.IsNullOrEmpty(yourTemplate)) yourTemplate = "Defalt.txt";
  60.  
  61.             body = ReadFileFrom(yourTemplate);
  62.  
  63.             Type myType = yourObject.GetType();
  64.             IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
  65.  
  66.             if (string.IsNullOrWhiteSpace(body))
  67.             {
  68.                 body = "<html><head><title></title></head><body>";
  69.  
  70.                 foreach (PropertyInfo prop in props)
  71.                 {
  72.                     object propValue = prop.GetValue(yourObject, null);
  73.                     object propName = prop.Name;
  74.  
  75.                     string propertyReplace = "{{" + propName.ToString() + "}}";
  76.  
  77.                     body += propName.ToString() + " : " + propertyReplace + "<hr/>";
  78.                 }
  79.                 body += "</body><html>";
  80.  
  81.                 WriteTemplate(body, yourTemplate);
  82.             }
  83.  
  84.             foreach (PropertyInfo prop in props)
  85.             {
  86.                 object propValue = prop.GetValue(yourObject, null);
  87.                 object propName = prop.Name;
  88.  
  89.                 string propertyReplace = "{{" + propName.ToString() + "}}";
  90.                 string propertyValueReplace = propValue == null ? "Unbind Model" : propValue.ToString();
  91.  
  92.                 if (body.Contains(propertyReplace))
  93.                 {
  94.                     body = body.Replace(propertyReplace, propertyValueReplace);
  95.                 }
  96.             }
  97.  
  98.             this.Body = body;
  99.  
  100.             return this;
  101.         }
  102.  
  103.         private string ReadFileFrom(string templateName)
  104.         {
  105.             bool folderExists = Directory.Exists(folder);
  106.  
  107.             if (!folderExists) Directory.CreateDirectory(folder);
  108.  
  109.             string filePath = folder + "/" + templateName;
  110.  
  111.             if (!File.Exists(filePath))
  112.             {
  113.                 (new FileInfo(filePath)).Directory.Create();
  114.                 using (TextWriter tw = new StreamWriter(filePath))
  115.                 {
  116.                     tw.WriteLine(string.Empty);
  117.                     tw.Close();
  118.                 }
  119.             }
  120.  
  121.             string body = File.ReadAllText(filePath);
  122.  
  123.             return body;
  124.         }
  125.  
  126.         private void WriteTemplate(string body, string templateName)
  127.         {
  128.             string filePath = folder + "/" + templateName;
  129.  
  130.             string s = string.Empty;
  131.             // Open the file to read from.
  132.             using (StreamReader sr = File.OpenText(filePath))
  133.             {
  134.                 while ((s = sr.ReadLine()) != null)
  135.                 {
  136.                     s = s + s;
  137.                 }
  138.             }
  139.  
  140.             if (!string.IsNullOrEmpty(body))
  141.             {
  142.                 if (!File.Exists(filePath) || string.IsNullOrEmpty(s))
  143.                 {
  144.                     // Create a file to write to.
  145.                     using (StreamWriter tw = File.CreateText(filePath))
  146.                     {
  147.                         tw.WriteLine(body);
  148.                         tw.Close();
  149.                     }
  150.                 }
  151.             }
  152.         }
  153.         #endregion
  154.  
  155.         #region To, CC, BCC, Subject, credentials
  156.  
  157.  
  158.         public BsixMailer EmailTo(params string[] EmailTo)
  159.         {
  160.             this.To = EmailTo.ToList();
  161.             return this;
  162.         }
  163.  
  164.         public BsixMailer CCTo(params string[] CCTo)
  165.         {
  166.             this.CC = CCTo.ToList();
  167.             return this;
  168.         }
  169.  
  170.         public BsixMailer BCCTo(params string[] BCCTo)
  171.         {
  172.             this.Bcc = BCCTo.ToList();
  173.             return this;
  174.         }
  175.  
  176.         public BsixMailer EmailSubject(string Subject)
  177.         {
  178.             this.Subject = Subject;
  179.             return this;
  180.         }
  181.         #endregion
  182.  
  183.         #region Attachment, Priority
  184.         public BsixMailer Attacment(params Attachment[] attachment)
  185.         {
  186.             this.Attachment = attachment.ToList();
  187.             return this;
  188.         }
  189.  
  190.         public BsixMailer EmailPriority(MailPriority priority)
  191.         {
  192.             this.Priority = priority;
  193.             return this;
  194.         }
  195.         #endregion
  196.  
  197.         #region sender
  198.         public void SendBackground()
  199.         {
  200.             new Thread(() =>
  201.             {
  202.                 Thread.CurrentThread.IsBackground = true;
  203.  
  204.                 MailMessage mail = new MailMessage
  205.                 {
  206.                     Sender = new MailAddress(MailConfig.From),
  207.                     From = new MailAddress(MailConfig.From),
  208.                     Body = this.Body,
  209.                     Subject = this.Subject
  210.                 };
  211.  
  212.                 if (this.To != null)
  213.                 {
  214.                     foreach (var item in this.To)
  215.                     {
  216.                         mail.To.Add(item);
  217.                     }
  218.                 }
  219.  
  220.                 if (this.CC != null)
  221.                 {
  222.                     foreach (var item in this.CC)
  223.                     {
  224.                         mail.CC.Add(item);
  225.                     }
  226.                 }
  227.  
  228.                 if (this.Bcc != null)
  229.                 {
  230.                     foreach (var item in this.Bcc)
  231.                     {
  232.                         mail.Bcc.Add(item);
  233.                     }
  234.                 }
  235.  
  236.                 if (this.Attachment != null)
  237.                 {
  238.                     foreach (var item in this.Attachment)
  239.                     {
  240.                         mail.Attachments.Add(item);
  241.                     }
  242.                 }
  243.  
  244.                 mail.Priority = this.Priority;
  245.                 mail.IsBodyHtml = true;
  246.  
  247.                 try
  248.                 {
  249.                     using (var client = new SmtpClient(MailConfig.Network.Host))
  250.                     {
  251.                         client.Port = MailConfig.Network.Port;
  252.                         client.Credentials = new NetworkCredential(MailConfig.Network.UserName, MailConfig.Network.Password);
  253.                         client.EnableSsl = MailConfig.Network.EnableSsl;
  254.                         client.Send(mail);
  255.                     }
  256.                 }
  257.                 catch (Exception e)
  258.                 {
  259.                     string path = folder + "/" + "Error_" + DateTime.Now.ToString("dd_MMM_yyyy") + ".txt";
  260.                     if (!File.Exists(path))
  261.                     {
  262.                         (new FileInfo(path)).Directory.Create();
  263.                         using (TextWriter tw = new StreamWriter(path))
  264.                         {
  265.                             tw.WriteLine(mail.Subject + "|" + mail.Body + "|" + e.ToString() + Environment.NewLine);
  266.                             tw.Close();
  267.                         }
  268.                     }
  269.                     else
  270.                     {
  271.                         using (StreamWriter tw = File.AppendText(path))
  272.                         {
  273.                             tw.WriteLine(mail.Subject + "|" + e.ToString() + Environment.NewLine);
  274.                             tw.Close();
  275.                         }
  276.                     }
  277.                 }
  278.  
  279.  
  280.             }).Start();
  281.         }
  282.  
  283.         public int Send()
  284.         {
  285.             MailMessage mail = new MailMessage
  286.             {
  287.                 Sender = new MailAddress(MailConfig.From),
  288.                 From = new MailAddress(MailConfig.From),
  289.                 Body = this.Body,
  290.                 Subject = this.Subject
  291.             };
  292.  
  293.             if (this.To != null)
  294.             {
  295.                 foreach (var item in this.To)
  296.                 {
  297.                     mail.To.Add(item);
  298.                 }
  299.             }
  300.  
  301.             if (this.CC != null)
  302.             {
  303.                 foreach (var item in this.CC)
  304.                 {
  305.                     mail.CC.Add(item);
  306.                 }
  307.             }
  308.  
  309.             if (this.Bcc != null)
  310.             {
  311.                 foreach (var item in this.Bcc)
  312.                 {
  313.                     mail.Bcc.Add(item);
  314.                 }
  315.             }
  316.  
  317.             if (this.Attachment != null)
  318.             {
  319.                 foreach (var item in this.Attachment)
  320.                 {
  321.                     mail.Attachments.Add(item);
  322.                 }
  323.             }
  324.  
  325.             mail.Priority = this.Priority;
  326.             mail.IsBodyHtml = true;
  327.  
  328.             try
  329.             {
  330.                 using (var client = new SmtpClient(MailConfig.Network.Host))
  331.                 {
  332.                     client.Port = MailConfig.Network.Port;
  333.                     client.Credentials = new NetworkCredential(MailConfig.Network.UserName, MailConfig.Network.Password);
  334.                     client.EnableSsl = MailConfig.Network.EnableSsl;
  335.                     client.Send(mail);
  336.                 }
  337.             }
  338.             catch (Exception e)
  339.             {
  340.                 string path = folder + "/" + "Error_" + DateTime.Now.ToString("dd_MMM_yyyy") + ".txt";
  341.                 if (!File.Exists(path))
  342.                 {
  343.                     (new FileInfo(path)).Directory.Create();
  344.                     using (TextWriter tw = new StreamWriter(path))
  345.                     {
  346.                         tw.WriteLine(mail.Subject + "|" + mail.Body + "|" + e.ToString() + Environment.NewLine);
  347.                         tw.Close();
  348.                     }
  349.                 }
  350.                 else
  351.                 {
  352.                     using (StreamWriter tw = File.AppendText(path))
  353.                     {
  354.                         tw.WriteLine(mail.Subject + "|" + e.ToString() + Environment.NewLine);
  355.                         tw.Close();
  356.                     }
  357.                 }
  358.  
  359.                 return 0;
  360.             }
  361.  
  362.             return this.To.Count;
  363.         }
  364.         #endregion
  365.     }
  366. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement