user1765862
user1765862

Reputation: 14155

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;[email protected]&gt;" >
      <network host="mail.test.com" userName="[email protected]" 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?

Upvotes: 0

Views: 2116

Answers (2)

ardila
ardila

Reputation: 1285

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="[email protected]" 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. […]

Upvotes: 2

Tejas R
Tejas R

Reputation: 9

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;
        }

Upvotes: 0

Related Questions