1

I would like to send an email via PowerShell using nuget package called MailKit. After downloading it along with all of the package dependencies (I managed to go over the loop dependency issues) I have created a script which I hoped will send the email I wanted:

Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\MimeKit.2.15.1\lib\net50\MimeKit.dll"
Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\MailKit.2.15.0\lib\net50\MailKit.dll"

$SMTP     = New-Object MailKit.Net.Smtp.SmtpClient
$Message  = New-Object MimeKit.MimeMessage

$TextPart = [MimeKit.TextPart]::new("plain")
$TextPart.Text = "MailKit test message"
$Message.From.Add("user1@domain.com")
$Message.To.Add("user2@domain.com")
$Message.Subject = 'Test'
$Message.Body = $TextPart
$SMTP.Connect('172.xx.xx.x', 25, $False)
$SMTP.Send($Message)
$SMTP.Disconnect($true)
$SMTP.Dispose()

Once I execute the above it fails with

MethodInvocationException: Exception calling "Send" with "1" argument(s): "relay not permitted"

The SMTP server is in-house, no firewall in between and most importantly no user/password required for the authentication. PowerShell version I use is 7.1.4

I know that the SMTP server works just fine, as I actively use it with some 3rd party apps which simply worked out of the box once I pointed then to the correct IP and port.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Bartosz X
  • 2,620
  • 24
  • 36
  • 1
    The error message suggests that authentication is required. That error message is coming from your server, not MailKit. If you believe you do not need to authenticate, you need to confirm that with your server admin. – jstedfast Sep 15 '21 at 15:45
  • The error message is straightforward - the mail server you are trying to send to does not allow relaying. As the previous comment noted, this error comes from the SMTP server you are trying to relay mail through, not PowerShell. – Bill_Stewart Sep 15 '21 at 15:46
  • 1
    Some systems that are setup with no authentication use other methods such as IP address, FROM email address, etc. Ask the mail admin if your IP address is whitelisted and/or if there are any other requirements to connect to the mail server. The mail server thinks you are **relaying** email. Now you must figure out why. – John Hanley Sep 15 '21 at 23:12
  • Thank you all for your comments. Thanks to your directions I have found the issue - the IP address I used was not whitelisted for using the SMTP. From the right source if works just as I hoped it would on the begeining! Really appreciate pointing me in the right direction. – Bartosz X Sep 16 '21 at 10:46
  • @BartoszX Please consider adding your solution to the question. Any reason why you didn't go for the builtin cmdlet, Send-MailMessage? – Dennis Sep 16 '21 at 17:35

0 Answers0