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
CodePudding user response:
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 = '[email protected]'
To = '[email protected]', '[email protected]'
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
CodePudding user response:
Your code worked for me, except that I had to enable ssl.
Maybe add $smtp.EnableSsl = $true
CodePudding user response:
Wouldn`t it be better to use MailKit as recomended here? https://github.com/dotnet/platform-compat/blob/master/docs/DE0005.md
MailKit: https://github.com/jstedfast/MailKit
Example Scripts can be found here: https://adamtheautomator.com/powershell-email/
