Exemplo n.º 1
0
        private static void Main(string[] args)
        {
            const string smtpHost     = "smtp.socketlabs.com";
            int          smtpPort     = 2525; // standard is port 25 but that is blocked by many ISP's
            string       smtpUserName = "******";
            string       smtpPassword = "******";

            var creds = new NetworkCredential(smtpUserName, smtpPassword);
            var auth  = creds.GetCredential(smtpHost, smtpPort, "Basic");

            using (var msg = new MailMessage())
                using (var smtp = new SmtpClient())
                {
                    // ** can be set in config **
                    // you can skip this set by setting your credentials in the web.config or app.config
                    // http://msdn.microsoft.com/en-us/library/w355a94k.aspx
                    smtp.Host        = smtpHost;
                    smtp.Port        = smtpPort;
                    smtp.Credentials = auth;
                    // ** can be set in config **

                    msg.From = new MailAddress("*****@*****.**");
                    msg.To.Add("*****@*****.**");
                    msg.Subject    = "Using the SMTP client with SocketLabs.";
                    msg.Body       = "<h1>Hello</h1><p>How are you doing today?</p>";
                    msg.IsBodyHtml = true;

                    smtp.Send(msg);
                }

            Console.WriteLine("Email Sent");
            Console.Read();
        }
Exemplo n.º 2
0
        public bool SendMail()
        {
            MailMessage message = new MailMessage(FromAddress, ToAddress, Subject, MessageText);

            SetServer();
            SmtpClient client = new SmtpClient();

            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl      = EnableSSL;
            client.Port           = Port;

            if (Encrypted)
            {
            }
            message.CC.Add(CC);
            message.Bcc.Add(BCC);
            client.Host = _SMTPServer;
            NetworkCredential credential = new NetworkCredential(_SMTPUsername, _SMTPPassword);

            credential.GetCredential(client.Host, Port, AuthenticationType);
            client.UseDefaultCredentials = false;
            client.Credentials           = credential;
            message.ReplyTo = message.From;
            try
            {
                client.Send(message);
            }
            catch (Exception err)
            {
                MMDBExceptionHandler.HandleException(err);
                throw(err);
            }
            return(true);
        }
Exemplo n.º 3
0
        public void SendMail()
        {
            if (!PrapertyEmailAddress)
            {//前提条件没有准备齐全,拒绝发送邮件操作
                return;
            }
            SmtpClient client = new SmtpClient();

            client.Host = EmailHost;
            if (EmailServicePort.HasValue)
            {
                client.Port = EmailServicePort.Value;
            }
            //client.UseDefaultCredentials = false;
            client.EnableSsl = MailEnableSsl;//使用安全套接字【当使用qq发送邮件时这个安全套接字的值必须是true】
            try
            {
                if (!MailEnablePswAuthentication)
                {
                    NetworkCredential nc = new NetworkCredential(UseMailOfUserName, UseMailOfUserPassword);
                    client.Credentials = nc.GetCredential(client.Host, client.Port, "NTLM");
                }
                else
                {
                    client.Credentials = new NetworkCredential(UseMailOfUserName, UseMailOfUserPassword);// ; new NetworkCredential(MailSendUserName, MailSendUserPassword);
                }
                //  client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Send(Mail);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    public static void GetPage(string url, string userName, string password)
    {
        try
        {
// <Snippet1>
            // Create an empty instance of the NetworkCredential class.
            NetworkCredential myCredentials = new NetworkCredential(userName, password);
            // Create a webrequest with the specified URL.
            WebRequest myWebRequest = WebRequest.Create(url);
            myWebRequest.Credentials = myCredentials.GetCredential(new Uri(url), "");
            Console.WriteLine("\n\nUser Credentials:- UserName : {0} , Password : {1}", myCredentials.UserName, myCredentials.Password);
            // Send the request and wait for a response.
            Console.WriteLine("\n\nRequest to Url is sent.Waiting for response...Please wait ...");
            WebResponse myWebResponse = myWebRequest.GetResponse();
            // Process the response.
            Console.WriteLine("\nResponse received successfully");
            // Release the resources of the response object.
            myWebResponse.Close();
// </Snippet1>
        }
        catch (WebException e)
        {
            Console.WriteLine("\r\nWebException is raised. The Reason for failure is : {0}", e.Status);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following exception was raised : {0}", e.Message);
        }
    }
Exemplo n.º 5
0
        /// <summary>
        /// 获取SMTP Client实例
        /// </summary>
        /// <param name="server"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private SmtpClient GetSmtpClient(string server, int port)
        {
            //构造SMTP的连接器
            SmtpClient smtp = new SmtpClient(server, port);

            if (!string.IsNullOrEmpty(this.HostName))
            {
                FieldInfo field = smtp.GetType().GetField("localHostName", BindingFlags.Instance | BindingFlags.NonPublic);
                if (field != null)
                {
                    field.SetValue(smtp, this.HostName);
                }
            }
            //超时设置
            smtp.Timeout = this.Server.Timeout;
            if (this.Server.EnableAuth)
            {
                //设置凭据
                NetworkCredential credential = new NetworkCredential(this.Server.UserName, this.Server.Password);

                if (this.Server.EnableSsl)
                {
                    //SSL验证
                    smtp.Credentials = credential;
                    smtp.EnableSsl   = this.Server.EnableSsl;
                }
                else
                {
                    //普通验证
                    smtp.Credentials = credential.GetCredential(server, port, this.Server.AuthenticationType);
                }
            }
            return(smtp);
        }
Exemplo n.º 6
0
 void CheckDefaults(NetworkCredential nc)
 {
     Assert.AreSame(String.Empty, nc.Domain, "Domain");
     Assert.AreSame(String.Empty, nc.Password, "Password");
     Assert.AreSame(String.Empty, nc.UserName, "UserName");
     Assert.AreSame(nc, nc.GetCredential(null, null), "GetCredential");
 }
Exemplo n.º 7
0
        /// <summary>
        /// 发送邮件(仅用于SMTP25或Explicit SSL(587端口)发送,Implicit SSL使用:SendSSLEmailL)
        /// 该方法仅用于测试,使用请用异步调用
        /// </summary>
        /// <param name="account">邮箱名</param>
        /// <param name="passwd">邮箱密码</param>
        /// <param name="server">SMTP服务器域名</param>
        /// <param name="port">SMTP为25,SSL:465,如果使用IMAP则需另设</param>
        /// <param name="mailInfo">邮件内容</param>
        /// <param name="attach">附件物理地址</param>
        /// <returns></returns>
        public static MailState SendEmail(string account, string passwd, string server, MailInfo mailInfo, string[] attach)
        {
            SmtpClient        client     = new SmtpClient(server, 25);
            NetworkCredential credential = new NetworkCredential(account, passwd);

            client.UseDefaultCredentials = true;
            client.EnableSsl             = false;
            client.Credentials           = credential.GetCredential(server, 25, "Basic");
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            //--------------------------------------------------
            MailMessage mailMessage = GetMailMessage(mailInfo, account);

            mailMessage.BodyEncoding = Encoding.UTF8;
            mailMessage.IsBodyHtml   = true;
            foreach (string file in attach)//物理路径
            {
                if (string.IsNullOrEmpty(file))
                {
                    continue;
                }
                Attachment item = new Attachment(file);
                mailMessage.Attachments.Add(item);
            }
            client.Send(mailMessage);
            MailState state = MailState.Ok;

            return(state);
        }
Exemplo n.º 8
0
        void Connect()
        {
            SelectButton.IsEnabled   = false;
            RestartButton.IsEnabled  = false;
            Progress.IsIndeterminate = true;

            if (!worker.Busy)
            {
                logger.Clear();
                logger.Write("Connecting to " + Model.Uri);

                NetworkCredential cred = CredentialCache.DefaultNetworkCredentials;

                var isBasicAuth = useBasicAuth.IsChecked == true;
                if (isBasicAuth)
                {
                    var cred2 = new NetworkCredential()
                    {
                        UserName = loginName.Text.Trim(),
                        Password = password.Password.Trim()
                    };
                    cred = cred2.GetCredential(new Uri(Model.Uri), "Basic");
                }
                worker
                .Failure(Discovery_Failure)
                .Complete(Discovery_Connect)
                .Connect(Model.Uri, cred, isBasicAuth);
            }
        }
Exemplo n.º 9
0
        public void SendAsync(string senderEmail, string senderName, List <string> toList, List <string> ccList, string title, List <string> attachedFiles, string content, bool isBodyHtml = false, object callbackData = null)
        {
            mailMessage       = new MailMessage();
            mailMessage.From  = new MailAddress(senderEmail, senderName);
            this.callbackData = callbackData;

            if (toList != null)
            {
                foreach (var to in toList)
                {
                    mailMessage.To.Add(to);
                }
            }

            if (ccList != null)
            {
                foreach (var cc in ccList)
                {
                    mailMessage.CC.Add(cc);
                }
            }

            if (attachedFiles != null)
            {
                AddAttachments(attachedFiles);
            }

            mailMessage.Subject         = title;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.Body            = content;
            mailMessage.IsBodyHtml      = isBodyHtml;
            mailMessage.BodyEncoding    = System.Text.Encoding.UTF8;
            mailMessage.Priority        = EMailPriority;

            smtpClient                       = new SmtpClient(smtpServer, smtpPort);
            smtpClient.Host                  = smtpServer;
            smtpClient.EnableSsl             = EnableSSL;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtpClient.SendCompleted        += new SendCompletedEventHandler(SendCompletedCallback);

            if (EnablePasswordAuthentication)
            {
                NetworkCredential networkCredential = new NetworkCredential(loginName, password);
                smtpClient.Credentials = networkCredential.GetCredential(smtpServer, smtpPort, "NTLM");
            }
            else
            {
                smtpClient.Credentials = new NetworkCredential(loginName, password);
            }

            try
            {
                smtpClient.SendAsync(mailMessage, MailToken);
            }
            catch (Exception exception)
            {
                LogHelper.Error(exception);
            }
        }
Exemplo n.º 10
0
 void CheckCustom(NetworkCredential nc)
 {
     Assert.AreEqual("dom", nc.Domain, "Domain");
     Assert.AreEqual("********", nc.Password, "Password");
     Assert.AreEqual("user", nc.UserName, "UserName");
     Assert.AreSame(nc, nc.GetCredential(new Uri("http://www.mono-project.com"), "basic"), "GetCredential");
 }
Exemplo n.º 11
0
        private void button1_Click(object sender, EventArgs e)
        {
            fdResp.Text = "please wait ..";
            Uri uri = new Uri(fdUrl.Text);
            WebResponse resp;
            WebRequest req = WebRequest.Create(uri);

            if (fdUseCred.Checked == true)
            {
                NetworkCredential cred = new NetworkCredential(fdUser.Text, fdPw.Text);
                ICredentials icred = cred.GetCredential(uri, "basic");
                req.Credentials = icred;
            }

            // Hello world 1234
            if (fdUseProxy.Checked == true) {
               req.Proxy = new System.Net.WebProxy(fdProxy.Text, true);
               req.Proxy.Credentials = CredentialCache.DefaultCredentials;
            }

            req.Timeout = 12000;

            try
            {
                resp = req.GetResponse();
                fdResp.Text = resp.Headers.ToString();
            }
            catch( Exception ex)
            {
                fdResp.Text = ex.ToString();
            }
        }
Exemplo n.º 12
0
        private void SendMail(string host, int port, string from, string to, string subj, string msg)
        {
            SmtpClient  client  = new SmtpClient(host, port);
            MailMessage message = new MailMessage();

            try
            {
                MailAddress fromAddress = new MailAddress(from, "Sender");
                MailAddress toAddress   = new MailAddress(to, "Recipient");

                message.From = fromAddress;
                message.To.Add(toAddress);
                message.Subject = subj;
                message.Body    = msg;

                client.UseDefaultCredentials = true;
                NetworkCredential networkCredential = CredentialCache.DefaultNetworkCredentials;
                client.Credentials = networkCredential.GetCredential(host, port, "Basic");

                client.SendAsync(message, "Send completed!");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 13
0
        public ZloCancelOrdersResponse ZloCancelOrders([System.Xml.Serialization.XmlElementAttribute("ZloCancelOrders", Namespace = "urn:sap-com:document:sap:soap:functions:mc-style")] ZloCancelOrders.ZloCancelOrders ZloCancelOrders1)
        {
            try
            {
                var settings = new SettingsService(SPContext.Current.Web);

                if (settings.SapCancelUrl == null)
                {
                    throw new NullReferenceException("Settings SAP-CANCEL-REQUEST is null");
                }
                if (settings.SapLogin == null)
                {
                    throw new NullReferenceException("Settings SAP-LOGIN is null");
                }
                if (settings.SapPass == null)
                {
                    throw new NullReferenceException("Settings SAP-PASS is null");
                }

                X5PackingLoggingService.LogInfo($"ZloCancelOrdersWs.ZloCancelOrders send to SAP with {settings.SapCancelUrl}");

                var netCredential = new NetworkCredential(settings.SapLogin, settings.SapPass);
                var uri           = new Uri(settings.SapCancelUrl);
                var credentials   = netCredential.GetCredential(uri, "Basic");

                var client = new ZloCancelOrdersClient
                {
                    Url             = settings.SapCancelUrl,
                    Credentials     = credentials,
                    PreAuthenticate = true
                    #if DEBUG
                    , Proxy = new WebProxy()
                    {
                        Address = new Uri("http://localhost:8888")
                    }
                    #endif
                };
                var xmlSerializerRequest = new XmlSerializer(ZloCancelOrders1.GetType());
                using (var textWriter = new StringWriter())
                {
                    xmlSerializerRequest.Serialize(textWriter, ZloCancelOrders1);
                    X5PackingLoggingService.LogInfo(textWriter.ToString());
                }
                var response = client.ZloCancelOrders(ZloCancelOrders1);
                var xmlSerializerResponse = new XmlSerializer(response.GetType());
                using (var textWriter = new StringWriter())
                {
                    xmlSerializerResponse.Serialize(textWriter, response);
                    X5PackingLoggingService.LogInfo(textWriter.ToString());
                }
                X5PackingLoggingService.LogInfo($"ZloCancelOrdersWs.ZloCancelOrders received from SAP with {settings.SapCancelUrl}");
                return(response);
            }
            catch (Exception e)
            {
                X5PackingLoggingService.LogError(e);
                throw;
            }
        }
Exemplo n.º 14
0
        public void SendEmail(string subject, string body, string emailFrom, string emailSender, string emailTo,
                              string[] copySomeoneEmai, bool isHtmlFormat, MailPriority priority, List <string> fileUrls)
        {
            if (!ValidateEmailClientParam())
            {
                return;
            }
            //验证邮件数据是否符合要求

            SmtpClient client = new SmtpClient()
            {
                Host = EmailClient
            };

            if (EmailClientPort.HasValue)
            {
                client.Port = EmailClientPort.Value;
            }
            client.EnableSsl = EnableSsl;
            // client.UseDefaultCredentials = false;
            try
            {
                if (!MailEnablePswAuthentication)
                {
                    NetworkCredential nc = new NetworkCredential(EmailId, EmailKey);
                    client.Credentials = nc.GetCredential(client.Host, client.Port, "NTLM");
                }
                else
                {
                    client.Credentials = new NetworkCredential(EmailId, EmailKey);
                } //  client.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailMessage mail = new MailMessage();
                mail.From   = new MailAddress(emailFrom);//发信人地址
                mail.Sender = new MailAddress(emailSender);//发件人地址
                mail.To.Add(emailTo);
                mail.Subject = subject;
                StringBuilder sb = new StringBuilder();
                if (!string.IsNullOrEmpty(BodyHeadText))
                {
                    sb.AppendLine(BodyHeadText);
                }
                sb.AppendLine(body);
                if (!string.IsNullOrEmpty(BodyFeetText))
                {
                    sb.AppendLine(BodyFeetText);
                }
                mail.Body         = sb.ToString();
                mail.IsBodyHtml   = isHtmlFormat;
                mail.BodyEncoding = Encoding.UTF8;
                mail.Priority     = priority;
                PreperAttachFile(fileUrls, ref mail);
                client.Send(mail);
                mail.Dispose();
            }
            catch (Exception ex)
            {
                ex.AppendLog((new StringBuilder()).AppendLine(ex.ToString()).ToString(), (new CommonFormat()).DateToHourIntFormatString + FileSuffix.Log, LogPath);
            }
        }
Exemplo n.º 15
0
/**
 * Method to return credentials.
 **/
    public ICredentials getCredentials(string url)
    {
        // Set up some credentials
        var          netCredential = new NetworkCredential(apiuser, apikey);
        var          uri           = new Uri(url);
        ICredentials credentials   = netCredential.GetCredential(uri, "Basic");

        return(credentials);
    }
Exemplo n.º 16
0
        /// <summary>
        ///  邮件的发送
        /// </summary>
        /// <param name="toMail">收件人地址(可以是多个收件人,程序中是以“;"进行区分的)</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="emailBody">邮件内容(可以以html格式进行设计)</param>
        /// <param name="attachments"></param>
        public static void Send(string toMail, string subject, string emailBody, List <Stream> attachments = null)
        {
            var maillAddress = AppConfig.DllConfigs.Current["Mail"]["MailAddress"];

            var message = new MailMessage
            {
                IsBodyHtml   = true,
                BodyEncoding = Encoding.UTF8,
                Priority     = MailPriority.Normal,
                Subject      = subject,
                Body         = emailBody
            };

            var fromMailAddress = new MailAddress(maillAddress, "中估联信息技术有限公司");

            message.From = fromMailAddress;

            var toMails = toMail.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var toMailAddress in toMails)
            {
                message.To.Add(toMailAddress);
            }

            if (attachments != null && attachments.Count != 0)
            {
                attachments.ForEach(item =>
                {
                    var attachment = new Attachment(item, MediaTypeNames.Application.Octet);
                    //var disposition = attachment.ContentDisposition;
                    //disposition.CreationDate = File.GetCreationTime(path[i]);
                    //disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                    //disposition.ReadDate = File.GetLastAccessTime(path[i]);
                    message.Attachments.Add(attachment);
                });
            }
            var mSmtpClient = new SmtpClient()
            {
                Host = AppConfig.DllConfigs.Current["Mail"]["Host"],
                Port = Convert.ToInt32(AppConfig.DllConfigs.Current["Mail"]["Port"]),
                UseDefaultCredentials = true,
                EnableSsl             = Convert.ToBoolean(AppConfig.DllConfigs.Current["Mail"]["EnableSsl"]),
            };

            if (Convert.ToBoolean(AppConfig.DllConfigs.Current["Mail"]["EnableAuthentication"]))
            {
                NetworkCredential nc = new NetworkCredential(AppConfig.DllConfigs.Current["Mail"]["UserName"], AppConfig.DllConfigs.Current["Mail"]["Password"]);
                mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
            }
            else
            {
                mSmtpClient.Credentials = new NetworkCredential(AppConfig.DllConfigs.Current["Mail"]["UserName"], AppConfig.DllConfigs.Current["Mail"]["Password"]);
            }
            mSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mSmtpClient.Send(message);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Create the network credentials and assign
        /// them to the service credentials
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void SetCredentials(string username, string password)
        {
            var nc          = new NetworkCredential(username, password);
            var uri         = new Uri(Url);
            var credentials = nc.GetCredential(uri, "Basic");

            Credentials = credentials;
            // Be sure to set PreAuthenticate to true or else authentication will not be sent.
            PreAuthenticate = true;
        }
        public static void SetCredential(this SoapHttpClientProtocol clientProtocol, string userName, string password, string url, string authenticationType = "Basic")
        {
            var nc  = new NetworkCredential(userName, password);
            var uri = new Uri(url);

            ICredentials credentials = nc.GetCredential(uri, authenticationType);

            clientProtocol.Credentials     = credentials;
            clientProtocol.PreAuthenticate = true;

            clientProtocol.Url = url;
        }
Exemplo n.º 19
0
        private SmtpClient CreateClient()
        {
            SmtpClient        client = new SmtpClient();
            NetworkCredential nc     = CredentialCache.DefaultNetworkCredentials;

            client.Host = _config.GetValue <string>("Email:Smtp:Host");
            client.Port = _config.GetValue <int>("Email:Smtp:Port");
            client.UseDefaultCredentials = true;
            client.Credentials           = (System.Net.ICredentialsByHost)nc.GetCredential(
                _config.GetValue <String>("Email:Smtp:Host"),
                _config.GetValue <int>("Email:Smtp:Port"),
                "Basic");
            return(client);
        }
Exemplo n.º 20
0
        public ProxyBuilder(ConnectionModel model)
        {
            var cred = CredentialCache.DefaultCredentials;

            if (!String.IsNullOrEmpty(model.Password))
            {
                cred      = new NetworkCredential(model.UserName, model.Password);
                discovery = new Discovery(model.Uri, cred.GetCredential(new Uri(model.Uri), "Basic"), true);
            }
            else
            {
                discovery = new Discovery(model.Uri, CredentialCache.DefaultCredentials, false);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Gets the authorise service. Loads a XML configuration file, creates a
        /// Basic Auth credentioals object and applies to the Service we want to use
        /// </summary>
        /// <returns>The authorise service.</returns>
        static AddressingService GetAuthoriseService()
        {
            // Set up some credentials
            NetworkCredential netCredential = new NetworkCredential(apiuser, apikey);
            // Create the service of type Addressing service
            AddressingService Service = new AddressingService(apiendpoint);

            Service.RequestEncoding = System.Text.Encoding.UTF8;
            Uri          uri         = new Uri(Service.Url);
            ICredentials credentials = netCredential.GetCredential(uri, "Basic");

            // Apply the credentials to the service
            Service.Credentials = credentials;
            return(Service);
        }
Exemplo n.º 22
0
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Form["javascript-enabled"] != "true")
        {
            context.Response.Redirect(HttpStatusCode.Found, "http://spammerbegone.com");
        }
        else
        {
            using (MailMessage message = new MailMessage())
                using (SmtpClient smtp = new SmtpClient())
                {
                    string smtpHost     = WebConfigurationManager.AppSettings["Smtp:Host"];
                    int    smtpPort     = Convert.ToInt32(WebConfigurationManager.AppSettings["Smtp:Port"]);
                    string smtpUsername = WebConfigurationManager.AppSettings["Smtp:Username"];
                    string smtpPassword = WebConfigurationManager.AppSettings["Smtp:Password"];

                    var creds = new NetworkCredential(smtpUsername, smtpPassword);
                    var auth  = creds.GetCredential(smtpHost, smtpPort, "Basic");

                    smtp.Host        = smtpHost;
                    smtp.Port        = smtpPort;
                    smtp.Credentials = auth;

                    string contactName  = context.Request.Form["contact-name"];
                    string contactEmail = context.Request.Form["contact-email"];

                    message.To.Add(new MailAddress(WebConfigurationManager.AppSettings["InfoEmail"], "Managed Fusion"));
                    message.To.Add(new MailAddress(contactEmail, contactName));
                    message.From    = new MailAddress(WebConfigurationManager.AppSettings["NoReplyEmail"], "Managed Fusion No Reply");
                    message.ReplyTo = new MailAddress(contactEmail, contactName);

                    message.Subject    = "Web Site Information Request";
                    message.IsBodyHtml = false;
                    message.Body       = "sent-at:" + Environment.NewLine + DateTime.Now.ToString("F") + Environment.NewLine + Environment.NewLine;
                    message.Body      += "sent-from:" + Environment.NewLine + "managedfusion.com" + Environment.NewLine + Environment.NewLine;

                    foreach (string id in context.Request.Form.AllKeys)
                    {
                        message.Body += id + ":" + Environment.NewLine + context.Request.Form[id] + Environment.NewLine + Environment.NewLine;
                    }

                    smtp.Send(message);
                }

            // redirect to form
            context.Response.Redirect(HttpStatusCode.SeeOther, "/thank-you.aspx");
        }
    }
Exemplo n.º 23
0
        public static string Disconnect(string ip, string user, string pwd)
        {
            try
            {
                string            url     = "断 线";
                string            uri     = "http://" + ip + "/userRpm/StatusRpm.htm?Disconnect=" + System.Web.HttpUtility.UrlEncode(url, System.Text.Encoding.GetEncoding("gb2312")) + "&wan=1";
                string            sUser   = user;
                string            sPwd    = pwd;
                string            sDomain = "";
                NetworkCredential oCredential;
                HttpWebRequest    oRequest = (System.Net.HttpWebRequest)WebRequest.Create(uri);
                if (oRequest != null)
                {
                    oRequest.ProtocolVersion = HttpVersion.Version11;// send request
                    oRequest.Method          = "GET";
                    oRequest.ContentType     = "application/x-www-form-urlencoded";
                    oRequest.UserAgent       = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6.4; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                    oRequest.Referer         = ip;

                    if (sUser != String.Empty)
                    {
                        oCredential          = new NetworkCredential(sUser, sPwd, sDomain);
                        oRequest.Credentials = oCredential.GetCredential(new Uri(uri), String.Empty);
                    }
                    else
                    {
                        oRequest.Credentials = CredentialCache.DefaultCredentials;
                    }
                    StreamReader sr   = new StreamReader(oRequest.GetResponse().GetResponseStream(), System.Text.Encoding.Default);
                    string       line = sr.ReadToEnd();
                    sr.Close();
                    if (line.IndexOf("LAN口状态") > -1)//登录成功
                    {
                        return("success");
                    }
                    else
                    {
                        return("fail");
                    }
                }
            }catch (Exception ex)
            {
                return("fial:" + ex.Message);
            }
            return("fail");
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the authorise service. Loads a XML configuration file, creates a
        /// Basic Auth credentials object and applies to the Service we want to use
        /// </summary>
        /// <returns>The authorise service.</returns>
        private static ShippingService GetAuthoriseService()
        {
            // Set up some credentials
            NetworkCredential netCredential = new NetworkCredential(apiuser, apikey);

            // Create the service of type Shipping service
            Service = new ShippingService
            {
                RequestEncoding = System.Text.Encoding.UTF8
            };
            Uri          uri         = new Uri(Service.Url);
            ICredentials credentials = netCredential.GetCredential(uri, "Basic");

            // Apply the credentials to the service
            Service.Credentials = credentials;
            return(Service);
        }
Exemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(x => x
                                                .UseSqlServer(Configuration.GetConnectionString("LostZoneLocal"))
                                                .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));

            services.Configure <IISOptions>(options => { options.AutomaticAuthentication = true; });
            services.Configure <ShaderOptions>(Configuration);
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireUser", policy => policy.RequireRole("admin", "riskCoordinator", "riskManager", "user"));
                options.AddPolicy("RequireCoordinator", policy => policy.RequireRole("admin", "riskCoordinator", "riskManager"));
                options.AddPolicy("RequireRM", policy => policy.RequireRole("admin", "riskManager"));
                options.AddPolicy("RequireSecurity", policy => policy.RequireRole("admin", "security"));
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("admin"));
            });
            services.AddMvc().AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                // надо бы разобраться в этом: =>
                opt.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            });
            services.AddScoped <IClaimsTransformation, ClaimsTransformer>();
            //services.AddScoped<IUserService, UserService>();
            services.AddSingleton <IUserService, UserService>();
            services.AddScoped <IMailService, MailService>();
            services.AddCors();
            services.AddScoped <SmtpClient>((serviceProvider) =>
            {
                var config           = serviceProvider.GetRequiredService <IConfiguration>();
                NetworkCredential nc = CredentialCache.DefaultNetworkCredentials;
                return(new SmtpClient()
                {
                    Host = config.GetValue <String>("Email:Smtp:Host"),
                    Port = config.GetValue <int>("Email:Smtp:Port"),
                    UseDefaultCredentials = true,
                    Credentials = (System.Net.ICredentialsByHost)nc.GetCredential(
                        config.GetValue <String>("Email:Smtp:Host"),
                        config.GetValue <int>("Email:Smtp:Port"),
                        "Basic")
                });
            });
            services.AddAutoMapper(typeof(Startup));
            services.AddTransient <Seed>();
        }
Exemplo n.º 26
0
        public static void SetNetworkCredentials(
            this WebClientProtocol client,
            string userName,
            string password,
            Uri customUrl = null)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            client.PreAuthenticate = true;

            var          uri           = customUrl == null ? new Uri(client.Url) : customUrl;
            var          netCredential = new NetworkCredential(userName, password);
            ICredentials credentials   = netCredential.GetCredential(uri, "Basic");

            client.Credentials = credentials;
        }
Exemplo n.º 27
0
        private void login()
        {
            if (!txtUserID.Text.Equals("") && !txtPassword.Text.Equals(""))
            {
                //MD5
                string pws = STL.PDA.Util.common.EncryptMD5(txtPassword.Text);

                try
                {
                    UserLogin.SI_MM028_PDA2SAP_LOGIN_OUTService svc = new UserLogin.SI_MM028_PDA2SAP_LOGIN_OUTService();;
                    svc.Url         = WebServiceInstants.GetURL(ServiceType.LoginURL);
                    svc.Credentials = nc.GetCredential(new Uri(svc.Url), "Basic");
                    UserLogin.ZFIS_PDA_LOGIN_REQ login_req = new STL.PDA.UserLogin.ZFIS_PDA_LOGIN_REQ();
                    login_req.ZDATA          = new STL.PDA.UserLogin.ZFIS_PDA_LOGIN_REQDATA();
                    login_req.ZDATA.PASSWORD = pws;
                    login_req.ZDATA.USERID   = txtUserID.Text;
                    UserLogin.ZFIS_PDA_LOGIN_RES login_res = svc.SI_MM028_PDA2SAP_LOGIN_OUT(login_req);
                    if (login_res.IF_STATU.Equals("01"))
                    {
                        MainForm mfm = new MainForm();
                        mfm.Show();
                        this.Hide();
                        SaveToConfig();
                    }
                    else
                    {
                        MessageBox.Show(login_res.IFMSG, "登陆失败");
                    }
                }
                catch (WebException ex)
                {
                    MessageBox.Show(ex.Status + ";" + ex.Response);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Please enter User Name and password.");
            }
        }
Exemplo n.º 28
0
	public void ProcessRequest(HttpContext context)
	{
		if (context.Request.Form["javascript-enabled"] != "true")
			context.Response.Redirect(HttpStatusCode.Found, "http://spammerbegone.com");
		else {
			using (MailMessage message = new MailMessage())
			using (SmtpClient smtp = new SmtpClient())
			{
				string smtpHost = WebConfigurationManager.AppSettings["Smtp:Host"];
				int smtpPort = Convert.ToInt32(WebConfigurationManager.AppSettings["Smtp:Port"]);
				string smtpUsername = WebConfigurationManager.AppSettings["Smtp:Username"];
				string smtpPassword = WebConfigurationManager.AppSettings["Smtp:Password"];
			
				var creds = new NetworkCredential(smtpUsername, smtpPassword);
				var auth = creds.GetCredential(smtpHost, smtpPort, "Basic");
			
				smtp.Host = smtpHost;
				smtp.Port = smtpPort;
				smtp.Credentials = auth;
			
				string contactName = context.Request.Form["contact-name"];
				string contactEmail = context.Request.Form["contact-email"];
				
				message.To.Add(new MailAddress(WebConfigurationManager.AppSettings["InfoEmail"], "Managed Fusion"));
				message.To.Add(new MailAddress(contactEmail, contactName));
				message.From = new MailAddress(WebConfigurationManager.AppSettings["NoReplyEmail"], "Managed Fusion No Reply");
				message.ReplyTo = new MailAddress(contactEmail, contactName);

				message.Subject = "Web Site Information Request";
				message.IsBodyHtml = false;
				message.Body = "sent-at:" + Environment.NewLine + DateTime.Now.ToString("F") + Environment.NewLine + Environment.NewLine;
				message.Body += "sent-from:" + Environment.NewLine + "managedfusion.com" + Environment.NewLine + Environment.NewLine;

				foreach (string id in context.Request.Form.AllKeys)
					message.Body += id + ":" + Environment.NewLine + context.Request.Form[id] + Environment.NewLine + Environment.NewLine;
					
				smtp.Send(message);
			}

			// redirect to form
			context.Response.Redirect(HttpStatusCode.SeeOther, "/thank-you.aspx");
		}
	}
Exemplo n.º 29
0
    public void ProcessRequest(HttpContext context)
    {
        using (MailMessage message = new MailMessage())
            using (SmtpClient smtp = new SmtpClient())
            {
                string smtpHost     = WebConfigurationManager.AppSettings["Smtp:Host"];
                int    smtpPort     = Convert.ToInt32(WebConfigurationManager.AppSettings["Smtp:Port"]);
                string smtpUsername = WebConfigurationManager.AppSettings["Smtp:Username"];
                string smtpPassword = WebConfigurationManager.AppSettings["Smtp:Password"];

                var creds = new NetworkCredential(smtpUsername, smtpPassword);
                var auth  = creds.GetCredential(smtpHost, smtpPort, "Basic");

                smtp.Host        = smtpHost;
                smtp.Port        = smtpPort;
                smtp.Credentials = auth;

                string contactName  = context.Request.Form["contact-name"];
                string contactEmail = context.Request.Form["contact-email"];

                message.To.Add(new MailAddress(WebConfigurationManager.AppSettings["InfoEmail"], "Berardi's Detailing"));
                message.To.Add(new MailAddress(contactEmail, contactName));
                message.From    = new MailAddress(WebConfigurationManager.AppSettings["NoReplyEmail"], "Berardi's Detailing No Reply");
                message.ReplyTo = new MailAddress(contactEmail, contactName);

                message.Subject    = "Web Site Information Request";
                message.IsBodyHtml = false;
                message.Body       = "sent-at:" + Environment.NewLine + DateTime.Now.ToString("F") + Environment.NewLine + Environment.NewLine;
                message.Body      += "sent-from:" + Environment.NewLine + "berardisdetailing.com" + Environment.NewLine + Environment.NewLine;

                foreach (string id in context.Request.Form.AllKeys)
                {
                    message.Body += id + ":" + Environment.NewLine + context.Request.Form[id] + Environment.NewLine + Environment.NewLine;
                }

                smtp.Send(message);
            }

        // redirect to form
        context.Response.Redirect("/thank-you.html");
    }
Exemplo n.º 30
0
        public Task <HttpResponseMessage> PostAsync(Uri target, string postContent, string contentType)
        {
            const string UserAgent      = "user-agent";
            const string UserAgentValue = "EveHQ v{0}";

            if (target != null)
            {
                var handler = new HttpClientHandler();

                // This is never null
                if (_proxyInfo != null && _proxyInfo.ProxyServerAddress != null)
                {
                    // set proxy if required.
                    var proxy = new WebProxy(_proxyInfo.ProxyServerAddress);
                    if (_proxyInfo.UseDefaultCredential)
                    {
                        proxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        var credential = new NetworkCredential(_proxyInfo.ProxyUserName, _proxyInfo.ProxyPassword);
                        proxy.Credentials = _proxyInfo.UseBasicAuth ? credential.GetCredential(_proxyInfo.ProxyServerAddress, "Basic") : credential;
                    }

                    handler.Proxy    = proxy;
                    handler.UseProxy = true;
                }

                handler.AutomaticDecompression = DecompressionMethods.GZip;
                handler.AllowAutoRedirect      = true;

                var requestClient = new HttpClient(handler);
                requestClient.DefaultRequestHeaders.Add(UserAgent, UserAgentValue.FormatInvariant(Version));

                HttpContent content = !postContent.IsNullOrWhiteSpace() ? new StringContent(postContent, Encoding.UTF8, contentType) : null;

                return(requestClient.PostAsync(target, content));
            }

            return(Task <HttpResponseMessage> .Factory.StartNew(() => null));
        }
Exemplo n.º 31
0
        public Task <HttpResponseMessage> GetAsync(Uri target, string acceptContentType, HttpCompletionOption completionOption)
        {
            if (target != null)
            {
                var handler = new HttpClientHandler();

                if (_proxyInfo != null && _proxyInfo.ProxyServerAddress != null)
                {
                    // set proxy if required.
                    var proxy = new WebProxy(_proxyInfo.ProxyServerAddress);
                    if (_proxyInfo.UseDefaultCredential)
                    {
                        proxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        var credential = new NetworkCredential(_proxyInfo.ProxyUserName, _proxyInfo.ProxyPassword);
                        proxy.Credentials = _proxyInfo.UseBasicAuth ? credential.GetCredential(_proxyInfo.ProxyServerAddress, "Basic") : credential;
                    }

                    handler.Proxy    = proxy;
                    handler.UseProxy = true;
                }

                handler.AutomaticDecompression = DecompressionMethods.GZip;
                handler.AllowAutoRedirect      = true;

                var request = new HttpClient(handler);
                request.DefaultRequestHeaders.Add("User-Agent", "EveHQ");

                if (!acceptContentType.IsNullOrWhiteSpace())
                {
                    request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptContentType));
                }

                return(request.GetAsync(target, completionOption));
            }

            return(Task <HttpResponseMessage> .Factory.StartNew(() => null));
        }
	public void ProcessRequest(HttpContext context)
	{
		using (MailMessage message = new MailMessage())
		using (SmtpClient smtp = new SmtpClient())
		{
			string smtpHost = WebConfigurationManager.AppSettings["Smtp:Host"];
			int smtpPort = Convert.ToInt32(WebConfigurationManager.AppSettings["Smtp:Port"]);
			string smtpUsername = WebConfigurationManager.AppSettings["Smtp:Username"];
			string smtpPassword = WebConfigurationManager.AppSettings["Smtp:Password"];
		
			var creds = new NetworkCredential(smtpUsername, smtpPassword);
			var auth = creds.GetCredential(smtpHost, smtpPort, "Basic");
		
			smtp.Host = smtpHost;
			smtp.Port = smtpPort;
			smtp.Credentials = auth;
		
			string contactName = context.Request.Form["contact-name"];
			string contactEmail = context.Request.Form["contact-email"];

			message.To.Add(new MailAddress(WebConfigurationManager.AppSettings["InfoEmail"], "Berardi's Detailing"));
			message.To.Add(new MailAddress(contactEmail, contactName));
			message.From = new MailAddress(WebConfigurationManager.AppSettings["NoReplyEmail"], "Berardi's Detailing No Reply");
			message.ReplyTo = new MailAddress(contactEmail, contactName);

			message.Subject = "Web Site Information Request";
			message.IsBodyHtml = false;
			message.Body = "sent-at:" + Environment.NewLine + DateTime.Now.ToString("F") + Environment.NewLine + Environment.NewLine;
			message.Body += "sent-from:" + Environment.NewLine + "berardisdetailing.com" + Environment.NewLine + Environment.NewLine;

			foreach (string id in context.Request.Form.AllKeys)
				message.Body += id + ":" + Environment.NewLine + context.Request.Form[id] + Environment.NewLine + Environment.NewLine;

			smtp.Send(message);
		}

		// redirect to form
		context.Response.Redirect("/thank-you.html");
	}
Exemplo n.º 33
0
        public static void GetCredential_HostPortAuthenticationType_Success()
        {
            NetworkCredential nc = new NetworkCredential();

            Assert.Equal(nc, nc.GetCredential("host", 500, "authenticationType"));
        }
Exemplo n.º 34
0
        public static void GetCredential_UriAuthenticationType_Success()
        {
            NetworkCredential nc = new NetworkCredential();

            Assert.Equal(nc, nc.GetCredential(new Uri("http://microsoft.com"), "authenticationType"));
        }
Exemplo n.º 35
0
	public HttpWebResponse Submit (Uri uri, FSpot.ProgressItem progress_item) 
	{
		this.Progress = progress_item;
		Request = (HttpWebRequest) WebRequest.Create (uri);
		CookieCollection cookie_collection = Cookies.GetCookies (uri);

		if (uri.UserInfo != null && uri.UserInfo != String.Empty) {
			NetworkCredential cred = new NetworkCredential ();
			cred.GetCredential (uri, "basic");
			CredentialCache credcache = new CredentialCache();
			credcache.Add(uri, "basic", cred);
			
			Request.PreAuthenticate = true;
			Request.Credentials = credcache;	
		}

		Request.ServicePoint.Expect100Continue = expect_continue;

		Request.CookieContainer = new CookieContainer ();
		foreach (Cookie c in cookie_collection) {
			if (SuppressCookiePath) 
				Request.CookieContainer.Add (new Cookie (c.Name, c.Value));
			else
				Request.CookieContainer.Add (c);
		}

		Request.Method = "POST";
		Request.Headers["Accept-Charset"] = "utf-8;";
		
		//Request.UserAgent = "F-Spot Gallery Remote Client";
		Request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040626 Firefox/0.9.1";

		Request.Proxy = WebProxy.GetDefaultProxy ();

		if (multipart) {
			GenerateBoundary ();
			Request.ContentType = "multipart/form-data; boundary=" + boundary;
			Request.Timeout = Request.Timeout * 3;

			long length = 0;
			for (int i = 0; i < Items.Count; i++) {
				FormItem item = (FormItem)Items[i];
				
				length += MultipartLength (item);
			}
			length += end_boundary.Length + 2;
			
			//Request.Headers["My-Content-Length"] = length.ToString ();
			if (Buffer == false) {
				Request.ContentLength = length;	
				Request.AllowWriteStreamBuffering = false;
			}
		} else {
			Request.ContentType = "application/x-www-form-urlencoded";
		}
		
		stream_writer = new StreamWriter (Request.GetRequestStream ());
		
		first_item = true;
		for (int i = 0; i < Items.Count; i++) {
			FormItem item = (FormItem)Items[i];
			
			Write (item);
		}
		
		if (multipart)
			stream_writer.Write (end_boundary + "\r\n");
		
		stream_writer.Flush ();
		stream_writer.Close ();

		HttpWebResponse response; 

		try {
			response = (HttpWebResponse) Request.GetResponse ();
			
			//Console.WriteLine ("found {0} cookies", response.Cookies.Count);
			
			foreach (Cookie c in response.Cookies) {
				Cookies.Add (c);
			}
		} catch (WebException e) {
			if (e.Status == WebExceptionStatus.ProtocolError 
			    && ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.ExpectationFailed && expect_continue) {
				e.Response.Close ();
				expect_continue = false;
				return Submit (uri, progress_item);
			}
			
			throw new WebException (Mono.Unix.Catalog.GetString ("Unhandled exception"), e);
		}

		return response;
	}