本文整理汇总了C#中System.Net.NetworkCredential类的典型用法代码示例。如果您正苦于以下问题:C# NetworkCredential类的具体用法?C# NetworkCredential怎么用?C# NetworkCredential使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
NetworkCredential类属于System.Net命名空间,在下文中一共展示了NetworkCredential类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ActivateFeature
public string ActivateFeature(string baseSiteUrl, string user, string password, string domain)
{
if (baseSiteUrl.EndsWith("/"))
baseSiteUrl += "_api/";
else
baseSiteUrl += "/_api/";
RestClient rc = new RestClient(baseSiteUrl);
NetworkCredential nCredential = new NetworkCredential(user, password, domain);
rc.Authenticator = new NtlmAuthenticator(nCredential);
RestRequest request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
request.AddHeader("Accept", "application/json;odata=verbose");
request.AddHeader("Body", "");
string returnedStr = rc.Execute(request).Content;
int startPos = returnedStr.IndexOf("FormDigestValue", StringComparison.Ordinal) + 18;
int length = returnedStr.IndexOf(@""",", startPos, StringComparison.Ordinal) - startPos;
string formDigestValue = returnedStr.Substring(startPos, length);
request = new RestRequest("web/features/add('de646322-53f3-474d-96bf-0ea3670a0722',false)", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json;odata=verbose");
//request.AddHeader("Body", "");
request.AddHeader("Content-Type", "application/json;odata=verbose");
request.AddHeader("X-RequestDigest", formDigestValue);
IRestResponse response = rc.Execute(request);
string content = response.Content;
return content;
}
示例2: GetFileFromSite
/// <summary>
/// method to download the contents of a file from a remote URI
/// </summary>
/// <param name="ftpUri"></param>
/// <param name="user"></param>
/// <param name="pass"></param>
/// <returns></returns>
public static string GetFileFromSite(Uri ftpUri, string user, string pass)
{
string fileString = string.Empty;
// The serverUri parameter should start with the ftp:// scheme.
if (ftpUri.Scheme != Uri.UriSchemeFtp)
{
return string.Empty;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
NetworkCredential nc = new NetworkCredential(user, pass);
CredentialCache cc = new CredentialCache();
cc.Add(ftpUri, "Basic", nc);
request.Credentials = cc;
try
{
byte[] newFileData = request.DownloadData(ftpUri.ToString());
fileString = System.Text.Encoding.UTF8.GetString(newFileData);
}
catch (WebException e)
{
m_logger.WriteToLogFile("FtpUtils::GetFileFromSite();ECaught: " + e.Message);
}
return fileString;
}
示例3: SendMail
public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string sendgridUserName = "", string sendgridPassword = "")
{
string sendMailBySendGrid = string.Empty;
try
{
//var smtp = new SmtpClient();
//smtp.Port = 25;
//smtp.Host = "smtp.sendgrid.net";
SendGrid myMessage = SendGridMail.SendGrid.GetInstance();
myMessage.AddTo(to);
myMessage.From = new MailAddress(from);
myMessage.Subject = subject;
//Add the HTML and Text bodies
myMessage.Html = body;
//myMessage.InitializeFilters();
var credentials = new NetworkCredential(sendgridUserName, sendgridPassword);
var transportWeb = SMTP.GetInstance(credentials);
// Send the email.
transportWeb.Deliver(myMessage);
sendMailBySendGrid = "Success";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return sendMailBySendGrid;
}
示例4: Main
public static void Main(string[] args)
{
string urlString = "ENTER_STREAM_URL_HERE";
HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create("YOUR_STREAM_URL_HERE");
request.Method = "GET";
//Setup Credentials
string username = "ENTER_USERNAME_HERE";
string password = "ENTER_PASSWORD_HERE";
NetworkCredential nc = new NetworkCredential(username, password);
request.Credentials = nc;
request.PreAuthenticate = true;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Headers.Add("Accept-Encoding", "gzip");
request.Accept = "application/json";
request.ContentType = "application/json";
Stream objStream;
objStream = request.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string sLine = "";
while (!objReader.EndOfStream)
{
sLine = objReader.ReadLine();
if (sLine!=null)
Console.WriteLine(sLine);
}
Console.ReadLine();
}
示例5: Send
/// <summary>
/// Sends an email
/// </summary>
/// <param name="to">The list of recipients</param>
/// <param name="subject">The subject of the email</param>
/// <param name="body">The body of the email, which may contain HTML</param>
/// <param name="htmlEmail">Should the email be flagged as "html"?</param>
/// <param name="cc">A list of CC recipients</param>
/// <param name="bcc">A list of BCC recipients</param>
public static void Send(List<String> to, String subject, String body, bool htmlEmail = false, List<String> cc = null, List<String> bcc = null)
{
// Need to have at least one address
if (to == null && cc == null && bcc == null)
throw new System.ArgumentNullException("At least one of the address parameters (to, cc and bcc) must be non-null");
NetworkCredential credentials = new NetworkCredential(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.AdminEmail), JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPassword));
// Set up the built-in MailMessage
MailMessage mm = new MailMessage();
mm.From = new MailAddress(credentials.UserName, "Just Press Play");
if (to != null) foreach (String addr in to) mm.To.Add(new MailAddress(addr, "Test"));
if (cc != null) foreach (String addr in cc) mm.CC.Add(new MailAddress(addr));
if (bcc != null) foreach (String addr in bcc) mm.Bcc.Add(new MailAddress(addr));
mm.Subject = subject;
mm.IsBodyHtml = htmlEmail;
mm.Body = body;
mm.Priority = MailPriority.Normal;
// Set up the server communication
SmtpClient client = new SmtpClient
{
Host = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPServer),
Port = int.Parse(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPort)),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = credentials
};
client.Send(mm);
}
示例6: SendEmail
/// <summary>
/// Send Gmail Email Using Specified Gmail Account
/// </summary>
/// <param name="address">Receipients Adresses</param>
/// <param name="subject">Email Subject</param>
/// <param name="message">Enail Body</param>
/// <param name="AttachmentLocations">List of File locations, null if no Attachments</param>
/// <param name="yourEmailAdress">Gmail Login Adress</param>
/// <param name="yourPassword">Gmail Login Password</param>
/// <param name="yourName">Display Name that Receipient Will See</param>
/// <param name="IsBodyHTML">Is Message Body HTML</param>
public static void SendEmail(List<string> addresses, string subject, string message, List<string> AttachmentLocations, string yourEmailAdress, string yourPassword, string yourName, bool IsBodyHTML)
{
try
{
string email = yourEmailAdress;
string password = yourPassword;
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email, yourName);
foreach (string address in addresses)
{
msg.To.Add(new MailAddress(address));
}
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = IsBodyHTML;
if (AttachmentLocations != null)
{
foreach (string attachment in AttachmentLocations)
{
msg.Attachments.Add(new Attachment(attachment));
}
}
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
catch { }
}
示例7: submitButton_Click
protected void submitButton_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(nameTextBox.Text) && !String.IsNullOrEmpty(emailTextBox.Text) && !String.IsNullOrEmpty(subjectTextBox.Text) && !String.IsNullOrEmpty(messageTextBox.Text))
{
try
{
string messageBody = String.Format("Name: {0}<br />Email: {1}<br />Subject: {2}<br />Message: {3}", nameTextBox.Text, emailTextBox.Text, subjectTextBox.Text, messageTextBox.Text);
MailMessage mailMessage = new MailMessage("[email protected]", "[email protected]", "Message From Riveu.com Website", messageBody);
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient("smtpout.secureserver.net");
NetworkCredential credentials = new NetworkCredential("[email protected]", "stonecold");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMessage);
nameTextBox.Text = String.Empty;
emailTextBox.Text = String.Empty;
subjectTextBox.Text = String.Empty;
messageTextBox.Text = String.Empty;
ScriptManager.RegisterStartupScript(this, GetType(), "MessageSuccess", "$( \"#dialog-message3\" ).dialog({modal: true,buttons: {Ok: function() {$( this ).dialog( \"close\" );}}});", true);
}
catch
{
ScriptManager.RegisterStartupScript(this, GetType(), "MessageFailed", "$( \"#dialog-message2\" ).dialog({modal: true,buttons: {Ok: function() {$( this ).dialog( \"close\" );}}});", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "ValidationFailed", "$( \"#dialog-message\" ).dialog({modal: true,buttons: {Ok: function() {$( this ).dialog( \"close\" );}}});", true);
}
}
示例8: Send
public void Send(string to, string subject, string body)
{
try
{
MailMessage mailMsg = new MailMessage();
// To
mailMsg.To.Add(new MailAddress(to));
// From
mailMsg.From = new MailAddress("[email protected]", "JoinIn");
// Subject and multipart/alternative Body
mailMsg.Subject = subject;
mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Plain));
//mailMsg.Attachments.Add(new Attachment(new MemoryStream(Attachment), AttachmentName));
// Init SmtpClient and send
var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
var credentials = new NetworkCredential("[email protected]", "ipxspx123");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
示例9: EnviarEmail2
private bool EnviarEmail2(string mensaje, string asunto, string destina)
{
string remitente = "[email protected]";
string passwordRemitente = "1234567890";
string destinatario = destina;
string servidor = "190.8.176.130";
int puerto = 25;
MailMessage objMail = new MailMessage(remitente, destinatario, asunto, mensaje);
NetworkCredential objNC = new NetworkCredential(remitente, passwordRemitente);
SmtpClient objsmtp = new SmtpClient(servidor, puerto);
objsmtp.EnableSsl = false;
objsmtp.UseDefaultCredentials = false;
objsmtp.Credentials = objNC;
try
{
objsmtp.Send(objMail);
return true;
}
catch (Exception e)
{
return false;
}
}
示例10: SendMail
public static bool SendMail(string toAddress, string fromAddress, string subject, string body)
{
try
{
var mailMsg = new MailMessage();
// To
mailMsg.To.Add(new MailAddress(toAddress));
// From
mailMsg.From = new MailAddress(fromAddress);
// Subject and multipart/alternative Body
mailMsg.Subject = subject;
mailMsg.Body = body;
mailMsg.IsBodyHtml = true;
// Init SmtpClient and send
var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
var credentials = new System.Net.NetworkCredential("[email protected]", "rb8t8vev");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
示例11: Contact
public async System.Threading.Tasks.Task<ActionResult> Contact(Email model)
{
ViewBag.Message = "Nice too meet you!";
if (ModelState.IsValid)
{
var body = "";
if (!string.IsNullOrEmpty(model.AboutProduct)) body = "<h2>Email From: {0} ({1})</h2></br><p>Message concerning {2}:</p><p>{3}</p>";
else body = "<h2>Email From: {0} ({1})</h2></br><p>Message:</p><p>{3}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("[email protected]"));
message.From = new MailAddress("[email protected]");
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.AboutProduct, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "[email protected]",
Password = "Ptaszysko04464"
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
return RedirectToAction("/Sent");
}
}
return View(model);
}
示例12: Add
// properties
// methods
/// <devdoc>
/// <para>Adds a <see cref='System.Net.NetworkCredential'/>
/// instance to the credential cache.</para>
/// </devdoc>
// UEUE
public void Add(Uri uriPrefix, string authType, NetworkCredential cred) {
//
// parameter validation
//
if (uriPrefix==null) {
throw new ArgumentNullException("uriPrefix");
}
if (authType==null) {
throw new ArgumentNullException("authType");
}
if ((cred is SystemNetworkCredential)
#if !FEATURE_PAL
&& !((string.Compare(authType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
|| (DigestClient.WDigestAvailable && (string.Compare(authType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
|| (string.Compare(authType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
|| (string.Compare(authType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
) {
throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authType), "authType");
}
++m_version;
CredentialKey key = new CredentialKey(uriPrefix, authType);
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");
cache.Add(key, cred);
if (cred is SystemNetworkCredential) {
++m_NumbDefaultCredInCache;
}
}
示例13: Authenticate
public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
{
lock (this.sessions)
{
NTAuthentication clientContext = this.sessions[sessionCookie] as NTAuthentication;
if (clientContext == null)
{
if (credential == null){
return null;
}
//
this.sessions[sessionCookie] = clientContext = new NTAuthentication(false, "WDigest", credential, spn, ContextFlags.Connection, channelBindingToken);
}
string resp = clientContext.GetOutgoingBlob(challenge);
if (!clientContext.IsCompleted)
{
return new Authorization(resp, false);
}
else
{
this.sessions.Remove(sessionCookie);
return new Authorization(resp, true);
}
}
}
示例14: SendMessage
public static void SendMessage(SmtpServer server, string from, string to, string subject, string content)
{
// compress Foe message and convert the compressed data to Base64 string
byte[] compressedData = Foe.Common.CompressionManager.Compress(Encoding.UTF8.GetBytes(content));
string based64 = Convert.ToBase64String(compressedData);
// send email
try
{
// create mail
MailMessage mail = new MailMessage(from, to, subject, based64);
// connect and send
SmtpClient smtp = new SmtpClient(server.ServerName, server.Port);
if (server.AuthRequired)
{
smtp.EnableSsl = server.SslEnabled;
smtp.UseDefaultCredentials = false;
NetworkCredential cred = new NetworkCredential(server.UserName, server.Password);
smtp.Credentials = cred;
}
smtp.Send(mail);
}
catch (Exception except)
{
throw except;
}
}
示例15: SendMail
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;
client.UseDefaultCredentials = false;
NetworkCredential credential = new NetworkCredential(_SMTPUsername, _SMTPPassword);
credential.GetCredential(client.Host, Port, AuthenticationType);
client.Credentials = credential;
message.ReplyTo = message.From;
try
{
client.Send(message);
}
catch(Exception err)
{
MMDBExceptionHandler.HandleException(err);
throw(err);
}
return true;
}