I have a site online, its not finished..
my problem is at the bottom "contact-us" forum.
its not sending any mail..
*in my local host it is working and i have no idea what is the different
java script code for sending the mail:
function sendEmail_click() {
if (Page_ClientValidate()) {
// $("#LoadingImage").show(); //Show loading image
var settings = {
'data': getData(),
'url': "Handlers/SendMail.ashx",
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8'
};
sendEmail(settings);
};
}
function getData() {
var data = {
'firstName': $('#txt_fName').val(),
'lastName': $('#txt_lName').val(),
'phone': $('#txt_phone').val(),
'bName': $('#txt_bName').val(),
'fromMail': $('#txt_email').val(),
'Message': $('#txt_message').val(),
'checkBox': $('#chk_ad').prop('checked')
};
return data;
}
function showOrHideLoadingImage(id, action) {
if (action == "show") {
$("#" + id).show();
} else {
$("#" + id).hide();
}
}
function sendEmail(settings) {
var success = false;
showOrHideLoadingImage("LoadingImage", "show");
$.ajax({
type: "POST",
contentType: settings.contentType,
data: settings.data,
url: settings.url,
dataType: "json",
success: function (data) {
$('#checkMark').css('display', 'inline').fadeOut(20000); //Show check mark image+text
$(".contact_input").each(function () {
$(this).val("");
})
success = true;
},
error: function (data) {
$('#xMark').css('display', 'inline').fadeOut(12000); //Show xMark image+text
success = false;
}
}).always(function () {
showOrHideLoadingImage("LoadingImage", "hide");
});
return success;
}
Handler:
public void ProcessRequest (HttpContext context) {
//add try catch
// Loads parameters into variables
string firstName = context.Request.Form.Get("firstName");
string lastName = context.Request.Form.Get("lastName");
string phone = context.Request.Form.Get("phone");
string bName = context.Request.Form.Get("bName");
string senderEmail = context.Request.Form.Get("fromMail");
string message = context.Request.Form.Get("message");
string chkBox_ad = context.Request.Form.Get("checkBox");
bool mailSent = Mail.SendEmail(firstName, lastName, bName, phone, senderEmail, message, chkBox_ad);
context.Response.ContentType = "text/plain";
if (mailSent)
{
context.Response.Write("true");
}
else
{
context.Response.Write("false");
}
}
Send mail function:
public static bool SendEmail(string firstName, string lastName, string bName, string phone, string senderEmail, string message, string chkBox_ad)
{
chkBox_ad = chkBox_ad == "true" ? "..." : "...";
// Email sending
string eBody = "...";
eBody += "...";
eBody += "...";
eBody += "...";
eBody += "...";
eBody += "...";
MailMessage MyMailMessage = new MailMessage("XXX#gmail.com", "XXX#gmail.com", "smbJob", eBody);
MyMailMessage.IsBodyHtml = true;
try
{
SmtpClient SMTPServer = new SmtpClient();
SMTPServer.Send(MyMailMessage);
return true;
}
catch
{
return false;
}
}
I am not sure if this is the exact code you need but it should get you going in the correct direction. Make sure you are using the correct using directive as well.
System.Net.Mail.MailMessage mail =
new System.Net.Mail.MailMessage("xxx#gmail.com", "xxx#gmail.com");
try
{
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.Credentials = new System.Net.NetworkCredential()
{
UserName = "someemail#address.com",
Password = "password"
};
client.EnableSsl = true;
}
catch
{
display some error from here
}
for anyone having that issue, I managed to solve it:
1) this is the right web.config setting(replace "info#yourDomainName.com" with your "goDaddy" email address
<system.net>
<mailSettings>
<smtp from="info#yourDomainName.com">
<network host="relay-hosting.secureserver.net" port="25"/>
</smtp>
</mailSettings>
As I understand, "goDaddy" dont allow sending mails from third-party accounts, like gmail(after live chatting with them), dont have to write user name & passowrd and its not through SSL.
your from address should be your "goDaddy" email address
Related
I can not do how to implement google recaptcha v3 in Contact us webform in ASP .NET(not in MVC).
please help me to short out this problem.
In the ASPX page put the following code at the top after the <asp:Content ID="Content2" ContentPlaceholderID="maincontent" runat="server">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function popup() {
swal({
title: "Successful!",
text: "Your enquiry is submitted. Thank you for contacting us.",
icon: "success",
button: "Ok",
});
}
function popupservererror() {
swal({
title: "Server Error!",
text: "Server error ! Try again later.",
icon: "error",
button: "Ok",
});
}
function errorcaptcha() {
swal({
title: "Catcha Error!",
text: "Captch error ! Try again later.",
icon: "error",
button: "Ok",
});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script> /*Site Key*/ /*6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_*/
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) {
document.getElementById("<%=hf_token.ClientID%>").value = token;
});
});
</script>
<script src="http://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) { //6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_//
$.ajax({
type: "POST",
url: "Default.aspx/SetToken",
data: JSON.stringify({ _token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<script src="js/main.js"></script>
And now see the below code for ASPX.CS page for the actions.
using App.BAL.Master;
using App.BAL.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
namespace Supplychain_cms.contact
{
public partial class index : System.Web.UI.Page
{
private string recaptchaSecret = "6LfYRxseAAAAAKu__YvhSPEQVJBVunOeeutWN8ro"; /*Secret Key --- 6LerAgceAAAAAM7gGAKouqHnz7w9KwrI25OnIjyw*/
private string Token = string.Empty;
private ResponseToken response = new ResponseToken();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Submit_click(object sender, EventArgs e)
{
try
{
if (CaptchaVerify().Success)
{
string to_username = ConfigurationManager.AppSettings["to_username"].ToString();
string form_username = ConfigurationManager.AppSettings["form_username"].ToString();
string form_password = ConfigurationManager.AppSettings["form_password"].ToString();
string smtpAddress = "smtppro.zoho.in";
int portNumber = 587;
bool enableSSL = true;
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactmail.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
template = template.Replace("EMAILID", txt_Email.Value);
template = template.Replace("MESSAGE", txt_Message.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(to_username);
mail.Subject = "New appointment query from " + txt_Name.Value + " for SuplyChain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactreply.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(txt_Email.Value);
mail.Subject = "Thank you for contacting on Supply Chain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "popup();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "errorcaptcha();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(GetType(), "popupservererror", "popupservererror(); console.log('" + ex.Message + "');", true);
}
}
public ResponseToken CaptchaVerify()
{
//It should only call once
if (response.score == 0)
{
Token = hf_token.Value;
var responseString = RecaptchaVerify(Token);
response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
}
return response;
}
private string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
private async Task<string> RecaptchaVerify(string recaptchaToken)
{
string url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
using (HttpClient httpClient = new HttpClient())
{
try
{
string responseString = httpClient.GetStringAsync(url).Result;
return responseString;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
public class ResponseToken
{
public DateTime challenge_ts { get; set; }
public float score { get; set; }
public List<string> ErrorCodes { get; set; }
public bool Success { get; set; }
public string hostname { get; set; }
}
}
}
Now go the Web.config file for Database connection.
<connectionStrings>
<add name="CON_NAME" connectionString="Data Source=localhost;
Initial Catalog=db_SUPPLY_CHAIN; User ID=sa;
Password=jagannath29" providerName="System.Data.SqlClient" />
</connectionStrings>
I'm kinda new to using AJAX call to a WebMethod. I feel my Web Method logic is but maybe someone could help out here. I do get an unknown web method error when I log the AJAX response to the console. Below is my Web method and AJAX call code.
$("#btnLogin").click(function () {
email = $("#txtEmailAddress").val();
password = $("#txtPassword").val();
//Create the login info object
var loginInfo = {};
//Set the object properties and value
loginInfo.Email = email;
loginInfo.Password = password;
//Make the ajax call
$.ajax({
type: "POST",
dataType: 'json',
url: '<%=ResolveUrl("identicate.aspx/ValidateUsersToken") %>',
data: '{loginInfo:' + JSON.stringify(loginInfo) + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d == null || data.d == undefined)
{
alert("Username or password not correct = " + data.d);
console.log(data);
console.log(loginInfo);
console.log(this.url);
}
},
error: function (data) {
console.log(data);
console.log(loginInfo);
console.log(this.url);
alert(data.d);
}
});
});
And here's my web method
[WebMethod]
public static String ValidateUsersToken(iloginmodel loginInfo)
{
//Variable to hold the user email address
String email = string.Empty;
//Get the connection string from config file
String connectionString = iDbConfiguration.GetConnectionString();
//Create the command text
String commandText = "select Email, Password from VUser where Email = #Email & Password = #Password";
//Create database connection object and open it
using(SqlConnection loginConnection = new SqlConnection(connectionString))
{
//Set command paramters
SqlCommand loginCommand = new SqlCommand(commandText, loginConnection);
//Set command type to text
loginCommand.CommandType = System.Data.CommandType.Text;
//Add parameter to command
loginCommand.Parameters.AddWithValue("Email", loginInfo.Email);
loginCommand.Parameters.AddWithValue("#Password", loginInfo.Password);
//Open the database connection
try
{
loginConnection.Open();
SqlDataReader loginReader = loginCommand.ExecuteReader();
if(loginReader.HasRows)
{
HttpContext.Current.Response.Write(loginReader.ToString());
while (loginReader.Read())
{
if (loginReader.HasRows)
{
email = loginReader["Email"].ToString();
}
}
}
}
catch(SqlException sqlEx)
{
HttpContext.Current.Response.Write(sqlEx.Message);
}
finally
{
loginConnection.Close();
}
}
return email;
}
I'm adding confirmation email feature to my ASP.NET WebAPI project. The server can send email fine, however, the confirmation link always return "Invalid token".
I checked some reasons as pointed out here
http://tech.trailmax.info/2015/05/asp-net-identity-invalid-token-for-password-reset-or-email-confirmation/
but it seems that none of them is the root cause
Below is my code:
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
try
{
await userManager.AddToRoleAsync(user.Id, "Player");
//Generate email confirmation token
//var provider = new DpapiDataProtectionProvider("GSEP");
var provider = new MachineKeyProtectionProvider();
userManager.UserTokenProvider = new DataProtectorTokenProvider<GSEPUser>(provider.Create("EmailConfirmation"));
var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
code = System.Web.HttpUtility.UrlEncode(code);
EmailHelper emailHelper = new EmailHelper();
string callBackUrl = emailHelper.GetCallBackUrl(user, code);
EmailMessage message = new EmailMessage();
message.Body = callBackUrl;
message.Destination = user.Email;
message.Subject = "GSEP Account confirmation";
emailHelper.sendMail(message);
}
catch (Exception e)
{
return Ok(GSEPWebAPI.App_Start.Constants.ErrorException(e));
}
}
And now is EmailHelper
public class EmailHelper
{
public string GetCallBackUrl(GSEPUser user, string code)
{
var newRouteValues = new RouteValueDictionary(new { userId = user.Id, code = code });
newRouteValues.Add("httproute", true);
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
string callbackUrl = urlHelper.Action(
"ConfirmEmail",
"Account",
newRouteValues,
HttpContext.Current.Request.Url.Scheme
);
return callbackUrl;
}
public void sendMail(EmailMessage message)
{
#region formatter
string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
string html = "Please confirm your account by clicking this link: link<br/>";
html += HttpUtility.HtmlEncode(#"Or click on the copy the following link on the browser:" + message.Body);
#endregion
MailMessage msg = new MailMessage();
msg.From = new MailAddress("myemail#example.com");
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail#example.com", "mypassword!");
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
}
}
And 2 MachineKey class
public class MachineKeyProtectionProvider : IDataProtectionProvider
{
public IDataProtector Create(params string[] purposes)
{
return new MachineKeyDataProtector(purposes);
}
}
public class MachineKeyDataProtector : IDataProtector
{
private readonly string[] _purposes;
public MachineKeyDataProtector(string[] purposes)
{
_purposes = purposes;
}
public byte[] Protect(byte[] userData)
{
return MachineKey.Protect(userData, _purposes);
}
public byte[] Unprotect(byte[] protectedData)
{
return MachineKey.Unprotect(protectedData, _purposes);
}
}
I also added machineKey tag in Web.config as some instruction pointed out.
And finally is my confirmation email API
[AllowAnonymous]
[HttpGet]
public async Task<IHttpActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return Ok("Confirm error");
}
IdentityResult result;
try
{
result = await UserManager.ConfirmEmailAsync(userId, code);
}
catch (InvalidOperationException ioe)
{
// ConfirmEmailAsync throws when the userId is not found.
return Ok("UserID not found");
}
if (result.Succeeded)
{
return Ok("Confirmation succesfully");
}
else
{
return Ok(result.Errors);
}
}
Please show me where am I go wrong
I know this is an old thread. But I though of adding the answer as it could help others.
You are using the below code
string callbackUrl = urlHelper.Action(
"ConfirmEmail",
"Account",
newRouteValues,
HttpContext.Current.Request.Url.Scheme
);
and the UrlHelper.Action already does the url encoding for you in the latest MVC versions. So here in your code you are doing the encoding twice (one inside the Register and another inside GetCallBackUrl using urlHelper.Action) and that is why you are getting the invalid token error.
I wonder if someone can please help with a MVC Contact Form which send an Email on submission? I think I have most elements setup, but for some reason the form appear to be sending (takes ages) then just returns back to the form and no email is received.
MailModels.cs:
namespace WebApplication1.Models
{
public class MailModels
{
public string Name { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Message { get; set; }
}
}
Contact.cshtml:
#using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #id = "contact-form", role = "form" }))
{
#Html.ValidationSummary()
<fieldset>
<div class="form-div-1">
<label class="name">
#Html.TextBoxFor(m => m.Name, new { #placeholder = "Name *", #type = "text" })
</label>
</div>
<div class="form-div-2">
<label class="email">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Email Address *", #type = "email" })
</label>
</div>
<div class="form-div-3">
<label class="phone notRequired">
#Html.TextBoxFor(m => m.Telephone, new { #placeholder = "Telephone Number", #type = "text" })
</label>
</div>
<div>
<label class="message">
#Html.TextAreaFor(m => m.Message, new { #placeholder = "Message *" })
</label>
</div>
<div class="button-wrapper">
<input type="submit" value="Send" name="submit" class="button"> <input type="reset" value="Reset" name="MFReset" class="button"><span>* Required Fields</span>
</div>
</fieldset>
}
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using WebApplication1.Models;
using System.Text;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Contact()
{
ViewBag.Message = "Test Form";
return View();
}
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
MailAddress from = new MailAddress(e.Email.ToString());
message.Append("Name: " + e.Name + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n");
message.Append(e.Message);
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.mail.yahoo.com";
smtp.Port = 465;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("yahooaccount", "yahoopassword");
smtp.Credentials = credentials;
smtp.EnableSsl = true;
mail.From = from;
mail.To.Add("yahooemailaddress");
mail.Subject = "Test enquiry from "+e.Name;
mail.Body = message.ToString();
smtp.Send(mail);
}
return View();
}
Banging my head against a brickwall with this one, any help would be much appreciated :-)
Sending an email will take time. It should be a thread. Put your code in a function. And make the following changes:
public void SendEmail(string toAddress, string fromAddress,
string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username#yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Call that function in your controller:
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
//prepare email
var toAddress = "someadress#yahoo.co.uk";
var fromAddress = e.Email.ToString();
var subject = "Test enquiry from "+ e.Name;
var message = new StringBuilder();
message.Append("Name: " + e.Name + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n");
message.Append(e.Message);
//start email Thread
var tEmail = new Thread(() =>
SendEmail(toAddress, fromAddress, subject, message));
tEmail.Start();
}
return View();
}
If you dont get email, check your spam folder
You need to implement Producer Consumer pattern for this use case. You will have to have one thread running dedicated to emails. This thread will read from the queue & send emails. In the contact method, you will just add to the queue. Its not a good idea to do time consuming operations in controller methods.
C# producer/consumer
settings to web.config
<system.net>
<mailSettings>
<smtp from="you#outlook.com">
<network host="smtp-mail.outlook.com"
port="587"
userName="you#outlook.com"
password="password"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
Port 465 or 587?
Lots of code samples for Gmail feature port 465 but most people cannot get this to work. When they revert to port 587, their email suddenly works. According to Gmail's documentation SSL is required if you specify port 465. Many people think that setting EnableSsl to true achieves this, but in fact, it means that your app must be running under https. When you set EnableSsl to true, you actually switch TLS on, which is required for port 587. Https is not supported by the SmtpClient object. For more details, read the Remarks section of the docs on MSDN.
public void SendEmail(string toAddress, string fromAddress,string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username#yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex chor gai )
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusye ||
status == SmtpStatusCode.MailboxUnavailableee)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.Toread());
}
}
I have hosted a Windows Web API using a basic authentication header with username and password.
I'm trying to create a login form that takes a username and password and sends back a token.
so i have the following code.
I'm using a Attributed method
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
private IPromiseRepository promiseRepository;
public BasicAuthenticationAttribute()
{
this.promiseRepository = new EFPromiseRepository(new PropellorContext());
//repository = promiseRepository;
}
public BasicAuthenticationAttribute(IPromiseRepository promiseRepository, INewsFeedRepository newsfeedRepository)
{
this.promiseRepository = promiseRepository;
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = authToken;
// Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
string password = decodedToken.Substring(decodedToken.IndexOf("^")+1);
string APIToken = decodedToken.Substring(decodedToken.IndexOf("="));
APIToken = APIToken.Replace("=", string.Empty);
password = password.Replace("=", string.Empty);
if (!string.IsNullOrEmpty(APIToken))
{
password = password.Replace(APIToken, string.Empty);
}
if (username != null && password != null)
{
try
{
var user = promiseRepository.GetUserByName(username);
var salt = user.PasswordSalt;
System.Security.Cryptography.SHA512Managed HashTool = new System.Security.Cryptography.SHA512Managed();
Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(password, salt));
Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
HashTool.Clear();
var hashedpass = Convert.ToBase64String(EncryptedBytes);
if (hashedpass == user.Password)
{
if (string.IsNullOrEmpty(user.APIToken))
{
String guid = System.Guid.NewGuid().ToString();
user.APIToken = guid;
promiseRepository.UpdateUser(user);
promiseRepository.Save();
}
if (user != null)
{
user = promiseRepository.GetUserByUserID(user.UserID);
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(user), new string[] { });
base.OnActionExecuting(actionContext);
}
}
if (APIToken != null)
{
if (user.APIToken == APIToken)
{
var userbytoken = promiseRepository.GetUserByAPIToken(APIToken);
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(userbytoken), new string[] { });
base.OnActionExecuting(actionContext);
}
}
}
catch (Exception)
{
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
base.OnActionExecuting(actionContext);
}
throw;
}
}
}
}
}
This works with Fiddler when the correct credentials are passed
I'm attempting to produce the same authentication in my windows phone application.
Passes a username and password into the basic authentication http header.
However I'm not sure how to do this after a large amount of diggging on the internet alot of the exmaples are windows phone 7 and certain methods don't exist anymore.
This is the code i have arrived at.
private void Login1_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:5650/api/start");
NetworkCredential credentials = new NetworkCredential(userName.Text + ":^",password.Text + "=");
request.Credentials = credentials;
request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);
Hopefully someone can guide me into the right direction.
it should be simple in principle :(
Here is a sample using HttpClient:
public static async Task<String> Login(string username, string password)
{
HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(StringToAscii(string.Format("{0}:{1}", username, password))));
var response = await Client.GetAsync(new Uri(new Uri("http://yourdomain.com"), "/login"));
var status= await response.Content.ReadAsAsync<String>();
return status;
}
And of course you can find the ToBase64String function on the internet. The tricky part here is the Authorization header.