MVC Contact Form with Email

丶灬走出姿态 提交于 2019-11-30 09:36:22

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

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.

MD Luffy

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!