tags:

views:

293

answers:

2

I see different versions of the constructor, one uses info from web.config, one specifies the host, and one the host and port. But how do I set the username and password to something different from the web.config? We have the issue where our internal smtp is blocked by some high security clients and we want to use their smtp server, is there a way to do this from the code instead of web.config?

Ah wait is it like this? In this case how would I use the web.config ones if none is available from the database for example?

public static void CreateTestMessage1(string server, int port)
        {
            string to = "[email protected]";
            string from = "[email protected]";
            string subject = "Using the new SMTP client.";
            string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
            MailMessage message = new MailMessage(from, to, subject, body);
            SmtpClient client = new SmtpClient(server, port);
            // Credentials are necessary if the server requires the client 
            // to authenticate before it will send e-mail on the client's behalf.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
      }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateTestMessage1(): {0}", 
                    ex.ToString() );
      }              
        }
+4  A: 

Use NetworkCredential

Yep, just add these two lines to your code.

System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;
gmcalab
+8  A: 

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
pipelinecache
if I don't set one will it use the ones from web.config by default?
shogun
No it will be the DefaultNetworkCredentials if supplied or nothing.
pipelinecache