Ejemplo n.º 1
0
        public MailBag(bool?isWeb = true)
        {
            SiteSettings site = new SiteSettings();

            CompanyName     = site.CompanyName;
            CompanyMail     = site.CompanyEmail;
            CompanyWebsite  = site.CompanyWebsite;
            CompanyMailAuto = site.CompanyEmailAuto;

            //从config读取邮件配置
            MailSettingsSectionGroup mailSettings;

            if (isWeb == true)
            {
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
                mailSettings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
            }
            else
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);//OpenExeConfiguration2个方法的参数我也没搞清楚到底该怎么用。
                mailSettings = NetSectionGroup.GetSectionGroup(config).MailSettings;
            }

            this.m_SmtpUserName     = mailSettings.Smtp.Network.UserName;
            this.m_SmtpUserPassword = mailSettings.Smtp.Network.Password;
            this.From = mailSettings.Smtp.From;
            this.DefaultCredentials = mailSettings.Smtp.Network.DefaultCredentials;
            this.EnableSsl          = mailSettings.Smtp.Network.EnableSsl;
            this.Port = mailSettings.Smtp.Network.Port;
            this.Host = mailSettings.Smtp.Network.Host;

            this.IsBodyHtml   = true;
            this.BodyEncoding = 936;
        }
Ejemplo n.º 2
0
        public PerfCounters()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            NetSectionGroup netGroup = (NetSectionGroup)config.SectionGroups.Get("system.net");

            netGroup.Settings.PerformanceCounters.Enabled = true;

            config.Save(ConfigurationSaveMode.Modified); bytesSentPerformanceCounter = new PerformanceCounter();
            bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
            bytesSentPerformanceCounter.CounterName  = "Bytes Sent";
            bytesSentPerformanceCounter.InstanceName = GetInstanceName();
            bytesSentPerformanceCounter.ReadOnly     = true;

            bytesReceivedPerformanceCounter = new PerformanceCounter();
            bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
            bytesReceivedPerformanceCounter.CounterName  = "Bytes Received";
            bytesReceivedPerformanceCounter.InstanceName = GetInstanceName();
            bytesReceivedPerformanceCounter.ReadOnly     = true;

            connectionsEstablishedPerformanceCounter = new PerformanceCounter();
            connectionsEstablishedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
            connectionsEstablishedPerformanceCounter.CounterName  = "Connections Established";
            connectionsEstablishedPerformanceCounter.InstanceName = GetInstanceName();
            connectionsEstablishedPerformanceCounter.ReadOnly     = true;
        }
Ejemplo n.º 3
0
 private static void SendMail(MailMessage mailMessage, bool isAsync, string host = null, int port = 0, ICredentialsByHost credential = null)
 {
     if (null == mailMessage)
     {
         throw new ArgumentNullException("mailMessage");
     }
     if (mailMessage.To.IsNullOrEmpty() && mailMessage.CC.IsNullOrEmpty() && mailMessage.Bcc.IsNullOrEmpty())
     {
         throw new InvalidOperationException("No recievers specified");
     }
     if (mailMessage.Body.IsNullOrWhiteSpace())
     {
         throw new InvalidOperationException("No message body found");
     }
     mailMessage.IsBodyHtml = true;
     if (host == null)
     {
         SmtpSection cfg = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~/web.config")).MailSettings.Smtp;
         host       = cfg.Network.Host;
         port       = cfg.Network.Port;
         credential = new System.Net.NetworkCredential(cfg.Network.UserName, cfg.Network.Password);
     }
     if (isAsync)
     {
         var thread = new Thread(() => { SendMailProc(mailMessage, host, port, credential); })
         {
             IsBackground = true
         };
         thread.Start();
     }
     else
     {
         SendMailProc(mailMessage, host, port, credential);
     }
 }
Ejemplo n.º 4
0
        public static SmtpSection GetCurrentSmtpSettings(out System.Configuration.Configuration config)
        {
            config = GetCurrentConfiguration();
            // Get Mail settings.
            var settings = NetSectionGroup.GetSectionGroup(config).MailSettings;

            return(settings.Smtp);
        }
Ejemplo n.º 5
0
 private static bool _SendMail(string toEmail, string toEmails, string bcc, string cc, string subject, string displayName, string body, Attachment[] attachs, int timeout, bool async, SendCompletedEventHandler sendCompleted)
 {
     try
     {
         SmtpSection smtp = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath)).MailSettings.Smtp;
         MailAddress from = new MailAddress(smtp.From, displayName, Encoding.UTF8);
         MailAddress to   = new MailAddress(toEmail, null, Encoding.UTF8);
         MailMessage mail = new MailMessage(from, to);
         if (!string.IsNullOrWhiteSpace(toEmails))
         {
             mail.To.Add(toEmails);
         }
         if (!string.IsNullOrWhiteSpace(bcc))
         {
             mail.Bcc.Add(bcc);
         }
         if (!string.IsNullOrWhiteSpace(cc))
         {
             mail.CC.Add(cc);
         }
         mail.Subject         = subject;
         mail.SubjectEncoding = Encoding.UTF8;
         mail.Body            = body;
         mail.BodyEncoding    = Encoding.UTF8;
         if (attachs != null && attachs.Length > 0)
         {
             foreach (Attachment item in attachs)
             {
                 mail.Attachments.Add(item);
             }
         }
         mail.IsBodyHtml = true;
         mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
         SmtpClient smtpClient = new SmtpClient(smtp.Network.Host, smtp.Network.Port)
         {
             Timeout = timeout
         };
         if (sendCompleted != null)
         {
             smtpClient.SendCompleted += sendCompleted;
         }
         if (async)
         {
             smtpClient.SendAsync(mail, mail);
         }
         else
         {
             smtpClient.Send(mail);
             mail.Dispose();
         }
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// 静态构造函数,初始化默认发件人。
        /// </summary>
        static Sender()
        {
            MailSettingsSectionGroup ms = NetSectionGroup.GetSectionGroup(
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/web.config")).MailSettings;

            defaultFrom     = ms.Smtp.From;
            defaultHost     = ms.Smtp.Network.Host;
            defaultPort     = ms.Smtp.Network.Port;
            defaultUserName = ms.Smtp.Network.UserName;
            defaultPassword = ms.Smtp.Network.Password;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 邮件发送类
        /// 主机信息从配置文件中获取
        /// 参考:ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.chs/dv_fxgenref/html/54f0f153-17e5-4f49-afdc-deadb940c9c1.htm
        /// </summary>
        /// <param name="mailFrom">发件人地址</param>
        /// <param name="mailTo">收件人地址</param>
        /// <param name="mailSubject">邮件主题</param>
        /// <param name="mailBody">邮件正文</param>
        public SMTP(string[] mailTo, string mailSubject, string mailBody)
        {
            System.Configuration.Configuration config       = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            MailSettingsSectionGroup           mailSettings = NetSectionGroup.GetSectionGroup(config).MailSettings;

            mMailFrom        = mailSettings.Smtp.From;
            mMailDisplyName  = mailSettings.Smtp.From;
            mMailTo          = mailTo;
            mMailCc          = null;
            mMailBcc         = null;
            mMailSubject     = mailSubject;
            mMailBody        = mailBody;
            mMailAttachments = null;
            mSMTPServer      = mailSettings.Smtp.Network.Host;
            mSMTPPort        = mailSettings.Smtp.Network.Port;
            mSMTPUsername    = mailSettings.Smtp.Network.UserName;
            mSMTPPassword    = mailSettings.Smtp.Network.Password;
            mSMTPSSL         = false;
        }
Ejemplo n.º 8
0
        public bool Send()
        {
            SmtpSection cfg         = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~/Web.config")).MailSettings.Smtp;
            MailAddress mailAddress = new MailAddress(cfg.From);
            MailMessage mailMessage = new MailMessage();

            mailMessage.From            = mailAddress;
            mailMessage.Subject         = subject;
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.Body            = body;
            mailMessage.BodyEncoding    = Encoding.Default;
            mailMessage.Priority        = MailPriority.High;
            mailMessage.IsBodyHtml      = isbodyhtml;
            if (to != null)
            {
                for (int i = 0; i < to.Length; i++)
                {
                    mailMessage.To.Add(to[i]);
                }
            }

            if (cc != null)
            {
                for (int i = 0; i < cc.Length; i++)
                {
                    mailMessage.CC.Add(cc[i]);
                }
            }

            try
            {
                if (attachments != null && attachments.Length > 0)
                {
                    Attachment attachment = null;
                    foreach (string path in attachments)
                    {
                        attachment = new Attachment(path);
                        mailMessage.Attachments.Add(attachment);
                    }
                }
            }
            catch (Exception err)
            {
                throw new Exception("附件处错误:" + err);
            }
            SmtpClient client = new SmtpClient();

            client.Credentials = new System.Net.NetworkCredential(cfg.Network.UserName, cfg.Network.Password);

            //client.Port = cfg.Network.Port;
            client.Host      = cfg.Network.Host;
            client.EnableSsl = false;
            try
            {
                client.Send(mailMessage);
                return(true);
            }
            catch (Exception err)
            {
                return(false);
            }
        }
Ejemplo n.º 9
0
        public void Test_BundleSource()
        {
            // Setup ConfigurationManager
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.Sections.Clear();
            config.SectionGroups.Clear();
            NetSectionGroup          netSectionGroup  = config.SectionGroups.Get("system.net") as NetSectionGroup;
            MailSettingsSectionGroup smtpSectionGroup = netSectionGroup.SectionGroups.Get("mailSettings") as MailSettingsSectionGroup;
            SmtpSection smtpSection = smtpSectionGroup.Sections.Get("smtp") as SmtpSection;

            smtpSection.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
            smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation = AppDomain.CurrentDomain.BaseDirectory + "\\Test";
            ResetPickupDirectory(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
            config.Save();
            ConfigurationManager.RefreshSection("system.net");
            ConfigurationManager.RefreshSection("mailSettings");

            SnakeEyes.EmailTraceListener listener = new SnakeEyes.EmailTraceListener();
            listener.Attributes.Add("fromAddress", "*****@*****.**");
            listener.Attributes.Add("toAddress", "*****@*****.**");
            listener.Attributes.Add("throttleSeconds", "1");

            var source = new System.Diagnostics.TraceSource("TestSource", SourceLevels.Error);

            source.Listeners.Add(listener);

            {
                DateTime startTime = DateTime.UtcNow;
                for (int i = 0; i < 5; ++i)
                {
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "Damn");
                }
                System.Threading.Thread.Sleep(1000);
                Assert.GreaterOrEqual(DateTime.UtcNow.Subtract(startTime).TotalSeconds, 5);    // See throttle time works
                Assert.AreEqual(5, System.IO.Directory.GetFiles(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation).Length);
            }

            source.Listeners.Remove(listener);

            listener = new SnakeEyes.EmailTraceListener();
            listener.Attributes.Add("fromAddress", "*****@*****.**");
            listener.Attributes.Add("toAddress", "*****@*****.**");
            listener.Attributes.Add("throttleSeconds", "1");
            listener.Attributes.Add("formatBundleSource", "{{/TraceEvent/EventLogSource}}");
            listener.Attributes.Add("formatBody", "Message = {{/TraceEvent/EventLogSource}}");
            source.Listeners.Add(listener);
            ResetPickupDirectory(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
            {
                DateTime startTime = DateTime.UtcNow;
                for (int i = 0; i < 10; ++i)
                {
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "<TraceEvent><EventLogSource>Damn</EventLogSource></TraceEvent>");
                }
                System.Threading.Thread.Sleep(1000);
                Assert.Less(DateTime.UtcNow.Subtract(startTime).TotalSeconds, 2);    // See bundle time works
                Assert.AreEqual(2, System.IO.Directory.GetFiles(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation).Length);
            }
            source.Listeners.Remove(listener);

            // See that it can also bundle when receiving messages from different sources
            listener = new SnakeEyes.EmailTraceListener();
            listener.Attributes.Add("fromAddress", "*****@*****.**");
            listener.Attributes.Add("toAddress", "*****@*****.**");
            listener.Attributes.Add("throttleSeconds", "1");
            listener.Attributes.Add("formatBundleSource", "{{/TraceEvent/EventLogSource}}");
            listener.Attributes.Add("formatBody", "Message = {{/TraceEvent/EventLogSource}}");
            source.Listeners.Add(listener);
            ResetPickupDirectory(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
            {
                DateTime startTime = DateTime.UtcNow;
                for (int i = 0; i < 5; ++i)
                {
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "<TraceEvent><EventLogSource>Damn</EventLogSource></TraceEvent>");
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "<TraceEvent><EventLogSource>Again</EventLogSource></TraceEvent>");
                }
                System.Threading.Thread.Sleep(1000);
                Assert.Less(DateTime.UtcNow.Subtract(startTime).TotalSeconds, 3);    // See bundle time works
                Assert.AreEqual(3, System.IO.Directory.GetFiles(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation).Length);
            }
            source.Listeners.Remove(listener);
        }