FQDN with SmtpClient in Powershell

你说的曾经没有我的故事 提交于 2019-12-23 02:52:20

问题


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 = "myaddress@mailserver.com"
$Mail.To.Add("myaddress@mailserver.com")
$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).


回答1:


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.



来源:https://stackoverflow.com/questions/37410598/fqdn-with-smtpclient-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!