G_hi3
G_hi3

Reputation: 598

FQDN with SmtpClient in Powershell

I am using the .Net class System.Net.Mail.SmtpClient in Powershell to send a mail with some attached documents. It all works great in our test environment, but fails in production.

The problem is, that a fully specified domain name is required in production to send the mails. However the SmtpClient does not allow me to specify this, as far as I know. I've read online, that you can use web.config settings with asp.net to specify the domain name, but I don't seem to be able to use it with Powershell.

Is there a way around this or do I have to implement it in another language?

Edit: This is the code I'm using

$SmtpClient = New-Object System.Net.Mail.SmtpClient "mail.mailserver.com", 25
$Mail = New-Object System.Net.Mail.MailMessage

# Custom (working) Cmdlet for creating a NetworkCredential object
$SmtpClient.Credentials = (GetCredential-FromFile)

$Mail.Subject = "New Import"
$Mail.Body = ""
$Mail.From = "[email protected]"
$Mail.To.Add("[email protected]")
$Mail.Attachments.Add(New-Object System.Net.Mail.Attachment "file.txt")

$SmtpClient.Send($Mail)

The SMTP-Server is set, but I need to set the FQDN of the client (the machine using the script).

Upvotes: 1

Views: 2376

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

This is a bug (or missing feature, depending on how you want to look at it) in the .NET Framework implementation. By default the NetBIOS name of the host is used in the HELO command, and the SmtpClient class doesn't have a property for configuring the HELO hostname in the program/script. See here for a detailed discussion of the problem. You need to create/change a configuration file on the client to override the default.

Edit the file powershell.exe.config in the same directory where powershell.exe is located. Create the file if it doesn't exist. Make sure it contains at least the following lines:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="network">
        <network clientDomain="mail.example.com" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Replace mail.example.com with your client's FQDN.

For .NET Framework 2.0 you first need to apply a patch (or upgrade to .NET Framework 4.0 or newer) before you can configure the clientDomain attribute.

For more information on SMTP client network settings see here.

Had you posted your code and error message right from the start we would've been able to provide this answer much earlier.

Upvotes: 5

Related Questions