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 = "existing_email#hotmail.com"
$smtpFrom = "email#hotmail.com"
$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?
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 = 'your_username#outlook.com'
$smtpPassword = 'your_password'
$MailTo = 'your_to_mail#example.com'
$MailFrom = 'your_username#outlook.com'
$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
I solved changing port to 25. But why I can't use IMAP ?
Related
I have a web application and I have one worker process set up. I need to ensure that IIS restarts when the value is exceeded. I am attaching a script below that works for me, but only when I have only one application pool. I am also attaching an error that appears on a server where there are multiple application pools.
$process_dump32 = get-process w3wp
$process_dump32_output = [Math]::Round($process_dump32.privatememorysize64, 2)
Write-Output $process_dump32_output
#Email Settings
$EmailBody = 'IIS has more than 800'
$subject_mail = "IIS has more than 800 - $Date"
$MailFrom = 'email#example.com'
$MailTo = 'email2#example.com'
$smtpServer = '10.0.0.1'
$smtpPort = '587'
$secpasswd1 = ConvertTo-SecureString "Paassword" -AsPlainText -Force
$mycreds1 = New-Object System.Management.Automation.PSCredential ("notification", $secpasswd1)
$encoding = [System.Text.Encoding]::UTF8
If ($process_dump32_output -lt 800000000)
{
#Do Nothing if RAM is less then 800MB
}
Else
{
#Stop/Start
Stop-Service W3SVC
Start-Sleep -seconds 5
Start-Service W3SVC
Send-MailMessage -from $MailFrom -to $MailTo -subject $subject_mail -body $EmailBody -Encoding $encoding -smtpServer $smtpServer -Port $smtpPort -credential $mycreds1
}
ERROR
Cannot find an overload for "Round" and the argument count: "2".
At I:\MONITOR\check-memory-exception-iis.ps1:7 char:1
+ $process_dump32_output = [Math]::Round($process_dump32.privatememorys ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Thanks for help
Gild
I tried to send an email with attachement to outlook (365) via powershell, like posted in this scriptlet:
$SmtpServer = "smtp.office365.com"
$SmtpPort = 587
$smtp = New-Object System.Net.Mail.SmtpClient($SmtpServer,$SmtpPort)
$MailMessage = New-Object system.net.mail.mailmessage
$attfile = "C:\temp\test.txt"
$attatchment = New-Object System.Net.Mail.Attachment($attfile)
$smtp.Host = "smtp.office365.com" #DNS oder IP
$MailMessage.From = "test***#outlook.de"
$MailMessage.To.Add("test***#outlook.de")
$MailMessage.Subject = "PowerShell Email with attatchemnt"
$MailMessage.Body ="This is a email from powershell with attatchments"
$MailMessage.IsBodyHtml = $false
$MailMessage.Attachments.Add($attatchment)
#mit Authentifizierung beim Mail Server (ohne einfach weglassen)
$SmtpUser = New-Object System.Net.NetworkCredential
$SmtpUser.UserName = "test***"
$SmtpUser.Password = "*****"
$smtp.Credentials = $SmtpUser
$smtp.Send($MailMessage)
Completed with the according real credentials,
I got the followin error message:
Ausnahme beim Aufrufen von "Send" mit 1 Argument(en): "Fehler beim Senden von Mail."
In Zeile:1 Zeichen:1
$smtp.Send($MailMessage)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
Any Hints, how I can get it run and send mails with attachement via a powershell script?
Kind regards,
Oliver
try this:
# Get the credential
$credential = Get-Credential
## Define the Send-MailMessage parameters
$mailParams = #{
SmtpServer = 'smtp.office365.com'
Port = '587'
UseSSL = $true
Credential = $credential
From = 'sender#yourdomain.com'
To = 'recipient#yourdomain.com', 'recipient#NotYourDomain.com'
Subject = "SMTP Client Submission - $(Get-Date -Format g)"
Body = 'This is a test email using SMTP Client Submission'
Attachment = 'C:\Test.txt' # Here you can change your attachment
DeliveryNotificationOption = 'OnFailure', 'OnSuccess'
}
## Send the message
Send-MailMessage #mailParams
Your code worked for me, except that I had to enable ssl.
Maybe add $smtp.EnableSsl = $true
Can someone please help me figure this part out.
#Mail Configuration
$smtpUser = "email#domain.com"
$smtppass = ConvertTo-SecureString "PasswordAsPlainText" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($smtpuser, $smtppass)
$ToAddress = "toaddress#domain.com"
$FromAddress = "send#domain.com"
$SMTPSERVER = "smtp.office365.com"
$SMTPPORT = "587"
$MailParam = #{
To = $ToAddress
From = $FromAddress
Subject = $subject
Body = $Mail
SMTPServer = $SMTPServer
Port = $SMTPPORT
Credential = $pscred
}
#Send Email
$GetChildItem = Get-ChildItem -Path C:\Temp
if ($GetChildItem -ne $Null)
{
Write-Host "Backup Success"
$subject = "$env:COMPUTERNAME SQL Backup Success"
$Mail = "SQL Backup Succeded on the server, please see the attached report for more details"
$attachment = $reportfile
Send-MailMessage #MailParam -BodyAsHtml -usessl
#Exit
}
if ($GetChildItem -eq $Null)
{
Write-Host "Backup Failed"
$subject = "$env:COMPUTERNAME SQL Backup Failed"
$Mail = "SQL Backup Failed on the server, please see the attached report for more details"
$attachment = $reportfile, $debuglog
Send-MailMessage #MailParam -usessl -BodyAsHtml
#Exit
}
Now I don't think anything is wrong with the code above, I am no expert coder but I can pretty much copy and paste :) and take stuff from there to get it working for me.
The issue with the above code is that when run it, it doesn't work for the 1st time but when you run it again it works fine. The error you get the first time is
Send-MailMessage : Cannot validate argument on parameter 'Body'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\Aasim\Desktop\Untitled1.ps1:29 char:26
+ Send-MailMessage #MailParam -BodyAsHtml -usessl
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage
I am not sure what the issue is and why it doesn't work only the first time but works every other subsequent time until you close and reopen the script.
Basically I am creating a SQL backup script that backs up databases to our Network Share and then emails me whether it was successful or not. so far the rest of the script works just fine.
In your If and Else blocks, instead of creating a variable $subject, or $Mail, update the hashtable, $MailParam. Also, you seem to be missing the Attachment variable in your Send-MailMessage
if ($GetChildItem -eq $Null)
{
Write-Host "Backup Failed"
$MailParam.Subject = "$env:COMPUTERNAME SQL Backup Failed"
$MailParam.Body = "SQL Backup Failed on the server, please see the attached report for more details"
$attachment = $reportfile, $debuglog
Send-MailMessage #MailParam -usessl -BodyAsHtml -Attachments $attachment
#Exit
}
How do I send an email containing a binary file using powershell script? Below is my failing best attempt
$to = 'andy.boo#boo.com'
$subject = 'boo'
$file = 'inf.doc'
$from = $to
$filenameAndPath = (Resolve-Path .\$file).ToString()
[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = 'smtp.boo.com'
$smtpClient.Send($message)
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At C:\email.ps1:15 char:17
+ $smtpClient.Send <<<< ($message)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
What version of PowerShell? If you're using version 2.0 save yourself the trouble and just use the Send-MailMessage cmdlet.
If version 1.0:
$msg = new-object system.net.mail.MailMessage
$SMTPClient = new-object system.net.mail.smtpClient
$SMTPClient.host = "smtp server"
$msg.From = "Sender"
$msg.To.Add("Recipient")
$msg.Attachments.Add('<fullPathToFile')
$msg.Subject = "subject"
$msg.Body = "MessageBody"
$SMTPClient.Send($Msg)
Found this.. which is a lot better
Send-MailMessage -smtpServer smtp.doe.com -from 'joe#doe.com' -to 'jane#doe.com' -subject 'Testing' -attachment foo.txt
I have written a PowerShell script that will create an email, however I can't seem to attach a file. The file does exist and PowerShell can open it, Could anyone tell me what I'm doing wrong?
$ol = New-Object -comObject Outlook.Application
$message = $ol.CreateItem(0)
$message.Recipients.Add("Deployment")
$message.Subject = "Website deployment"
$message.Body = "See attached file for the updates made to the website`r`n`r`nWarm Regards`r`nLuke"
# Attach a file this doesn't work
$file = "K:\Deploy-log.csv"
$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)
If you are on PowerShell 2.0, just use the built-in cmdlet Send-MailMessage:
C:\PS>Send-MailMessage -from "User01 <user01#example.com>" `
-to "User02 <user02#example.com>", `
"User03 <user03#example.com>" `
-subject "Sending the Attachment" `
-body "Forgot to send the attachment. Sending now." `
-Attachment "data.csv" -smtpServer smtp.fabrikam.com
If you copy/paste this watch out for the extra space added after the backtick. PowerShell doesn't like it.
I got the above to work by removing the line
$attachment = new-object System.Net.Mail.Attachment $file
and changing
$message.Attachments.Add($attachment)
to
$message.Attachments.Add($file)
While the solution provided by #Keith Hill would be better, even with a lot of goggling I couldn't get it to work.
This worked for me using powershell-
Define Variables:
$fromaddress = "donotreply#pd.com"
$toaddress = "test#pd.com"
$Subject = "Test message"
$body = "Please find attached - test"
$attachment = "C:\temp\test.csv"
$smtpserver = "mail.pd.com"
Use the variables in the script:
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
You can use send-mailmessage or system.net.mail.MailMessage to accomplish it. Interestingly, there is a significant execution time difference between the two approaches. You can use measure-command to observe the execution time of the commands.
I have experienced such problem, (windows 10 / PS 5.1)
My SMTP is not authentified or secure ...
I have to finish by this line "MyAttacheObject.Dispose()"
... / and finally that's work :!
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$attach.Dispose()
this is my code with two attachments :
# Email configuration NO AUTH NO SECURE
$emailHost = "smtp.bot.com"
$emailUser = ""
$emailPass = ""
$emailFrom = "myemail#bot.com"
$emailsTo=#("toyoumylove#bot.com","toyoumybad#bot.com")
$emailSubject = $title
$emailbody=$body
$attachment1 = #($PATh+$outFile)
$attachment2 = #($PATh+$inFile)
#End of parameters
$msg = New-Object System.Net.Mail.MailMessage
$msg.from = ($emailFrom)
foreach ($d in $emailsTo) {
$msg.to.add($d)
}
$msg.Subject = $emailSubject
$msg.Body = $emailbody
$msg.isBodyhtml = $true
$att = new-object System.Net.Mail.Attachment($attachment1)
$msg.Attachments.add($att)
$att = new-object System.Net.Mail.Attachment($attachment2)
$msg.Attachments.add($att)
$smtp = New-Object System.Net.Mail.SmtpClient $emailHost
$smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass);
$smtp.send($msg)
$att.Dispose()
"yourpassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\Password.txt"
# The above command will encrypt the password you need to run this command only one time
# 1.Sign in to your work or school account, go to the My Account page, and select Security info.
2.Select Add method, choose App password from the list, and then select Add.
3.Enter a name for the app password, and then select Next. it will give password
# you should use this password in above mentioned command
$User = "mymail#company.net"
$File = "C:\Users\username\Desktop\Mail\Password.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString -AsPlainText -Force)
$EmailTo = "mymail#company.net"
$EmailFrom = "mymail#company.net"
$Subject = "SERVICE STOPPED"
$Body = "SERVICE STOPPED PFA Document to get more details."
$SMTPServer = "smtp.office365.com"
$filenameAndPath = "C:\Users\username\Desktop\new.txt"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
I needed to drop the "-AsPlainText -Force"
$emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailUser, (Get-Content $emailPasswordFile | ConvertTo-SecureString)