I search all way for use forgot passwrod on (youtube,docMicrosoft..) with no result . Please someone explain me the error and expose part by part the process forgotpassword from webconfig to identityConfig service . Thanks
this is the error :
Le serveur SMTP requiert une connexion sécurisée ou le client n'était pas authentifié. La réponse du serveur était : 5.5.1 Authentication Required. Learn more at
this is methode of controller :
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Ne révélez pas que l'utilisateur n'existe pas ou qu'il n'est pas confirmé
return View("ForgotPasswordConfirmation");
}
// Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
// Envoyer un message électronique avec ce lien
string Code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code= Code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Réinitialiser le mot de passe", "Réinitialisez votre mot de passe en cliquant ici");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
And this is my methode IndentyConfig :
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Credentials:
var credentialUserName = "morad21838#gmail.com";
var sentFrom = "morad21838#gmail.com";
var pwd = "95147823";
// Configure the client:
System.Net.Mail.SmtpClient client =
new System.Net.Mail.SmtpClient("smtp.gmail.com");
client.Port = 587;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
// Creatte the credentials:
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(credentialUserName, pwd);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail = new System.Net.Mail.MailMessage(sentFrom, message.Destination);
mail.Subject = message.Subject;
mail.Body = message.Body;
// Send:
return client.SendMailAsync(mail);
}
}
And this is my web.config :
</appSetting>
<system.net>
<mailSettings>
<smtp from="haniyac1#gmail.com">
<network host="smtp-relay.gmail.com"
port="587"
userName="haniyac1#gmail.com"
password="95147823" />
</smtp>
</mailSettings>
</system.net>
Hello I find solution and is work perfectly wish that help someone have the same error .
this is updated file :
IdentityConfig
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
SmtpClient client = new SmtpClient();
return client.SendMailAsync(ConfigurationManager.AppSettings["toEmail"],
message.Destination,
message.Subject,
message.Body);
}
}
Web.Config
<!--Smptp Server (confirmations emails)-->
<add key="toEmail" value="haniyac1#gmail.com" />
<add key="UserId" value="haniyac1#gmail.com" />
<add key="Password" value="95147823" />
<add key="SMTPPort" value="587" />
<add key="Host" value="smtp.gmail.com" />
> </appSettings>
> <appSettings>
> <system.net>
> <mailSettings>
> <smtp from="morad28138#gmail.com">
> <network host="smtp.gmail.com" userName="morad28138" defaultCredentials="false" password="95147823" port="587"
> enableSsl="true" />
> </smtp>
> </mailSettings>
Controller forgotPassword Method :
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Ne révélez pas que l'utilisateur n'existe pas ou qu'il n'est pas confirmé
return View("ForgotPasswordConfirmation");
}
// Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
// Envoyer un message électronique avec ce lien
string Code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code= Code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Réinitialiser le mot de passe", "Réinitialisez votre mot de passe en cliquant ici");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
return View(model);
}
Register : post
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
// Envoyer un message électronique avec ce lien
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrll = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, Code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirmez votre compte", "Confirmez votre compte en cliquant ici");
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
//await this.UserManager.AddToRolesAsync(user.Id, model.Roles);
return RedirectToAction("Index", "Home");
}
ViewBag.Roles = new SelectList(db.Roles.Where(a => !a.Name.Contains("Admins")), "Name", "Name");
AddErrors(result);
}
// Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
return View(model);
}
Hope that help
Related
I am using Google Sheets Api to read information from a sheet. Locally on Visual Studio, the code works properly, I am able to get all the information.
However when I implement my website on IIS I get the following error:
Error al enviar la solicitud (error occuring while sending the request)
The exception message is not very specific about what is happening and where.
I don't know if the IIS executed by Visual Studio has a different configuration and this is why is working locally.
This is my code
try {
string path = Server.MapPath("Updating");
ServiceAccountCredential credential;
string[] Scopes = { SheetsService.Scope.Spreadsheets };
string serviceAccountEmail = "account.com";
string jsonfile = Path.Combine(path, "cred.json");
using (Stream stream = new FileStream(jsonfile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = (ServiceAccountCredential)
GoogleCredential.FromStream(stream).UnderlyingCredential;
var initializer = new ServiceAccountCredential.Initializer(credential.Id)
{
User = serviceAccountEmail,
Key = credential.Key,
Scopes = Scopes
};
credential = new ServiceAccountCredential(initializer);
}
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String spreadsheetId = "1zkqBR9svQInKwM9hqPzrzhOFQB....";
string range = "Info!A:D";
string firmasRange = "Info!A:D";
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);
var response = request.Execute(); //It seems that the error happens here
IList<IList<Object>> values = response.Values;
sincronizeSheet(values);
}
This is the stacktrace
CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) en Google.Apis.Auth.OAuth2.ServiceAccountCredential.d__33.MoveNext() --- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción --- en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) en Google.Apis.Auth.OAuth2.TokenRefreshManager.d__12.MoveNext() --- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción --- en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) en Google.Apis.Auth.OAuth2.TokenRefreshManager.<g__LogException|10_0>d.MoveNext() --- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción --- en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() en Google.Apis.Requests.ClientServiceRequest`1.Execute() en Xerox_Mailroom.CoordinarCelular.ButtonSincronizar_Click(Object sender, EventArgs e)
For someone who is getting the same error the problem was pretty obvious, the connection with google api is made by the server, and it doesn't have internet access, so it never could validate the token.
I create a class with 3 parameters so as to populate and display a gridview.
this object is composed like this : string, string, list.
I managed to display the first and the second parameter, but not the third one, like this :
enter image description here
This is my main code :
protected void Page_Load(object sender, EventArgs e)
{
// Process principal
try
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
Liste_template = new List<TemplateObject>();
// Tant que le DataReader lit des informations.
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newTemplate = new TemplateObject(temp_id, temp_name, liste_id_form("Content", sdr));
Liste_template.Add(newTemplate);
}
}
gv.DataSource = Liste_template;
gv.DataBind();
}
finally
{
connect.Close();
}
}
// Méthode pour délimiter chaque chaque chaine de caractères à partir des symboles dans le tableau delimiterChars.
public string[] RecupChaines(string chaine)
{
char[] delimiterChars = { ';', '&', '=', '"' };
string[] words = chaine.Split(delimiterChars);
return words;
}
// Méthode de récupération des Id des Form dans le champs Content de la table Template.
public List<String> liste_id_form(string field, SqlDataReader sdr)
{
List<string> listIdForm = new List<string>();
// enregistrement du contenu du champs Content dans une variable
string content = sdr[field].ToString();
// Tentative de séparation des deux parties de la chaine de caracteres
string chaineACouper = "<Property Name=\"Description\" Value=\"\" />";
string[] chaineArrive = content.Split(new string[] { chaineACouper }, StringSplitOptions.None);
chaineArrive[0] += chaineACouper;
// Séparation des deux parties.
string stringPartOne = chaineArrive[0];
string stringPartTwo = chaineArrive[1];
// Récuperation de la liste des valeurs des FormId de la chaine de caractères
string[] words = RecupChaines(stringPartTwo);
for (int i = 0; i < words.Length; i++)
{
if (words[i].Equals("FormId"))
{
listIdForm.Add(words[i + 5]);
}
}
return listIdForm;
}
}
I don't know how to loop on list_id_form, so as to display it on my gridview. For information, my class has an id, a name, and a list of datas.
I have to work with strings, because the datas from the database is not correctly stored. I don't have hand on this and i can't modify this.
I would like to store some datas from a database to a list of a class.
Unfortunatly, my webpage is totally blank and totally emply...
This my code :
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Process principal
try
{
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
sdr.Read();
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
List<TemplateObject> Liste_template = new List<TemplateObject>()
{
new TemplateObject(temp_id,temp_name)
};
}
GridView1.DataSource = Liste_template;
GridView1.DataBind();
}
finally
{
connect.Close();
}
}
Code from the Class i created :
public class TemplateObject
{
string Id_template { get; set; }
string Name_template { get; set; }
public TemplateObject(string id, string name)
{
this.Id_template = id;
this.Name_template = name;
}
}
I would like to store and display an object which is composed of one TemplateObject and one FormObject, composed with two parameters (as TemplateObject) : id and name. I d'ont create the FormObject, because i'm starting with one at first.
I have to store my datas like this, beacause the datasource is a bit weird and i only work with strings.
You need a loop
create the list before that loop
fill the list in the loop
List<TemplateObject> Liste_template = new List<TemplateObject>()
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newObject = new TemplateObject(temp_id,temp_name);
Liste_template.Add(TemplateObject)
}
Now you can assign it as DataSource of the GridView:
GridView1.DataSource = Liste_template;
GridView1.DataBind();
I am using the default ASP.NET AccountController any idea why the confirmation mail is entering spam folder in my gmail? the app is configured to send from gmail account
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Comment the following line to prevent log in until the user is confirmed.
// await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Currency Protector - Confirm your account", "Please confirm your account by clicking here");
ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
+ "before you can log in.";
return View("Info");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
EDIT
Here is my mail class
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("XXX#gmail.com");
mail.To.Add(message.Destination);
mail.Subject = message.Subject;
mail.Body = message.Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("XXX#gmail.com", "PASS");
return smtp.SendMailAsync(mail);
}
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());
}
}