Discipulos
Discipulos

Reputation: 469

PowerShell error on sending e-mail

I have the following Powershell script that I would use to send an e-mail:

$smtpServer = "smtp.live.com"
$smtpPort = "465"
$credential = [Net.NetworkCredential](Get-Credential)

$smtpClient = New-Object System.Net.Mail.SmtpClient $smtpServer, $smtpPort
$smtpClient.EnableSsl=$true
$smtpClient.UseDefaultCredentials=$false
$smtpClient.Credentials= $credential

$smtpTo = "[email protected]"
$smtpFrom = "[email protected]"
$messageSubject = "Testing Mail" 
$messageBody = "Hi, This is a Test"

$message = New-Object System.Net.Mail.MailMessage $smtpFrom, $smtpTo, $messageSubject, $messageBody

try
{
  $smtpClient.Send($message)
  Write-Output "Message sent."
}
catch
{
  $_.Exception.Message
  Write-Output "Message send failed."
}

But I receive this error:

+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,mail.ps1

Exception calling "Send with "1" arguments" Failure Sending mail

What is wrong whit this code?

Upvotes: 0

Views: 9853

Answers (2)

Petar Marinković
Petar Marinković

Reputation: 126

You haven't defined $smtpFrom (address from which the e-mail is sent). Also, just a suggestion, why don't you use Send-MailMessage cmdlet, it's available from PowerShell 2.0

This code works for me without any issues with smtp.live.com and port 587 with SSL

$SmtpServer = 'smtp.live.com'
$SmtpUser = '[email protected]'
$smtpPassword = 'your_password'
$MailTo = '[email protected]'
$MailFrom = '[email protected]'
$MailSubject = "Test using $SmtpServer" 
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -AsPlainText -Force) 
Send-MailMessage -To "$MailTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -Credential $Credentials -UseSsl -Port 587 

Upvotes: 3

Discipulos
Discipulos

Reputation: 469

I solved changing port to 25. But why I can't use IMAP ?

Upvotes: 1

Related Questions