locked
Sending an email form but using the web.config RRS feed

  • Question

  • User-366561614 posted

    I am able to create an email form and send an email through this link: https://www.asp.net/web-pages/overview/getting-started/11-adding-email-to-your-web-site

    However, there is no security in it by leaving your credentials open on a .cshtml page. We currently use web forms and the smtp credentials are encrypted in the web.config. Is there any way to do this in ASP Web Pages too? I would feel more secure that way. 

    Wednesday, January 25, 2017 11:38 PM

All replies

  • User-1025250470 posted

    Hello Cyweb,

    You can try code behind method.

    SmtpClient smtpClient = new SmtpClient("Yourmailserver.com", 25);

    smtpClient.Credentials = new System.Net.NetworkCredential("youremail@yourdomainname.com", "yourpassword");
    smtpClient.UseDefaultCredentials = true;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtpClient.EnableSsl = true;
    MailMessage mail = new MailMessage();

    mail.From = new MailAddress("youremail@yourdomainname.com", "Your Name");
    mail.To.Add(new MailAddress("someone@somedomain.com"));

    smtpClient.Send(mail);

    Regards,

    Rajs

    Thursday, January 26, 2017 6:00 AM
  • User-366561614 posted

    Thank you. I did consider doing it with the code behind method but I don't want to define my credentials within the cshtml file for security reasons. 

    smtpClient.Credentials = new System.Net.NetworkCredential("youremail@yourdomainname.com", "yourpassword");

    Thursday, January 26, 2017 4:54 PM
  • User475983607 posted

    You can use the mailSettings node the web.config.

      <system.net>
        <mailSettings>
          <smtp deliveryMethod="network" deliveryFormat="SevenBit"  from="ben@contoso.com">
            <network
              host="localhost"
              port="25"
              password=""
              userName=""  />
          </smtp>
        </mailSettings>
      </system.net>

    Thursday, January 26, 2017 7:24 PM
  • User-366561614 posted

    Thank you to everyone who answered. There was a user who had posted something but deleted it but that was actually the solution. 

    The solution that ended up working for me was in my _appstart, I added:

    WebMail.SmtpServer = "smtp.server.net";
    WebMail.SmtpPort = 587;
    WebMail.UserName = ConfigurationManager.AppSettings["MailUser"];
    WebMail.Password = ConfigurationManager.AppSettings["MailPW"];
    WebMail.From = "name@email.com";

    I just added the below in the web.config and was able to encrypt that section:

    <appSettings>
    <add key="MailUser" value="username" />
    <add key="MailPW" value="password" />
    </appSettings>

    Thursday, January 26, 2017 8:24 PM
  • User475983607 posted

    FYI, the default constructor of the SmtpServer class reads the mailSetting node in the web.config by default.

    Thursday, January 26, 2017 8:31 PM