Show message "Email sending failed/successful" asp.net mvc 4 - asp.net

I have feedback form on my mvc site and I send this form to email.
In my controller I created ErrorMessage in case email sending is failed and SuccessMessage in case email sending is successful
/*Feedback*/
[HttpGet]
public ActionResult Feedback(string ErrorMessage)
{
if (ErrorMessage != null)
{
}
return View();
}
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
string ErrorMessage, SuccessMessage;
//email
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
msg.Priority = MailPriority.High;
msg.From = new MailAddress(Model.Email, Model.Name);
msg.To.Add("tayna-anita#mail.ru");
msg.Subject = #Resources.Global.Feedback_Email_Title + " " + Model.Company;
string message = #Resources.Global.Feedback_Email_From + " " + Model.Name + "\n"
+ #Resources.Global.Feedback_Email + " " + Model.Email + "\n"
+ #Resources.Global.Feedback_Phone + " " + Model.Phone + "\n"
+ #Resources.Global.Feedback_Company + " " + Model.Company + "\n\n"
+ Model.AdditionalInformation;
msg.Body = message;
msg.IsBodyHtml = false;
//Attachment
if (Model.ProjectInformation != null && !(String.IsNullOrEmpty(Model.ProjectInformation.FileName)))
{
HttpPostedFileBase attFile = Model.ProjectInformation;
if (attFile.ContentLength > 0)
{
var attach = new Attachment(attFile.InputStream, attFile.FileName);
msg.Attachments.Add(attach);
}
}
SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
try
{
client.Send(msg);
SuccessMessage = "Email sending was successful"
}
catch (Exception ex)
{
return RedirectToAction("Feedback", "Home", ErrorMessage = "Email sending failed");
}
return RedirectToAction("Feedback", "Home");
}
How can I add showing this messages in my view?

As you are redirecting to new page use the TempData , which will be available in next request after redirect. Put the message in TempData["Message"] and output in the Feedback view. To be more better check if
<% TempData["Message"] != null { %>
<%= TempData["Message"] %>;
<%} %>

Can't you try to access those as Model properties as follows:
<%= Model.ErrorMessage %>
<%= Model.SuccessMessage %>

use TempData.
You can use a TempDataDictionary object to pass data in the same way that you use a ViewDataDictionary object. However, the data in a TempDataDictionary object persists only from one request to the next, unless you mark one or more keys for retention by using the Keep method. If a key is marked for retention, the key is retained for the next request.
A typical use for a TempDataDictionary object is to pass data from an action method when it redirects to another action method. For example, an action method might store information about an error in the controller's TempData property (which returns a TempDataDictionary object) before it calls the RedirectToAction method. The next action method can then handle the error and render a view that displays an error message.
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
bool error = true;
if(error){
TempData["Message"] = "Error";
TempData["Error"] = true;
}
else{
TempData["Message"] = "Success";
TempData["Error"] = false;
}
return RedirectToAction("Feedback", "Home");
}
[HttpGet]
public ActionResult Feedback()
{
string message = TempData["Message"].ToString();
bool error = Convert.ToBoolean(TempData["Error"]);
var model = new FeedbackModel{Message = message, Error = error};
return View(model);
}

Related

email function not working after publishing to iis

I've published my app and it is now running from IIS. the problem is that the email function in my controller no longer works when running on IIS (the email function does not send email)
I have an email function on my mvc application and when I run it, it does send an email. The problem starts after I've published my app, Its running on IIS now but the email function does not send the email anymore. How do I go about fixing this?
[HttpPost]
public JsonResult SendMailToUser(string lt, string reason, string name, string fr, string ed)
{
bool result = false;
result = SendMail("ntulisakhile8#gmail.com", "Leave Reaquest", "Hi Sensei,<br />I would like to take a " + lt + " leave<br/><strong>From:</strong> " + fr + " <strong>To:</strong> " + ed + " <br/>Reason: " + reason + "<br/>Regards<br/>" + name + "<br/><a href=~/Response.html>Respond</a>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendMail(string toEmail, string subject, string emailBody)
{
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}

throw exception to change password in ASP.NET

i wanna ask again. How can i resolve this problem
Eror Picture
always find error, and i won't stop. I must be try with help from you guys.
after you look my error, this is my code:
using System;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Web.SessionState;
namespace FormsAuthAd
{
public class ChangePasswordPSI
{
public bool ChangePass(HttpSessionState Session, string OldPassword, string NewUPassword)
{
string Domain = Session["domain"].ToString();
string Username = Session["username"].ToString();
try
{
string ldapPath = "LDAP://MyDomain.com";
DirectoryEntry user = new DirectoryEntry(ldapPath, Domain + "\\" + Username, OldPassword);
if (user != null)
{
DirectorySearcher search = new DirectorySearcher(user);
search.Filter = "(SAMAccountName=" + Username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
object ret = user.Invoke("ChangeUserPassword", new object[] { OldPassword, NewUPassword });
user.CommitChanges();
return true;
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
}
}
can somebody tell me, what should i do?
thank you
If you are using try..catch and cannot find where exactly the exception occurred, delete try and catch and execute the code again. In your example, it might happen on Invoke("ChangeUserPassword"... - as far as I see the method name should be "ChangePassword"
https://msdn.microsoft.com/en-us/library/ms180896(v=vs.80).aspx

Confirmation email got Invalid token

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.

Catch exception in contact form

I'm going to create form contact in asp.net mvc 4. I have yet form in html and code in controller. And his looks like:
[HttpPost]
public ActionResult Kontakt(KontaktModel k)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(k.Mail.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myemail#gmail.com");
msg.Subject = k.Temat.ToString();
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
sb.Append("Nick / Imię i nazwisko: " + k.Name);
sb.Append(Environment.NewLine);
sb.Append("Typ problemu: " + k.TypProblemu);
sb.Append(Environment.NewLine);
sb.Append("Treść:");
sb.Append(Environment.NewLine);
sb.Append(k.Tresc);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("SUCCESS");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}
}
But when I clicked to button app return Error.cshtml. I have a question, how I can know how exception catched? I don't know why it does not work. Any ideas?
The answer should be to get the Exception Message and put inside a ViewBag.Message and show it in the Error.cshtml view.
Error:
#ViewBag.Message
But is good to know little more about Exception and Exception Handling. If you only declare a try catch and a exception happen it will go inside the catch is the same if you do try catch(Exception) if you want to know more detail about the exception is happening you can declare a variable, example :
try{
///code
}catch(Exception e){}
and then you can watch inside the variable for more detail.
The good practice is to know what type of exception you can receive and handle, here is a link that have a good explanation Exception and Exception Handling
Example:
try
{
//code
}
catch(Exception c)
{
ViewBag.Message = c.Message
return View("ERROR");
}

Show message “Email sending failed/successful” asp.net mvc 4 via ViewBag

I have feedback form on my mvc site and I send this form to email.
I'd like to show error message in case email sending is failed and success message in case email sending is successful. I try to make that via ViewBag.
I added in my controller
[HttpGet]
public ActionResult Feedback(string Message)
{
if (Message != null)
{
if (Message == "No")
{
ViewBag.Message = "Error";
}
if (Message == "Yes")
{
ViewBag.Message = "Success";
}
}
else
{
ViewBag.Message = null;
}
return View();
}
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
string Message;
//email
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
msg.Priority = MailPriority.High;
msg.From = new MailAddress(Model.Email, Model.Name);
msg.To.Add(/*"evaluation#corepartners.ru"*/"tayna-anita#mail.ru");
msg.Subject = #Resources.Global.Feedback_Email_Title + " " + Model.Company;
string message = #Resources.Global.Feedback_Email_From + ": " + Model.Name + "\n"
+ #Resources.Global.Feedback_Email + ": " + Model.Email + "\n"
+ #Resources.Global.Feedback_Phone + ": " + Model.Phone + "\n"
+ #Resources.Global.Feedback_Company + ": " + Model.Company + "\n\n"
+ Model.AdditionalInformation;
msg.Body = message;
msg.IsBodyHtml = false;
//Attachment
if (Model.ProjectInformation != null && !(String.IsNullOrEmpty(Model.ProjectInformation.FileName)))
{
HttpPostedFileBase attFile = Model.ProjectInformation;
if (attFile.ContentLength > 0)
{
var attach = new Attachment(attFile.InputStream, attFile.FileName);
msg.Attachments.Add(attach);
}
}
SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
try
{
client.Send(msg);
return RedirectToAction("Feedback", "Home", Message = "Yes");
}
catch (Exception ex)
{
return RedirectToAction("Feedback", "Home", Message = "No");
}
}
and I added in my view
#if (ViewBag.Message != null)
{
<p style="color: red;">#ViewBag.Message</p>
}
but I don't get any message in any case.
What's wrong?
Try this:
return RedirectToAction("Feedback", "Home", new { Message = "Yes" });

Resources