189

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?

In this case how would I use the web.config credentials 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());
    }              
}

5 Answers 5

350

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
6
  • if I don't set one will it use the ones from web.config by default?
    – MetaGuru
    May 4, 2010 at 16:43
  • 3
    @pipelinecache Ryan is right, if no credentials supplied it will look at <system.net><mailSettings> in web.config
    – Tomas
    Feb 3, 2012 at 12:03
  • 2
    I believe if UseDefaultCredentials is set to true it will use the defaults, otherwise it will first look in Credentials property and then in the web.config. If none are set it will send the email anonymously. Jun 18, 2013 at 10:36
  • 1
    Is it safe to hard code username and password in c# code?
    – kudlatiger
    Jan 4, 2017 at 6:15
  • 5
    Warning: If you set 'UseDefaultCredentials = false' you must do it BEFORE setting Credentials, as the change nulls any existing credentials set.
    – WhoIsRich
    Aug 15, 2017 at 14:33
36

Use NetworkCredential

Yep, just add these two lines to your code.

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

client.Credentials = credentials;
1
  • 11
    why not just one line?
    – JSON
    Oct 30, 2018 at 17:03
9
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
5
  • 5
    you should try posting only relavent code to the answer
    – johnny 5
    Feb 9, 2016 at 21:48
  • 3
    @johnny5 context isn't the biggest crime in the world
    – Shiv
    Jun 27, 2018 at 0:21
  • @shiv you’re correct, but a context would be writing an explanation of the answer, which also isn’t here.
    – johnny 5
    Jun 27, 2018 at 0:29
  • 1
    @johnny5 the other top answers don't have explanations - the example is pretty self explanatory as the code is self documenting.
    – Shiv
    Jun 27, 2018 at 0:36
  • 1
    @Shiv the top answers are self documenting because they post only the relevant code. My original comment has just as many upvotes as this answer, for a reason, I don’t see why I would have to sift though 15 lines of code, when only 2 are needed to answer this question, if you found this answer useful, upvote it. Otherwise, these no point in arguing about a comment I made 2 years ago which other found was useful
    – johnny 5
    Jun 27, 2018 at 0:45
0

There are a couple of things not mentioned in other answers.

First, it can be necessary to use CredentialCache instead of NetworkCredential directly, in order to specify different authentication schemes.

In the documentation, the SMTP authentication type names are listed as:

"NTLM", "Digest", "Kerberos", and "Negotiate"

However I had to breakpoint within the .NET code to see that the value being passed for "AUTH LOGIN" was actually "login". This seems to happen automatically anyway, so this is only necessary to use different schemes.

Second, though no one here is, you probably do NOT want to specify a domain name in your NetworkCredential. Doing so results in SmtpClient passing a username of the form example.com\username which is almost guaranteed to not be accepted by a mail server. (And if your mail server is loose with its authentication requirements, you may not know that you are failing to authenticate.)

var nc = new NetworkCredential(
   username,
   password
   // no domain!
);

// only if you need to specify a particular authentication scheme,
// though it doesn't hurt to do this anyway if you use the right scheme name
var cache = new CredentialCache();
cache.Add(smtpServerName, port, "NTLM", nc);
// can add more credentials for different combinations of server, port, and scheme

smtpClient.Credentials = cache;

Lastly, note that you do not need to set UseDefaultCredentials if you are also setting Credentials as they are both based on the same underlying value. Setting both can lead to issues since they will just overwrite each other.

If in doubt, use WireShark and disable SSL temporarily (to see the network frames or else they are encrypted), and confirm that your SMTP authentication is working. (Use an "smtp" filter in WireShark).

1
-3

Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.

Here is the VB code:

sSMTPUser = ConfigurationManager.AppSettings("SMTPUser")
sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword")

If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then
    NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword)

    sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes
End If

NetClient.Send(Message)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.