示例#1
0
文件: SendMail.cs 项目: samercs/NCSS
    public void SendMailList(string to1, string subject, string body, string filename)
    {
        try
        {

            System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
            eMail.IsBodyHtml = true;
            eMail.Body = body;
            eMail.From = new System.Net.Mail.MailAddress("*****@*****.**", "مسابقة اصغر رجل اعمال-القائمة البريدية");
            eMail.To.Add(to1);
            eMail.Subject = subject;
            eMail.Priority = MailPriority.High;
            Attachment attach = new Attachment(filename);
            eMail.Attachments.Add(attach);

            System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
            NetworkCredential Xcred = new NetworkCredential("samercs", "samer2006");
            SMTP.Credentials = Xcred;
            SMTP.Send(eMail);

        }
        catch (System.Exception e)
        {
            /*Database db = new Database();
            db.AddParameter("@msgfrom", "*****@*****.**");
            db.AddParameter("@msgto", to1);
            db.AddParameter("@subject", subject);
            db.AddParameter("@body", body);
            db.AddParameter("@ErrorMsg", e.Message);
            db.ExecuteNonQuery("Insert Into mailError(msgfrom,msgto,subject,body,ErrorMsg) values(@msgfrom,@msgto,@subject,@body,@ErrorMsg)");
             */
        }
    }
示例#2
0
        public static void Password_GetSet_Success()
        {
            NetworkCredential nc = new NetworkCredential();

            nc.Password = "******";
            Assert.Equal("password", nc.Password);
        }
示例#3
0
 public static void Ctor_Empty_Success()
 {
     NetworkCredential nc = new NetworkCredential();
     Assert.Equal(String.Empty, nc.UserName);
     Assert.Equal(String.Empty, nc.Password);
     Assert.Equal(String.Empty, nc.Domain);
 }
    protected void Button1_Click(object sender, EventArgs e)
    {
        locator.locate find = new locator.locate();
          String j = bgroup.Text;
         String[] emailList= find.mailing(j);
         // string a = group.Text;
        //   a = a + ", [email protected],[email protected]";

        //List<String> emailList=null;
        //emailList.
           string a="";
           foreach(String eachItem in emailList){
           a = eachItem+", "+a;
           }
           a = a.Substring(0, a.Length - 2);
        string b = body.Text;
        MailMessage MyMailMessage = new MailMessage("*****@*****.**", a,"Donor Notifications", b);
        MyMailMessage.IsBodyHtml = false;
        NetworkCredential mailAuthentication = new NetworkCredential("*****@*****.**", "giveblood");
        SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
        mailClient.EnableSsl = true;
        mailClient.UseDefaultCredentials = false;
        mailClient.Credentials = mailAuthentication;
        mailClient.Send(MyMailMessage);
        Label1.Text = "Sent Notifications Successfully";
    }
示例#5
0
 public static void Ctor_UserNamePasswordDomain_Success()
 {
     NetworkCredential nc = new NetworkCredential("username", "password", "domain");
     Assert.Equal("username", nc.UserName);
     Assert.Equal("password", nc.Password);
     Assert.Equal("domain", nc.Domain);
 }
示例#6
0
    public static void Send(string to, string title, string body)
    {
        MailMessage mail = new MailMessage();

        MailAddress address = new MailAddress(to);

        MailAddress FromAddress = new MailAddress("*****@*****.**", "vbn");

        mail.From = FromAddress;

        mail.To.Add(address);

        mail.Body = body;

        mail.Subject = title;

        mail.BodyEncoding = Encoding.UTF8;

        SmtpClient SendMail = new SmtpClient();

        NetworkCredential Authentication = new NetworkCredential();

        Authentication.UserName = "******";

        Authentication.Password = "******";

        SendMail.Credentials = Authentication;

        SendMail.Host = "mail.vbn.vn";

        SendMail.Port = 25;

        SendMail.Send(mail);
    }
        public void ProxyExplicitlyProvided_DefaultCredentials_Ignored()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            var rightCreds = new NetworkCredential("rightusername", "rightpassword");
            var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");

            using (var handler = new HttpClientHandler())
            using (var client = new HttpClient(handler))
            {
                handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
                handler.DefaultProxyCredentials = wrongCreds;

                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
示例#8
0
    public void sendEmail(String aemailaddress, String asubject, String abody)
    {
        try
        {
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            MailAddress from = new MailAddress("*****@*****.**", "123");
            MailAddress to = new MailAddress(aemailaddress, "Sas");
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent using gmail as a relay server ";
            message.Subject = "Gmail test email with SSL and Credentials";
            NetworkCredential myCreds = new NetworkCredential("*****@*****.**", "", "");
            client.Credentials = myCreds;

            client.Send(message);
            Label1.Text = "Mail Delivery Successful";
        }
        catch (Exception e)
        {
            Label1.Text = "Mail Delivery Unsucessful";
        }
        finally
        {
            txtUserID.Text = "";
            txtQuery.Text = "";
        }
    }
    public static bool SendMail(string gMailAccount, string password, string to, string subject, string message)
    {
        try
        {
            NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(gMailAccount);
            msg.To.Add(new MailAddress(to));
            msg.Subject = subject;
            msg.Body = message;
            msg.IsBodyHtml = true;
            SmtpClient client = new SmtpClient("smtp.gmail.com");
            client.Port = 587;
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = loginInfo;
            client.Send(msg);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
    /// <summary>
    /// Returns ICredential object for SharePoint authentication based on given username and password.
    /// </summary>
    public static ICredentials GetSharePointCredetials(string username, string password, bool base64)
    {
        ICredentials credentials = null;

        string pass = password;

        // If password is in base64 encoding, convert it back
        if (base64)
        {
            pass = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(pass));
        }

        // Handle username like DOMAIN\username
        int domainIndex = username.LastIndexOfCSafe("\\");
        if (domainIndex > 0)
        {
            string domain = username.Substring(0, domainIndex);
            string user = username.Substring(domainIndex + 1);

            credentials = new NetworkCredential(user, pass, domain);
        }
        else
        {
            credentials = new NetworkCredential(username, pass);
        }

        return credentials;
    }
示例#11
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage msg = new MailMessage();
        MailAddress mailadd = new MailAddress("*****@*****.**","Amita Shukla");
        msg.From = mailadd;
        msg.To.Add(new MailAddress(TextBox1.Text));
        msg.Subject = TextBox2.Text;
        msg.Body = TextBox4.Text;
        if (FileUpload1.HasFile)
        {
            msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        NetworkCredential nkc = new NetworkCredential("*****@*****.**", "*******");
        smtp.Credentials = nkc;
        smtp.EnableSsl = true;

        try
        {
            smtp.Send(msg);
            Label5.Text = "Email sent successfully";
        }
        catch(Exception ex)
        {
            Label5.Text = ex.Message;
        }
    }
    private void ListMessages()
    {
        lblMessage.ForeColor = Color.Green;
        lblMessage.Text = "";

        try
        {
            // initialize exchange client
            NetworkCredential credential = new NetworkCredential(txtUsername.Text, Session["Password"].ToString(), txtDomain.Text);
            Aspose.Email.Exchange.ExchangeWebServiceClient client = new Aspose.Email.Exchange.ExchangeWebServiceClient(txtHost.Text, credential);

            // get list of messages
            Aspose.Email.Exchange.ExchangeMailboxInfo exchangeMailboxInfo = client.GetMailboxInfo();
            Aspose.Email.Exchange.ExchangeMessageInfoCollection msgCollection = client.ListMessages(exchangeMailboxInfo.InboxUri);
            gvMessages.DataSource = msgCollection;
            gvMessages.DataBind();

            lblMessage.Text = "Successfully connected to Microsoft Exchange server.<br><hr>";
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
示例#13
0
        internal void ValidateCreateContext(
            string package,
            NetworkCredential credential,
            string servicePrincipalName,
            ExtendedProtectionPolicy policy,
            ProtectionLevel protectionLevel,
            TokenImpersonationLevel impersonationLevel)
        {
            if (policy != null)
            {
                // One of these must be set if EP is turned on
                if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null)
                {
                    throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy));
                }

                _extendedProtectionPolicy = policy;
            }
            else
            {
                _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
            }

            ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel);
        }
        internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
        {
            SafeSspiAuthDataHandle authData = null;
            try
            {
                Interop.SECURITY_STATUS result = Interop.SspiCli.SspiEncodeStringsAsAuthIdentity(
                    credential.UserName, credential.Domain,
                    credential.Password, out authData);

                if (result != Interop.SECURITY_STATUS.OK)
                {
                    if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}"));
                    throw new Win32Exception((int)result);
                }

                return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth,
                    package, (isServer ? Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND : Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND), ref authData);
            }
            finally
            {
                if (authData != null)
                {
                    authData.Dispose();
                }
            }
        }
示例#15
0
    void EmailNotification()
    {
        MailMessage mm = new MailMessage();
        mm.From = new MailAddress("*****@*****.**");
        mm.To.Add(txtEmail.Text.ToString());
        mm.Subject = "Feedback - Inquiry/Issue";
        string body = "Hello " + txtFirstName.Text.Trim() + ",";
        body += "<br /><br />Thank you for sending us a message";
        body += "<br /><br />we will get back to you shortly using the email " + txtEmail.Text.ToString();
        body += "<br /><br />Thanks";
        body += "<br /><br />";
        body += "<br /><br />Customer Care - Lifeline Ambulance Rescue Inc.,";
        mm.Body = body;
        mm.IsBodyHtml = true;

        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        NetworkCredential cred = new NetworkCredential("*****@*****.**", "swantonbomb");
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.Credentials = cred;
        client.Send(mm);
    }
    public static bool Sendmail(string from, string name, List<string> to, string subject, string body)
    {
        try
        {
            MailMessage msg = new MailMessage();
            SmtpClient sclient = new SmtpClient();
            NetworkCredential si = new NetworkCredential("*****@*****.**", "pradeep9412350241");
            sclient.UseDefaultCredentials = false;
            sclient.Credentials = si;
            //msg.Priority = MailPriority.Low;
            msg.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
            msg.From = new MailAddress(from, name);
            foreach (string s in to)
            {
                msg.To.Add(s);
            }
            msg.Subject = subject;
            msg.Body = body;
            msg.IsBodyHtml = true;
            sclient.EnableSsl = true;
            sclient.Port = 587;
            sclient.Host = "smtp.gmail.com";
            sclient.DeliveryMethod = SmtpDeliveryMethod.Network;
            sclient.Send(msg);

            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    public string EmailForActivationRegistry(string emailOfUser, MailMessage mail)
    {
        string status = "";

        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.EnableSsl = true;
        smtpClient.Port = 587;
        smtpClient.UseDefaultCredentials = true;
        NetworkCredential networkCred = new NetworkCredential("*****@*****.**", "ULatina506");
        smtpClient.Credentials = networkCred;

        try
        {
            smtpClient.Send(mail);
            status = "Enviado";
        }
        catch
        {
            status = "No Enviado";

        }

        return status;
    }
示例#18
0
        internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
        {
            if (isServer)
            {
                throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
            }

            bool isNtlm = string.Equals(package, NegotiationInfoClass.NTLM);

            if (isNtlm)
            {
                throw new PlatformNotSupportedException(SR.net_nego_ntlm_not_supported);
            }

            try
            {
                // Note: In client case, equivalent of default credentials is to use previous, cached Kerberos TGT to get service-specific ticket.
                return (string.IsNullOrEmpty(credential.UserName) || string.IsNullOrEmpty(credential.Password)) ?
                    new SafeFreeNegoCredentials(string.Empty, string.Empty, string.Empty) :
                    new SafeFreeNegoCredentials(credential.UserName, credential.Password, credential.Domain);
            }
            catch(Exception ex)
            {
                throw new Win32Exception(NTE_FAIL, ex.Message);
            }
        }
        [PlatformSpecific(PlatformID.AnyUnix)] // proxies set via the http_proxy environment variable are specific to Unix
        public void ProxySetViaEnvironmentVariable_DefaultCredentialsUsed()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);

            const string ExpectedUsername = "******";
            const string ExpectedPassword = "******";

            // libcurl will read a default proxy from the http_proxy environment variable.  Ensure that when it does,
            // our default proxy credentials are used.  To avoid messing up anything else in this process, we run the
            // test in another process.
            var psi = new ProcessStartInfo();
            psi.Environment.Add("http_proxy", $"http://localhost:{port}");
            RemoteInvoke(() =>
            {
                using (var handler = new HttpClientHandler())
                using (var client = new HttpClient(handler))
                {
                    var creds = new NetworkCredential(ExpectedUsername, ExpectedPassword);
                    handler.DefaultProxyCredentials = creds;

                    Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
                    Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                    Task.WaitAll(responseTask, responseStringTask);

                    TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                }
                return SuccessExitCode;
            }, new RemoteInvokeOptions { StartInfo = psi }).Dispose();

            Assert.Equal($"{ExpectedUsername}:{ExpectedPassword}", proxyTask.Result.AuthenticationHeaderValue);
        }
示例#20
0
文件: Mailmsg.cs 项目: peless/290513
    public static void Send(string Body,string subject, string Address)
    {
        try
        {

        SmtpClient smtpClient = new SmtpClient();
        NetworkCredential basicCredential = new NetworkCredential("nephromorsys", "Orr190557");
        MailMessage message = new MailMessage();
        MailAddress fromAddress = new MailAddress("*****@*****.**");

        //smtpClient.Credentials = new NetworkCredential("nephromorsys", "Orr190557");
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;

        message.From = fromAddress;
        message.Subject = subject;
        //Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "<h1> " + Body +"</h1>";
        message.To.Add(Address);
        //message.To.Add("*****@*****.**");
        //message.To.Add("*****@*****.**");

            smtpClient.Send(message);
        }
        catch (Exception ex)
        {
            //Error, could not send the message
            //Response.Write(ex.Message);
            throw ex;
        }
    }
示例#21
0
        internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
        {
            if (isServer)
            {
                throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
            }

            bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) ||
                                     string.IsNullOrWhiteSpace(credential.Password);
            bool ntlmOnly = string.Equals(package, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase);
            if (ntlmOnly && isEmptyCredential)
            {
                // NTLM authentication is not possible with default credentials which are no-op 
                throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred);
            }

            try
            {
                return isEmptyCredential ?
                    new SafeFreeNegoCredentials(false, string.Empty, string.Empty, string.Empty) :
                    new SafeFreeNegoCredentials(ntlmOnly, credential.UserName, credential.Password, credential.Domain);
            }
            catch(Exception ex)
            {
                throw new Win32Exception(NTE_FAIL, ex.Message);
            }
        }
    protected void Submit_Click(object sender, EventArgs e)
    {
        MembershipUser membershipuser;
        MailMessage mailmessage;
        NetworkCredential networkcredential;
        SmtpClient smtpclient;

        if (ValidateInput())
        {
            membershipuser = Membership.GetUser(EmailAddress.Text);
            if (membershipuser != null)
            {
                mailmessage = new MailMessage(GlobalVariable.superadministratoremailaddress, EmailAddress.Text, "Email Subject", GlobalVariable.emailheadertemplate + "<p>Email Body</p><p>Reset Password Link : <a href=\"" + Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl("~/resetpassword.aspx?operation=resetpassword&username="******"\">Reset Password</a></p>" + GlobalVariable.emailfootertemplate);
                mailmessage.IsBodyHtml = true;
                networkcredential = new NetworkCredential(GlobalVariable.superadministratoremailaddress, GlobalVariable.superadministratoremailpassword);
                smtpclient = new SmtpClient("smtp.mail.yahoo.com", 587);
                smtpclient.UseDefaultCredentials = false;
                smtpclient.Credentials = networkcredential;
                smtpclient.Send(mailmessage);

                Response.Redirect("resetpassword.aspx?operation=resetpasswordinstruction");
            }
            else
            {
                EmailAddressError.Visible = true;
            }
        }
        else
        {

        }
    }
示例#23
0
	// Use this for initialization
	void Start () {
		PlaneXML = new PlaneXMLv1 ();
		c = new NetworkCredential("*****@*****.**", "B8955E7C-C03F-4CF9-9B8D-C38C50FDA67A");
		PlaneXML.Credentials = c;
		flight = PlaneXML.FlightInfo(flightID, true, true);
		StartCoroutine("refresh");
	}
示例#24
0
    public bool SendMail(ArrayList toAdresses)
    {
        SmtpClient smtpClient = new SmtpClient(adminMailServer, adminMailPort);

        NetworkCredential networkCredential = new NetworkCredential(adminMailAddress, adminMailPassword);

        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = networkCredential;

        MailMessage mail = new MailMessage();

        mail.From = new MailAddress(adminMailAddress, appName);

        for (int i = 0; i < (toAdresses.Count); i++)
        {
            mail.To.Add(new MailAddress(toAdresses[i].ToString()));
        }

        mail.Subject = appName + " - Mail Notification";
        mail.IsBodyHtml = true;
        mail.Body = MessageModifier();
        //mail.Priority = MailPriority.High;

        try
        {
            smtpClient.Send(mail);
            return true;
        }
        catch
        {
            return false;
        }
    }
    //Now in ppClass_sb.cs
    //get expired permits and reset spots to unoccupied
    //private void _resetSpots()
    //{
    //    //get expired spots
    //    var expiredSpots = objPark.getExpiredPermits(DateTime.Now);
    //    foreach (var spot in expiredSpots)
    //    {
    //       var spotSingle = objPark.getSpotBySpot(spot.spot);
    //    }
    //}
    //Send Email Receiptfd
    protected void sendReceipt(DateTime _timeExp, string _spot)
    {
        //This is the script provided by my hosting to send mail (Source URL: https://support.gearhost.com/KB/a777/aspnet-form-to-email-example.aspx?KBSearchID=41912)
        try
        {
            //Create the msg object to be sent
            MailMessage msg = new MailMessage();
            //Add your email address to the recipients
            msg.To.Add(txt_email.Text);
            //Configure the address we are sending the mail from
            MailAddress address = new MailAddress("*****@*****.**");
            msg.From = address;
            //Append their name in the beginning of the subject
            msg.Subject = "Your KDH Parking Reciept";
            msg.Body = "Thank you for parking with us. You are parked in " + _spot + " and your permit expires at " + _timeExp.ToString(@"hh\:mm\:ss") + ".";

            //Configure an SmtpClient to send the mail.
            SmtpClient client = new SmtpClient("mail.stevebosworth.ca");
            client.EnableSsl = false; //only enable this if your provider requires it
            //Setup credentials to login to our sender email address ("UserName", "Password")
            NetworkCredential credentials = new NetworkCredential("*****@*****.**", "Pa55w0rd!");
            client.Credentials = credentials;

            //Send the msg
            client.Send(msg);
        }
        catch
        {
            //If the message failed at some point, let the user know

            lbl_message.Text = "Your message failed to send, please try again.";
        }
    }
示例#26
0
 //
 public virtual void AuthenticateAsClient( NetworkCredential       credential,
                                         string                  targetName,
                                         ProtectionLevel         requiredProtectionLevel,   //this will be the ultimate result or exception
                                         TokenImpersonationLevel allowedImpersonationLevel) //this OR LOWER will be ultimate result in auth context
 {
     AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
 }
    protected void Submit_Click(object sender, EventArgs e)
    {
        MailAddress mailFrom = new MailAddress("*****@*****.**");
        MailAddress mailTo = new MailAddress("*****@*****.**");

        MailMessage emailMessage = new MailMessage(mailFrom, mailTo);

        emailMessage.Subject = "Unsubscribe";
        emailMessage.Body += "<br>Email: " + email.Text;

        emailMessage.IsBodyHtml = false;

        SmtpClient myMail = new SmtpClient();
        myMail.Host = "localhost";
        myMail.DeliveryMethod = SmtpDeliveryMethod.Network;

        //myMail.Port = 25;
        NetworkCredential SMTPUserInfo = new NetworkCredential("*****@*****.**", "!p3Learning", "pinnacle3learning.com");
        //myMail.UseDefaultCredentials = false;
        myMail.Credentials = SMTPUserInfo;

        myMail.Send(emailMessage);

        MultiView1.ActiveViewIndex = 1;
    }
    protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.ForeColor = Color.Green;
        lblMessage.Text = "";

        try
        {
            // initialize exchange client
            NetworkCredential credential = new NetworkCredential(txtUsername.Text, Session["Password"].ToString(), txtDomain.Text);
            Aspose.Email.Exchange.ExchangeClient client = new Aspose.Email.Exchange.ExchangeClient(txtHost.Text, credential);

            // build message
            MailMessage msg = new MailMessage();
            msg.From = txtFrom.Text;
            msg.To = txtTo.Text;
            msg.Subject = txtSubject.Text;
            msg.TextBody = txtTextBody.Text;

            // send email
            client.Send(msg);

            lblMessage.Text = "Successfully sent email using Microsoft Exchange server.<br><hr>";
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
    protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";
        lblMessage.ForeColor = Color.Green;

        try
        {
            // initialize exchange client
            NetworkCredential credential = new NetworkCredential(txtUsername.Text, txtPassword.Text, txtDomain.Text);
            Aspose.Email.Exchange.ExchangeWebServiceClient client = new Aspose.Email.Exchange.ExchangeWebServiceClient(txtHost.Text, credential);

            // get mailbox and folders information
            Aspose.Email.Exchange.ExchangeMailboxInfo exchangeMailboxInfo = client.GetMailboxInfo();
            lblMailboxURI.Text = exchangeMailboxInfo.MailboxUri;
            lblInboxURI.Text = exchangeMailboxInfo.InboxUri;
            lblSentItemsURI.Text = exchangeMailboxInfo.SentItemsUri;
            lblDraftsURI.Text = exchangeMailboxInfo.DraftsUri;
            lblCalendarURI.Text = exchangeMailboxInfo.CalendarUri;
            lblDeletedItemsURI.Text = exchangeMailboxInfo.DeletedItemsUri;

            lblMessage.Text = "Successfully connected to Microsoft Exchange server.<br><hr>";
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
    public static bool SendMail(string gMailAccount, string password, string to, string subject, string message)
    {
        try
        {
            NetworkCredential loginInfo = new NetworkCredential("*****@*****.**", "sivababu86");
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("*****@*****.**");
            msg.To.Add(new MailAddress(to));
            msg.Subject = subject;
            msg.Body = message;
            msg.IsBodyHtml = true;

            //if any files are attached used this code..
            //msg.Attachments.Add(new Attachment("D:\\Human.doc"));
            //msg.Attachments.Add(new Attachment("D:\\Music.mp3"));
            //msg.Attachments.Add(new Attachment("D:\\Music.mp3"));

            SmtpClient client = new SmtpClient("smtp.gmail.com");
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = loginInfo;
            client.Send(msg);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
示例#31
0
 public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName)
 {
     throw null;
 }
    protected void btnCreateAccount_Click(object sender, EventArgs e)
    {
        //Birthday
        DateTime bday = new DateTime();

        if (txtBday.Text == "")
        {
            lblError.Text = "Please enter the birthdate (MM/DD/YYYY). <br/>";
        }
        else
        {
            //Birthdate validation
            DateTime today = DateTime.Now;
            bday = DateTime.Parse(txtBday.Text, new System.Globalization.CultureInfo("pt-BR"));
            int age = today.Year - bday.Year;
            if (bday > today.AddYears(-age))
            {
                age--;
            }
            if (age < 18)
            {
                lblError.Text = "You must be at least 18 years old.";
            }
            else
            {
                System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection();
                sc.ConnectionString = "server=aawnyfad9tm1sf.cqpnea2xsqc1.us-east-1.rds.amazonaws.com; database =roommagnetdb;uid=admin;password=Skylinejmu2019;";
                sc.Open();
                System.Data.SqlClient.SqlCommand checkEmailCount = new System.Data.SqlClient.SqlCommand();
                System.Data.SqlClient.SqlCommand insert          = new System.Data.SqlClient.SqlCommand();
                checkEmailCount.Connection = sc;
                insert.Connection          = sc;

                int emailCount;

                //create new account and tenant object
                Account newAccount = new Account(HttpUtility.HtmlEncode(txtFN.Text), HttpUtility.HtmlEncode(txtMN.Text), HttpUtility.HtmlEncode(txtLN.Text),
                                                 HttpUtility.HtmlEncode(txtPhone.Text), DateTime.Parse(txtBday.Text, new System.Globalization.CultureInfo("pt-BR")), HttpUtility.HtmlEncode(txtEmail.Text),
                                                 HttpUtility.HtmlEncode(txtHouseNum.Text), HttpUtility.HtmlEncode(txtStreet.Text), HttpUtility.HtmlEncode(txtCity.Text), ddState.SelectedValue,
                                                 HttpUtility.HtmlEncode(txtZip.Text), "US", Int32.Parse("3"), Int32.Parse("3"));
                Tenant newTenant = new Tenant(newAccount, Int32.Parse("0"), "Student");

                checkEmailCount.CommandText = "SELECT COUNT(*) FROM ACCOUNT WHERE EMAIL = @emailCheck";
                checkEmailCount.Parameters.Add(new SqlParameter("@emailCheck", newAccount.getEmail()));

                emailCount = (int)checkEmailCount.ExecuteScalar();
                //Insert into Account
                if (emailCount < 1)
                {
                    insert.CommandText = "INSERT into Account VALUES(@fName, NULLIF(@mName, ''), @lName, @phone, @bday, @email, @HouseNbr, @street, @city, @state, @zip, @country, NULL, @AccType, @ModDate, @PID); " +
                                         "INSERT into Tenant VALUES(@@IDENTITY, @BackCheck, @TenantReason); " +
                                         "INSERT into Password VALUES((SELECT MAX(TenantID) from Tenant), @email, @password);";

                    //Insert into ACCOUNT
                    insert.Parameters.Add(new SqlParameter("@fName", newTenant.getFirstName()));
                    insert.Parameters.Add(new SqlParameter("@mName", newTenant.getMiddleName()));
                    insert.Parameters.Add(new SqlParameter("@lName", newTenant.getLastName()));
                    insert.Parameters.Add(new SqlParameter("@phone", newTenant.getPhone()));
                    insert.Parameters.Add(new SqlParameter("@bday", newTenant.getBday()));
                    insert.Parameters.Add(new SqlParameter("@email", newTenant.getEmail()));
                    insert.Parameters.Add(new SqlParameter("@HouseNbr", newTenant.getHouseNumber()));
                    insert.Parameters.Add(new SqlParameter("@street", newTenant.getStreet()));
                    insert.Parameters.Add(new SqlParameter("@city", newTenant.getCity()));
                    insert.Parameters.Add(new SqlParameter("@state", newTenant.getState()));
                    insert.Parameters.Add(new SqlParameter("@zip", newTenant.getZip()));
                    insert.Parameters.Add(new SqlParameter("@country", newTenant.getCountry()));
                    insert.Parameters.Add(new SqlParameter("@AccType", newTenant.getAccType()));
                    insert.Parameters.Add(new SqlParameter("@ModDate", newTenant.getModDate()));
                    insert.Parameters.Add(new SqlParameter("@PID", newTenant.getPID()));

                    //Insert into TENANT
                    insert.Parameters.Add(new SqlParameter("@BackCheck", newTenant.getBackgroundStatus()));
                    insert.Parameters.Add(new SqlParameter("@TenantReason", newTenant.getTenantReason()));

                    //Insert into PASSWORD
                    insert.Parameters.Add(new SqlParameter("@password", PasswordHash.HashPassword(txtPassword.Text))); // hash entered password

                    insert.ExecuteNonQuery();
                    //Tenant Access
                    Session["type"] = 3;

                    System.Data.SqlClient.SqlCommand getAcctID = new System.Data.SqlClient.SqlCommand();
                    getAcctID.CommandText = "SELECT AccountID FROM Account WHERE EMAIL = @emailCheck";
                    getAcctID.Parameters.Add(new SqlParameter("@emailCheck", newAccount.getEmail()));
                    getAcctID.Connection = sc;
                    int AccountID = (int)getAcctID.ExecuteScalar();

                    Session["AccountId"] = AccountID;

                    sc.Close();

                    //Fetching Settings from WEB.CONFIG file.
                    string  emailSender         = ConfigurationManager.AppSettings["username"].ToString();
                    string  emailSenderPassword = ConfigurationManager.AppSettings["password"].ToString();
                    string  emailSenderHost     = ConfigurationManager.AppSettings["smtp"].ToString();
                    int     emailSenderPort     = Convert.ToInt16(ConfigurationManager.AppSettings["portnumber"]);
                    Boolean emailIsSSL          = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSSL"]);


                    //Fetching Email Body Text from EmailTemplate File.
                    string       FilePath = Server.MapPath("~/Email.aspx");
                    StreamReader str      = new StreamReader(FilePath);
                    string       MailText = str.ReadToEnd();
                    str.Close();

                    //Repalce [newusername] = signup user name
                    MailText = MailText.Replace("[newusername]", txtFN.Text.Trim());


                    string subject = "Welcome to roommagnet!";

                    //Base class for sending email
                    MailMessage _mailmsg = new MailMessage();

                    //Make TRUE because our body text is html
                    _mailmsg.IsBodyHtml = true;

                    //Set From Email ID
                    _mailmsg.From = new MailAddress(emailSender);

                    //Set To Email ID
                    _mailmsg.To.Add(txtEmail.Text.ToString());

                    //Set Subject
                    _mailmsg.Subject = subject;

                    //Set Body Text of Email
                    _mailmsg.Body = MailText;


                    //Now set your SMTP
                    SmtpClient _smtp = new SmtpClient();

                    //Set HOST server SMTP detail
                    _smtp.Host = emailSenderHost;

                    //Set PORT number of SMTP
                    _smtp.Port = emailSenderPort;

                    //Set SSL --> True / False
                    _smtp.EnableSsl = emailIsSSL;

                    //Set Sender UserEmailID, Password
                    NetworkCredential _network = new NetworkCredential(emailSender, emailSenderPassword);
                    _smtp.Credentials = _network;

                    //Send Method will send your MailMessage create above.
                    _smtp.Send(_mailmsg);

                    //send email if user has check the background checkbox
                    //if (cbBackCheck.Checked == true)
                    //{
                    //    //Fetching Email Body Text from EmailTemplate File.
                    //    string FilePath2 = Server.MapPath("~/BackgroundEmail.aspx");
                    //    StreamReader str2 = new StreamReader(FilePath);
                    //    string MailText2 = str2.ReadToEnd();
                    //    str2.Close();

                    //    //Replace [newusername] = signup user name
                    //    MailText2 = MailText.Replace("[newusername]", txtFN.Text.Trim());


                    //    string subject2 = "Begin your Background Check!";

                    //    //Base class for sending email
                    //    MailMessage _mailmsg2 = new MailMessage();

                    //    //Make TRUE because our body text is html
                    //    _mailmsg2.IsBodyHtml = true;

                    //    //Set From Email ID
                    //    _mailmsg2.From = new MailAddress(emailSender);

                    //    //Set To Email ID
                    //    _mailmsg2.To.Add(txtEmail.Text.ToString());

                    //    //Set Subject
                    //    _mailmsg2.Subject = subject2;

                    //    //Set Body Text of Email
                    //    _mailmsg2.Body = MailText;


                    //    //Now set your SMTP
                    //    SmtpClient _smtp2 = new SmtpClient();

                    //    //Set HOST server SMTP detail
                    //    _smtp2.Host = emailSenderHost;

                    //    //Set PORT number of SMTP
                    //    _smtp2.Port = emailSenderPort;

                    //    //Set SSL --> True / False
                    //    _smtp2.EnableSsl = emailIsSSL;

                    //    //Set Sender UserEmailID, Password
                    //    NetworkCredential _network2 = new NetworkCredential(emailSender, emailSenderPassword);
                    //    _smtp2.Credentials = _network2;

                    //    //Send Method will send your MailMessage create above.
                    //    _smtp2.Send(_mailmsg2);

                    //    //Clear text boxes
                    //    txtFN.Text = "";
                    //    txtMN.Text = "";
                    //    txtLN.Text = "";
                    //    txtBday.Text = "";
                    //    txtEmail.Text = "";
                    //    txtPhone.Text = "";
                    //    txtPassword.Text = "";
                    //    txtHouseNum.Text = "";
                    //    txtStreet.Text = "";
                    //    txtCity.Text = "";
                    //    ddState.ClearSelection();
                    //    txtZip.Text = "";

                    //    Response.Redirect("TenantAccountCategories.aspx");
                    //}

                    //Clear text boxes
                    txtFN.Text       = "";
                    txtMN.Text       = "";
                    txtLN.Text       = "";
                    txtBday.Text     = "";
                    txtEmail.Text    = "";
                    txtPhone.Text    = "";
                    txtPassword.Text = "";
                    txtHouseNum.Text = "";
                    txtStreet.Text   = "";
                    txtCity.Text     = "";
                    ddState.ClearSelection();
                    txtZip.Text = "";

                    Response.Redirect("TenantAccountCategories.aspx");
                }
                else
                {
                    sc.Close();
                    //Clear text boxes
                }
            }
        }
    }
        //Password vergessen
        protected void BtnEmailsenden_Click(object sender, EventArgs e)
        {
            if (ValidateEmail(txtemailtoPass.Value.ToString()))
            {
                Random pass             = new Random();
                int    neuPass          = pass.Next();
                string userRole         = string.Empty;
                string password         = string.Empty;
                string ConnectionString = "data Source = localhost\\MAHMOUDSQL; Initial Catalog = RaumVerwaltung; Persist Security Info = True; User ID = Allameh; Password = Allameh1905";
                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT userRole FROM Users WHERE uname = @Email"))
                    {
                        cmd.Parameters.AddWithValue("@Email", txtemailtoPass.Value.ToString());
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            if (sdr.Read())
                            {
                                userRole = sdr["userRole"].ToString();
                            }
                            con.Close();
                        }
                    }
                    if (!string.IsNullOrEmpty(userRole))
                    {
                        SqlConnection cnn = new SqlConnection(ConnectionString);
                        SqlCommand    cmd = new SqlCommand();
                        cnn.Open();
                        cmd.CommandText = "UPDATE Users SET Pwd = @Pass WHERE uname=@email ";
                        cmd.Connection  = cnn;
                        cmd.Parameters.AddWithValue("@pass", value: neuPass);
                        cmd.Parameters.AddWithValue("@email", value: "*****@*****.**");
                        cmd.ExecuteNonQuery();
                        cnn.Close();
                        cnn.Dispose();

                        Session.Add("EmailToPass", txtemailtoPass.Value);
                        using (MailMessage mm = new MailMessage("*****@*****.**", Convert.ToString(Session["EmailToPass"].ToString())))
                        {
                            mm.Subject = "Neu Passwort erstellen";
                            string body = "Sehr geeherte Damen und Herren";
                            body         += "<br /><br />hiermit schicken wir Ihnen eine email und temporäres Passwort ";
                            body         += "<br /><br />Email : [email protected]";
                            body         += "<br />Temporäres Passwort : " + neuPass;
                            body         += "<br /><br />Mit freundlichen Grüßen";
                            mm.Body       = body;
                            mm.IsBodyHtml = true;
                            SmtpClient smtp = new SmtpClient("mail.gmx.net", 25);
                            smtp.EnableSsl = true;
                            NetworkCredential NetworkCred = new NetworkCredential("*****@*****.**", "testmail3311");
                            smtp.UseDefaultCredentials = true;
                            smtp.Credentials           = NetworkCred;
                            smtp.Send(mm);
                        }

                        Response.Redirect("NeuPasswort.aspx");
                    }
                    else
                    {
                        lblEmailError.Visible      = true;
                        lblEmailError0.Visible     = false;
                        lblEmailLeer.Visible       = false;
                        lblEmailtopassLeer.Visible = false;
                        lblEmilAdresseLeer.Visible = false;
                        lblErrorPass.Visible       = false;
                        lblMsg1.Visible            = false;
                        lblMsg.Visible             = false;
                        lblPassLeer.Visible        = false;
                        lblPassLeer2.Visible       = false;
                        lblPasswortLeer.Visible    = false;
                    }
                }
            }
        }
        /// <summary>
        /// Call the plugin credential provider application to acquire credentials.
        /// The request will be passed to the plugin on standard input as a json serialized
        /// PluginCredentialRequest.
        /// The plugin will return credentials as a json serialized PluginCredentialResponse.
        /// Valid credentials will be returned, or null if the provide cannot provide credentials
        /// for the given request.  If the plugin returns an Abort message, an exception will be thrown to
        /// fail the current request.
        /// </summary>
        /// <param name="uri">The uri of a web resource for which credentials are needed.</param>
        /// <param name="proxy">Ignored.  Proxy information will not be passed to plugins.</param>
        /// <param name="type">
        /// The type of credential request that is being made. Note that this implementation of
        /// <see cref="ICredentialProvider"/> does not support providing proxy credenitials and treats
        /// all other types the same.
        /// </param>
        /// <param name="isRetry">If true, credentials were previously supplied by this
        /// provider for the same uri.</param>
        /// <param name="message">A message provided by NuGet to show to the user when prompting.</param>
        /// <param name="nonInteractive">If true, the plugin must not prompt for credentials.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A credential object.  If </returns>
        public Task <CredentialResponse> GetAsync(
            Uri uri,
            IWebProxy proxy,
            CredentialRequestType type,
            string message,
            bool isRetry,
            bool nonInteractive,
            CancellationToken cancellationToken)
        {
            CredentialResponse taskResponse;

            if (type == CredentialRequestType.Proxy)
            {
                taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
                return(Task.FromResult(taskResponse));
            }

            try
            {
                var request = new PluginCredentialRequest
                {
                    Uri            = uri.ToString(),
                    IsRetry        = isRetry,
                    NonInteractive = nonInteractive,
                    Verbosity      = _verbosity
                };
                PluginCredentialResponse response;

                // TODO: Extend the plug protocol to pass in the credential request type.
                try
                {
                    response = GetPluginResponse(request, cancellationToken);
                }
                catch (PluginUnexpectedStatusException) when(PassVerbosityFlag(request))
                {
                    // older providers may throw if the verbosity flag is sent,
                    // so retry without it
                    request.Verbosity = null;
                    response          = GetPluginResponse(request, cancellationToken);
                }

                if (response.IsValid)
                {
                    ICredentials result = new NetworkCredential(response.Username, response.Password);
                    if (response.AuthTypes != null)
                    {
                        result = new AuthTypeFilteredCredentials(result, response.AuthTypes);
                    }

                    taskResponse = new CredentialResponse(result);
                }
                else
                {
                    taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (PluginException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw PluginException.Create(Path, e);
            }

            return(Task.FromResult(taskResponse));
        }
示例#35
0
        void BOKClick(object sender, EventArgs e)
        {
            WebClient wcli = null;

            try
            {
                string source = txOrigen.Text.Trim();

                if (source == string.Empty)
                {
                    throw new Exception("No se ha especificado fichero de origen");
                }
                if (!File.Exists(source))
                {
                    throw new Exception("No se encuentra el fichero de origen especificado");
                }

                string dest = txDestino.Text.Trim();

                if (dest != string.Empty)
                {
                    string data = string.Empty;
                    try
                    {
                        using (StreamReader r = new StreamReader(source))
                        {
                            data = r.ReadToEnd();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    NameValueCollection nvc = new NameValueCollection();
                    nvc.Add("FILENAME", Path.GetFileName(source));
                    nvc.Add("DATA", data);
                    wcli = new WebClient();
                    wcli.UploadValues(dest, nvc);

                    if (wcli.ResponseHeaders["Status"] != null)
                    {
                        if (wcli.ResponseHeaders["Status"] == "401")
                        {
                            frmHTTPBasicAuth w = new frmHTTPBasicAuth();
                            w.ShowDialog();
                            if (w.DialogResult == DialogResult.OK)
                            {
                                NetworkCredential c = new NetworkCredential(w.Usr, w.Pwd);
                                wcli.Credentials = c;
                                wcli.UploadValues(dest, nvc);
                            }
                            else
                            {
                                return;
                            }
                        }
                    }

                    if (wcli.ResponseHeaders["Status"] != null)
                    {
                        switch (wcli.ResponseHeaders["Status"])
                        {
                        case "200":
                            MessageBox.Show("El servidor de destino respondió: 200 (OK)", "Upload", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            break;

                        case "404":
                            throw new Exception("El servidor de destino respondió: 404 (Not found)");

                        default:
                            throw new Exception(string.Format("El servidor de destino respondió: {0}", wcli.ResponseHeaders["Status"]));
                        }
                    }
                    else
                    {
                        throw new Exception("El destino no es válido");
                    }
                }
                else
                {
                    throw new Exception("No se ha especificado URI de destino");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#36
0
 public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel)
 {
     throw null;
 }
示例#37
0
 public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel)
 {
     throw null;
 }
示例#38
0
 public virtual void AuthenticateAsServer(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel)
 {
 }
示例#39
0
        public RESTfulService()
        {
            _credentials = new NetworkCredential();

            LoadConfiguration();
        }
示例#40
0
 public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName)
 {
     throw null;
 }
示例#41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:MailKit.Net.Proxy.Socks5Client"/> class.
 /// </summary>
 /// <remarks>
 /// Initializes a new instance of the <see cref="T:MailKit.Net.Proxy.Socks5Client"/> class.
 /// </remarks>
 /// <param name="host">The host name of the proxy server.</param>
 /// <param name="port">The proxy server port.</param>
 /// <param name="credentials">The credentials to use to authenticate with the proxy server.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="host"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="credentials"/>is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="port"/> is not between <c>1</c> and <c>65535</c>.
 /// </exception>
 /// <exception cref="System.ArgumentException">
 /// <para>The <paramref name="host"/> is a zero-length string.</para>
 /// <para>-or-</para>
 /// <para>The length of <paramref name="host"/> is greater than 255 characters.</para>
 /// </exception>
 public Socks5Client(string host, int port, NetworkCredential credentials) : base(5, host, port, credentials)
 {
 }
示例#42
0
        private void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
        {
            using (MailMessage mailMessage = new MailMessage())
            {
                if (Forms == "Order_Invoice")
                {
                    mailMessage.From = new MailAddress("*****@*****.**");
                    Path1            = @"\\192.168.12.33\Invoice-Reports\Invoicemerge.pdf";
                    Attachment_Name  = Order_Number.ToString() + ".pdf";
                }
                else if (Forms == "Monthly_Invoice")
                {
                    mailMessage.From = new MailAddress("*****@*****.**");
                    Path1            = @"\\192.168.12.33\Invoice-Reports\InvoiceMonthly.pdf";
                    Attachment_Name  = "MonthlyInvoice.pdf";
                }

                var      maxsize  = 15 * 1024 * 1000;
                var      fileName = Path1;
                FileInfo fi       = new FileInfo(fileName);
                var      size     = fi.Length;
                if (size <= maxsize)
                {
                    MemoryStream ms = new MemoryStream(File.ReadAllBytes(Path1));



                    mailMessage.Attachments.Add(new System.Net.Mail.Attachment(ms, Attachment_Name.ToString()));

                    Hashtable             htdate = new Hashtable();
                    System.Data.DataTable dtdate = new System.Data.DataTable();
                    htdate.Add("@Trans", "SELECT");
                    htdate.Add("@Sub_Process_Id", Sub_Process_ID);
                    dtdate = dataaccess.ExecuteSP("Sp_Client_Mail", htdate);
                    if (dtdate.Rows.Count > 0)
                    {
                        Email             = "Avilable";
                        Alternative_Email = "Avilable";
                    }
                    else
                    {
                        Email             = "";
                        Alternative_Email = "";
                    }


                    if (Email != "")
                    {
                        for (int j = 0; j < dtdate.Rows.Count; j++)
                        {
                            mailMessage.To.Add(dtdate.Rows[j]["Email-ID"].ToString());
                        }

                        if (Forms == "Monthly_Invoice")
                        {
                            mailMessage.CC.Add("*****@*****.**");
                        }
                        else
                        {
                            mailMessage.CC.Add("*****@*****.**");
                        }

                        if (Forms == "Order_Invoice")
                        {
                            Hashtable htorder = new Hashtable();
                            DataTable dtorder = new DataTable();
                            htorder.Add("@Trans", "GET_INVOICE_ORDER_DETAILS_FOR_EMAIL");
                            htorder.Add("@Order_ID", Order_Id);
                            dtorder = dataaccess.ExecuteSP("Sp_Order_Invoice_Entry", htorder);
                            if (dtorder.Rows.Count > 0)
                            {
                            }

                            string Title   = dtorder.Rows[0]["Order_Type"].ToString();
                            string Subject = "" + Order_Number + "-" + Title.ToString();
                            mailMessage.Subject = Subject.ToString();

                            StringBuilder sb = new StringBuilder();
                            sb.Append("Subject: " + Subject.ToString() + "" + Environment.NewLine);
                        }
                        else if (Forms == "Monthly_Invoice")
                        {
                            string Subject = "Invoice - " + Invoice_Month_Name.ToString();
                            mailMessage.Subject = Subject.ToString();
                        }


                        mailMessage.Body       = body;
                        mailMessage.IsBodyHtml = true;



                        SmtpClient smtp = new SmtpClient();

                        smtp.Host = "smtpout.secureserver.net";

                        if (Forms == "Order_Invoice")
                        {
                            NetworkCred = new NetworkCredential("*****@*****.**", "123abs");
                        }
                        else if (Forms == "Monthly_Invoice")
                        {
                            NetworkCred = new NetworkCredential("*****@*****.**", "Steve@1234");
                        }
                        smtp.UseDefaultCredentials = false;
                        // smtp.Timeout = Math.Max(attachments.Sum(Function(Item) (DirectCast(Item, MailAttachment).Size / 1024)), 100) * 1000
                        smtp.Timeout     = (60 * 5 * 1000);
                        smtp.Credentials = NetworkCred;
                        // smtp.EnableSsl = true;
                        smtp.Port = 80;
                        //string userState = "test message1";
                        smtp.Send(mailMessage);
                        smtp.Dispose();

                        if (Forms == "Order_Invoice")
                        {
                            Update_Invoice_Email_Status();
                        }
                        else if (Forms == "Monthly_Invoice")
                        {
                            Update_Monthly_Invoice_Email_Status();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Email is Not Added Kindly Check It");
                    }
                }
                else
                {
                    MessageBox.Show("Attachment Size should less than 10 mb ");
                }
            }
        }
示例#43
0
        private IPrincipal GetPrincipal(HttpContextBase context, MembershipUser membershipUser, NetworkCredential credential)
        {
            //if configuration specifies a plug-in principal builder, then use what's specified
            //this allows use to accept basic auth credentials, but return custom principal objects
            //i.e. username /password -> custom principal!
            if (null != Configuration.PrincipalBuilder)
            {
                return(Configuration.PrincipalBuilder.ConstructPrincipal(context, membershipUser, credential));
            }

            //otherwise, use our generic identities / principals create principal and set Context.User
            GenericIdentity id = new GenericIdentity(credential.UserName, "CustomBasic");

            if (!string.IsNullOrEmpty(Configuration.RoleProviderName))
            {
                return(new FixedProviderRolePrincipal(RoleProviderHelper.GetProviderByName(Configuration.RoleProviderName), id));
            }

            return(new GenericPrincipal(id, null));
        }
示例#44
0
        //public AlternateView GetAlternateView(string htmlBody)
        //{
        //    var avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);

        //    var inline = new LinkedResource("hellogram_icon.png", MediaTypeNames.Image.Jpeg)
        //    {
        //        ContentId = "#img#"
        //    };
        //    avHtml.LinkedResources.Add(inline);
        //    return avHtml;
        //}

        public async Task SendEmail(IdentityMessage message)
        {
            try
            {
                using (var mail = new MailMessage())
                {
                    var email    = ConfigurationManager.AppSettings["email"];
                    var password = ConfigurationManager.AppSettings["password"];

                    var loginInfo = new NetworkCredential(email, password);

                    mail.From = new MailAddress(email);
                    mail.To.Add(new MailAddress(message.Destination));
                    mail.Subject    = message.Subject;
                    mail.Body       = message.Body;
                    mail.IsBodyHtml = true;

                    //mail.AlternateViews.Add(GetAlternateView(message.Body));

                    try
                    {
                        using (var smtpClient = new SmtpClient(ConfigurationManager.AppSettings["outlook-smtp"], Convert.ToInt32(ConfigurationManager.AppSettings["outlook-port"])))
                        {
                            smtpClient.EnableSsl             = true;
                            smtpClient.UseDefaultCredentials = false;
                            smtpClient.Credentials           = loginInfo;
                            await smtpClient.SendMailAsync(mail);
                        }
                    }
                    finally
                    {
                        //dispose the client
                        mail.Dispose();
                    }
                }
            }
            catch (SmtpFailedRecipientsException ex)
            {
                foreach (var t in ex.InnerExceptions)
                {
                    var status = t.StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy ||
                        status == SmtpStatusCode.MailboxUnavailable)
                    {
                        throw new ArgumentException("Delivery failed - retrying in 5 seconds.");
                    }
                    else
                    {
                        throw new ArgumentException($"Failed to deliver message to {t.FailedRecipient}");
                    }
                }
            }
            catch (SmtpException e)
            {
                // handle exception here
                throw new ArgumentException(e.ToString());
            }

            catch (Exception ex)
            {
                throw new ArgumentException(ex.ToString());
            }
        }
 /// <summary>
 /// Generates a string that can be used for "Auth" headers in web requests, "username:password" encoded in Base64
 /// </summary>
 /// <param name="cred"></param>
 /// <returns></returns>
 public static string GetBasicAuthString(this NetworkCredential cred)
 {
     byte[] credentialBuffer = new UTF8Encoding().GetBytes(cred.UserName + ":" + cred.Password);
     return(Convert.ToBase64String(credentialBuffer));
 }
示例#46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanismDigestMd5"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new DIGEST-MD5 SASL context.
 /// </remarks>
 /// <param name="credentials">The user's credentials.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="credentials"/> is <c>null</c>.
 /// </exception>
 public SaslMechanismDigestMd5(NetworkCredential credentials) : base(credentials)
 {
 }
示例#47
0
        public static XDocument GetServerProfile(string serviceUrl, string logsTempPath, string appName, NetworkCredential credentials = null)
        {
            var       zippedLogsPath   = Path.Combine(logsTempPath, appName + ".zip");
            var       unzippedLogsPath = Path.Combine(logsTempPath, appName);
            var       profileLogPath   = Path.Combine(unzippedLogsPath, "trace", "trace.xml");
            XDocument document         = null;

            DownloadDump(serviceUrl, zippedLogsPath, credentials);

            if (File.Exists(zippedLogsPath))
            {
                ZipUtils.Unzip(zippedLogsPath, unzippedLogsPath);
                using (var stream = File.OpenRead(profileLogPath))
                {
                    document = XDocument.Load(stream);
                }
            }

            return(document);
        }
示例#48
0
 public CustomProxy(bool bypassAll)
 {
     this.bypassAll         = bypassAll;
     this.networkCredential = new NetworkCredential(CustomProxy.DefaultUsername, CustomProxy.DefaultPassword, CustomProxy.DefaultDomain);
 }
示例#49
0
    protected void btnEnv_Click(object sender, EventArgs e)
    {
        int retorno = 0;

        retorno = ValidarForm();
        if (retorno == 1)//Motivo
        {
            Response.Write("<script language = 'javascript'>alert('Por favor Selecione um Motivo do contato');</script>");
        }
        if (retorno == 2)//Nome
        {
            Response.Write("<script language = 'javascript'>alert('O Campo Nome Está Vazio');</script>");
        }
        if (retorno == 3)//E-mail
        {
            Response.Write("<script language = 'javascript'>alert('O Campo E-mail Está Vazio');</script>");
        }
        if (retorno == 4)//Mensagem
        {
            Response.Write("<script language = 'javascript'>alert('O Campo Mensagem Está Vazio');</script>");
        }
        if (retorno == 5)//Todos
        {
            Response.Write("<script language = 'javascript'>alert('Todos os Campos estão vazios');</script>");
        }
        if (retorno == 6)//Email não valido
        {
            Response.Write("<script language = 'javascript'>alert('Esse E-mail não é valido');</script>");
        }
        if (retorno == 0)
        {
            Response.Write("<script language = 'javascript'>alert('Mensagem enviada com sucesso');</script>");

            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("*****@*****.**");
            msg.To.Add(new MailAddress("*****@*****.**"));
            if (rdnBug.Checked == true)
            {
                msg.Subject = "Reportar Bug";
            }
            if (rdnHate.Checked == true)
            {
                msg.Subject = "Reclamação";
            }
            if (rdnOutro.Checked == true)
            {
                msg.Subject = "Outro";
            }
            msg.IsBodyHtml = true;
            msg.Body       = "Nome: " + txtNome.Text + "\nE-mail: " + txtEmail.Text + "\nMensagem: " + txtMen.Text;

            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            System.Net.NetworkCredential ntcd = new NetworkCredential();
            ntcd.UserName    = "******";
            ntcd.Password    = "******";
            smtp.Credentials = ntcd;
            smtp.EnableSsl   = true;
            smtp.Port        = 587;
            smtp.Send(msg);
        }
    }
示例#50
0
 public Fetcher(NetworkCredential credential)
 {
     this.Credential = credential;
 }
 public WatsonConversationHelper(string workSpaceId, string userId, string password)
 {
     _Server        = string.Format("https://gateway.watsonplatform.net/assistant/api/v1/workspaces/{0}/message?version={1}", workSpaceId, DateTime.Today.ToString("yyyy-MM-dd"));
     _NetCredential = new NetworkCredential(userId, password);
 }
示例#52
0
 /// <summary>
 ///     Start checking for new version of application via FTP and display dialog to the user if update is available.
 /// </summary>
 /// <param name="appCast">FTP URL of the xml file that contains information about latest version of the application.</param>
 /// <param name="ftpCredentials">Credentials required to connect to FTP server.</param>
 /// <param name="myAssembly">Assembly to use for version checking.</param>
 public static void Start(String appCast, NetworkCredential ftpCredentials, Assembly myAssembly = null)
 {
     FtpCredentials = ftpCredentials;
     Start(appCast, myAssembly);
 }
示例#53
0
    // FTP 下載
    internal bool Download(string downloadUrl, string TargetPath, string UserName, string Password)
    {
        // downloadUrl下載FTP的目錄ex :
        // ftp//127.0.0.1/abc.xml
        // TargetPath本機存檔目錄
        // UserName使用者FTP登入帳號
        // Password使用者登入密碼

        Stream       responseStream = null;
        FileStream   fileStream     = null;
        StreamReader reader         = null;

        try
        {
            FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);
            downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile; //設定Method下載檔案

            if (UserName.Length > 0)                                     //如果需要帳號登入
            {
                NetworkCredential nc = new NetworkCredential(UserName, Password);
                downloadRequest.Credentials = nc;//設定帳號
            }

            FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();
            responseStream = downloadResponse.GetResponseStream(); //取得FTP伺服器回傳的資料流
            string fileName = Path.GetFileName(downloadRequest.RequestUri.AbsolutePath);

            if (fileName.Length == 0)
            {
                reader = new StreamReader(responseStream);
                throw new Exception(reader.ReadToEnd());
            }
            else
            {
                fileStream = File.Create(TargetPath + @"\" + fileName);
                byte[] buffer = new byte[1024];
                int    bytesRead;
                while (true)
                {//開始將資料流寫入到本機
                    bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    fileStream.Write(buffer, 0, bytesRead);
                }
            }
            return(true);
        }
        catch (IOException ex)
        {
            throw new Exception(ex.Message);
        }

        finally
        {
            if (reader != null)
            {
                reader.Close();
            }

            else if (responseStream != null)
            {
                responseStream.Close();
            }

            if (fileStream != null)
            {
                fileStream.Close();
            }
        }
    }
示例#54
0
 private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2)
 {
     Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check");
     return(credential1.UserName == credential2.UserName &&
            credential1.Domain == credential2.Domain &&
            string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal));
 }
示例#55
0
 public ADRootOrganizationRecipientSession(string domainController, ADObjectId searchRoot, int lcid, bool readOnly, ConsistencyMode consistencyMode, NetworkCredential networkCredential, ADSessionSettings sessionSettings) : base(domainController, searchRoot, lcid, readOnly, consistencyMode, networkCredential, sessionSettings)
 {
 }
示例#56
0
            public Uri GetProxy(Uri targetUri)
            {
                NetworkCredential credentials = null;
                Uri proxy = null;

                if (targetUri == null)
                {
                    throw new ArgumentNullException("targetUri");
                }

                try {
                    CFProxySettings settings = CFNetwork.GetSystemProxySettings();
                    CFProxy[]       proxies  = CFNetwork.GetProxiesForUri(targetUri, settings);

                    if (proxies != null)
                    {
                        for (int i = 0; i < proxies.Length && proxy == null; i++)
                        {
                            switch (proxies[i].ProxyType)
                            {
                            case CFProxyType.AutoConfigurationJavaScript:
                                proxy = GetProxyUriFromScript(proxies[i].AutoConfigurationJavaScript, targetUri, out credentials);
                                break;

                            case CFProxyType.AutoConfigurationUrl:
                                // unsupported proxy type (requires fetching script from remote url)
                                break;

                            case CFProxyType.HTTPS:
                            case CFProxyType.HTTP:
                            case CFProxyType.FTP:
                                // create a Uri based on the hostname/port/etc info
                                proxy = GetProxyUri(proxies[i], out credentials);
                                break;

                            case CFProxyType.SOCKS:
                                // unsupported proxy type, try the next one
                                break;

                            case CFProxyType.None:
                                // no proxy should be used
                                proxy = targetUri;
                                break;
                            }
                        }

                        if (proxy == null)
                        {
                            // no supported proxies for this Uri, fall back to trying to connect to targetUri directly
                            proxy = targetUri;
                        }
                    }
                    else
                    {
                        proxy = targetUri;
                    }
                } catch {
                    // ignore errors while retrieving proxy data
                    proxy = targetUri;
                }

                if (!userSpecified)
                {
                    this.credentials = credentials;
                }

                return(proxy);
            }
        public static NetworkCredential GetNetworkCredential(this IAuthentication authentication)
        {
            var networkCredential = new NetworkCredential(authentication.Username, authentication.Password);

            return(networkCredential);
        }
示例#58
0
 public ADRootOrganizationRecipientSession(string domainController, ADObjectId searchRoot, int lcid, bool readOnly, ConsistencyMode consistencyMode, NetworkCredential networkCredential, ADSessionSettings sessionSettings, ConfigScopes configScope) : this(domainController, searchRoot, lcid, readOnly, consistencyMode, networkCredential, sessionSettings)
 {
     base.CheckConfigScopeParameter(configScope);
     base.ConfigScope = configScope;
 }
        protected void btnEmail_Click(object sender, EventArgs e)
        {
            try
            {
                string    checkedRequiredField = "";
                DataTable dt = new DataTable();
                Report.LoadSourceDataSet(ref checkedRequiredField, ref dt);
                foreach (DataRow dR in dt.Rows)
                {
                    string email = dR["OfficialEmail"].ToString().Trim();
                    if (email.IsNullOrEmpty())
                    {
                        continue;
                    }
                    Microsoft.Reporting.WebForms.ReportViewer rview = new Microsoft.Reporting.WebForms.ReportViewer();
                    rview.LocalReport.ReportPath = Session["reportPath"].ToString();
                    DataTable dt1 = new DataTable();
                    Report.LoadSourceDataSet(dR["EmpKey"].ToString(), ref dt1);


                    ReportDataSource rdSource = null;
                    //foreach (DataTable dtTable in Report.dsSource.Tables)
                    //{
                    rdSource       = new ReportDataSource();
                    rdSource.Name  = dt1.TableName;
                    rdSource.Value = dt1.DefaultView;
                    rview.LocalReport.DataSources.Add(rdSource);
                    //}

                    string   mimeType, encoding, extension;
                    string[] streamids; Microsoft.Reporting.WebForms.Warning[] warnings;
                    string   format = "PDF";
                    byte[]   bytes  = rview.LocalReport.Render(format, "", out mimeType, out encoding, out extension, out streamids, out warnings);


                    using (MemoryStream input = new MemoryStream(bytes))
                    {
                        using (MemoryStream output = new MemoryStream())
                        {
                            string    password = "******";
                            PdfReader reader   = new PdfReader(input);
                            PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
                            bytes = output.ToArray();
                            //Response.ContentType = "application/pdf";
                            //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                            //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                            //Response.BinaryWrite(bytes);
                            //Response.End();
                        }
                    }

                    //save the pdf byte to the folder

                    string savePath = ConfigurationManager.AppSettings["PaySlipFile"];
                    var    path     = System.Web.HttpContext.Current.Server.MapPath(savePath) + dR["EmpKey"].ToString() + "-" + dR["EmpName"].ToString() + ".pdf";
                    //var fullFileName = path  + fileInfo.Extension;
                    FileStream fs   = new FileStream(path, FileMode.Create);
                    byte[]     data = new byte[fs.Length];
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();

                    //SendEmailWithReportAttachment obj = new SendEmailWithReportAttachment();
                    //obj.Email(dR["EmpKey"].ToString(), email, path);
                    MailMessage msg = new MailMessage();

                    //msg.To.Add("*****@*****.**");
                    msg.To.Add(email);
                    MailAddress frmAdd = new MailAddress("*****@*****.**");
                    msg.From = frmAdd;

                    ////Check user enter CC address or not
                    //if (ccId != "")
                    //{
                    //    msg.CC.Add(ccId);
                    //}
                    ////Check user enter BCC address or not
                    //if (bccId != "")
                    //{
                    //    msg.Bcc.Add(bccId);
                    //}
                    msg.Subject = "Pay Slip";
                    //Check for attachment is there
                    //if (FileUpload1.HasFile)
                    //{
                    //    msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
                    //}
                    msg.IsBodyHtml = true;
                    msg.Body       = "This is system generated mail.";

                    Attachment attach = new Attachment(path);
                    msg.Attachments.Add(attach);
                    //MailAttachment attachment = new MailAttachment(Server.MapPath("test.txt")); //create the attachment
                    //mail.Attachments.Add(attachment);	//add the attachment
                    //SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
                    SmtpClient        mailClient = new SmtpClient("*****@*****.**", 1408);
                    NetworkCredential NetCrd     = new NetworkCredential("*****@*****.**", "@ukhiya1*44");
                    mailClient.UseDefaultCredentials = false;
                    mailClient.Credentials           = NetCrd;
                    mailClient.EnableSsl             = true;
                    mailClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    mailClient.Send(msg);
                    attach.Dispose();
                    msg.Dispose();
                    mailClient.Dispose();

                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                }
            }
            catch (Exception ex)
            {
                ((PageBase)this.Page).ErrorMessage = (ExceptionHelper.getExceptionMessage(ex));
            }
        }
示例#60
0
 public SmtpClient(string host, int port, bool enableSsl, bool useDefaultCredentials, NetworkCredential credentials) : base()
 {
     this.Host                  = host;
     this.Port                  = port;;
     this.EnableSsl             = enableSsl;
     this.UseDefaultCredentials = useDefaultCredentials;
     this.Credentials           = credentials;
 }