locked
Identity current user email as From address in a contact form RRS feed

  • Question

  • User251280784 posted

    Hello All

    A little project I am working on, need to send various different forms from the site. I need the forms to have the "From" address of the current logged in user. I am using Identity 2.0 for authentication and the standard "System.Net.Mail" namespace.

    In the controller I have:

        if (ModelState.IsValid)
        {
            var message = new MailMessage();
            message.To.Add(new MailAddress("email addresses"));  // these should also be variables coming from the database
            message.From = new MailAddress("current user email");  // set to the identity 2.0 current users email address.

    I can use:

    ApplicationUser user = UserManager.FindByName(userName);
    string mail= user.Email;

    to get the email address but now I'm kinda stuck on how to use that as a variable for the email form.

    Thanks. Any help would be appreciated!!

    Sunday, December 16, 2018 11:26 PM

Answers

  • User251280784 posted

    Really simple solution, in case anyone else has this question.

    At the controller method add:

    string userId = User.Identity.GetUserName();

    then use the "userID" for the variable:

    message.From = new MailAddress(userID);  // set to the identity 2.0 current users email address.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 17, 2018 1:37 PM

All replies

  • User251280784 posted

    Really simple solution, in case anyone else has this question.

    At the controller method add:

    string userId = User.Identity.GetUserName();

    then use the "userID" for the variable:

    message.From = new MailAddress(userID);  // set to the identity 2.0 current users email address.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 17, 2018 1:37 PM
  • User753101303 posted

    Hi,

    Not sure to see what is the problem in reusing the variable ie :

    new MailAddress(mail);

    The problem is with the To address ? Which data do you have for this user, it's User ID ? IMO don't use the UserName. For the default templates it is set to the mail address but this is not the general case. Do that only if this your current approach as well.

    Monday, December 17, 2018 1:45 PM
  • User1080785583 posted

    You want to return a View or Partial View with your model. Requires a strongly typed view model though.

    Example: var model = EmailObject();

                     model.Email = user.Email;

    return PartialView(model);

    Monday, December 17, 2018 6:14 PM