简体   繁体   中英

smtp client and accessing username and password from configuration code

If I have mail settings inside web.config

  <system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="&quot;testo&quot; &lt;admin@test.com&gt;" >
      <network host="mail.test.com" userName="admin@test.com" password="waiff75E-" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

and if I'm using following code to send mail from c# code

smtpclient.EnableSsl = false;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);

how can I configure here to username and password from above configuarion code?

Try adding the attribute defaultCredentials="false" to the network element so that it looks like:

<network host="mail.test.com" port="25" 
         defaultCredentials="false" 
         userName="admin@test.com" password="waiff75E-" />

The SmtpClient object will automagically initialize with whatever parameters you've specified in your configuration file (see the Remarks section in the MSDN article for the SmtpClient constructor ):

This constructor initializes the Host , Credentials , and Port properties for the new SmtpClient by using the settings in the application or machine configuration files. […]

Please refer this below code snippet and credentials will take care by webconfig Add defaultCredentials="false" in webconfig

 public bool SendSupportEmail(string fromMailID, string toMailID, string subject, string body)
        {

            bool brv = true;

            try
            {
                SmtpClient smtpClient = new SmtpClient();
                //smtpClient.EnableSsl = true;
                MailMessage message = new MailMessage();
                message.From = new MailAddress(fromMailID.ToString());
                message.To.Add(toMailID);
                message.Subject = subject;
                message.IsBodyHtml = true;
                message.Body = body;
                log.Info("From Addres-> " + fromMailID.ToString());
                log.Info("To Addres-> " + toMailID);
                smtpClient.Send(message);
            }
            catch (Exception ex)
            {
                log.Info("From Addres-> " + fromMailID.ToString());
                log.Info("To Addres-> " + toMailID);
                //log.Info("CC Addres-> " + EmailId);
                log.Error("Error:  " + ex.Message + "\nStrace: " + ex.StackTrace);
                brv = false;

            }
            return brv;
        }

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