简体   繁体   中英

C# replace the mail from NetworkCredential

I have a contact form made with ASP.NET and C# and I want to replace the email from NetworkCredential with the one specified in the email field.

I will explain the issue with an example.

Here is my code:

public ActionResult Index(EmailFormModel vm)
{
    if (ModelState.IsValid)
    {
        MailMessage msz = new MailMessage();
        msz.From = new MailAddress(vm.Email); //Email which you are getting from contact us page 
        msz.To.Add("my-email@gmail.com"); //Where mail will be sent 
        msz.Subject = vm.Subject;
        msz.Body = vm.Message;
        SmtpClient smtp = new SmtpClient();

        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("my-email@gmail.com", "my-password");
        smtp.EnableSsl = true;
        smtp.Send(msz);

        ModelState.Clear();
    }

    return View();
}

View:

<% using (Html.BeginForm("Index", "SendMail", FormMethod.Post))
   {%>
        <%: Html.ValidationSummary("Please correct the errors and try again.") %>
        <p>Email: </p>
        <%: Html.TextBoxFor(m => m.Email)%>
        <p>Subject: </p>
        <%: Html.TextBoxFor(m => m.Subject)%>
        <p>Message: </p>
        <%: Html.TextBoxFor(m => m.Message)%>
        <input type ="submit" value ="Send" />
<% } %>

Example: When I send the email I want it to be sent from the address specified in vm.Email , not from my-email@gmail.com (the one from NetworkCredential), to `my-email@gmail.com.

Right now, if I try to send an email from valid-email@gmail.com to my-email@gmail.com the sender email is still my-email@gmail.com . Hope I made myself clear on the issue...please ask me if something is unclear :) .

您是否尝试过设置sender属性?

   msz.Sender = new MailAddress(vm.Email)

What you are doing is going to cause issues with Email Authentication and since you're using GMAIL it's going to be a real problem, they honor DMARC Records. A good percentage of the people filling out your contact us form, you will never receive the information from. You can no longer fill the "from" field with the customers email address with the inception of DMARC. In the past, it was an acceptable practice.

Take a look at this article: Contact Form Nightmare

The article shows a different approach on how to handle the situation that's being more popular, but I think you can also use the "reply-to:" field for the customers email, you definitely don't want to use the FROM field.

I urge you to re-think what you're trying to accomplish, because it's going to hinder your communications with your audience.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM