Powershell - sending an outlook message with attachement via powershell (January 23, 2022) - powershell

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

Related

Send email via SMTP Mail server

I have installed SMTP Virtual Server in windows server 2012 r2. Later I have used following PowerShell script to send the email. Which was successful
$email = "xxxxxxxxxx#xxxxxx.com"
$pass = "xxxxxxx"
$smtpServer = "smtp.office365.com"
$smtpPort = "25"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
$msg.From = "$email"
$attachment = New-Object Net.Mail.Attachment("C:abcd/123.txt");
$msg.Attachments.Add($attachment);
$msg.To.Add("xxxx#xxxxx.com")
$msg.BodyEncoding = [system.Text.Encoding]::Unicode
$msg.SubjectEncoding = [system.Text.Encoding]::Unicode
$msg.IsBodyHTML = $true
$msg.Subject ="List of users"
$msg.Body=$msg.Body = "<h2> hi everyone </h2>
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email", "$pass");
$smtp.Send($msg)
here my question is can I send email without using from address in the above script(Is there any chance to save from email address and credentials somewhere in SMTP virtual server settings so that script can take credentials directly). I don't want to use from email address and credentials in above script
I'd suggest using Send-MailMessage instead of manual .NET manipulation:
$Creds = Import-CliXml -Path 'C:\mycreds.xml'
$MailArgs = #{ 'SmtpServer' = 'smtp.office365.com'
'Port' = 25
'To' = 'xxxx#xxxxx.com'
'From' = $Creds.UserName
'Subject' = 'List of users'
'Attachments' = 'C:\abcd\123.txt'
'Body' = '<h2> hi everyone </h2>'
'Encoding' = [Text.Encoding]::Unicode
'BodyAsHtml' = $true
'UseSsl' = $true
'Credential' = $Creds
}
Send-MailMessage #MailArgs
And you would create your $Creds object as follows:
Get-Credential -Credential 'xxxxxxxxxx#xxxxxx.com' | Export-CliXml -Path 'C:\mycreds.xml'
There are a couple extra options you might be interested in (such as notification of delivery) you can read about in the doc linked above.
Additionally, your password is encrypted when exported using Export-CliXml specific to that device and account utilizing DPAPI.

Unable to Send Outlook Email via Powershell

I can create an email and display it with my script, but for some reason it doesn't send and I receive the following error. Am I missing something, maybe there's a permissions issue?
Exception calling "Send" with "0" argument(s): "Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))"At C:\TEMP\Scripts\PowerShell\Outlook EMail Creation\TestEMailSend.ps1:27 char:5
+ $mail.Send()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
My code:
$global:UserReportsToEmail = "my.email#domain.com"
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = "$global:UserReportsToEmail"
$mail.cc = "EMAIL#domain.com"
$mail.Subject = "mySubject"
$mail.HTMLBody =
"<font color ='blue'><b>TESTING STUFFFF!</b></font><br>
Text on a new line $UserID"
$mail.Send()
$inspector = $mail.GetInspector
$inspector.Display()
According to a few of the Microsoft sites (e.g. https://social.msdn.microsoft.com/Forums/en-US/80c66a08-66ee-4ab6-b629-6b1e70143eb0/operation-aborted-exception-from-hresult-0x80004004-eabort-outlook-appointment?forum=outlookdev ) this is due to 'object model guard'. A security feature to prevent automated programs from doing stuff like auto-emailing out viruses and stuff from the background.
You probably already worked this out. Posting this here so that others like myself can more quickly and easily understand why its not working.
you can use the Send-MailMessage CmdLets : https://technet.microsoft.com/en-us/library/hh849925.aspx
then when i need more controls and dispose functionnality i use System.Net.Mail.SmtpClient
try
{
$emailCredentials = Import-Clixml "C:\testMail\credentials.clixml"
$recipients = #("user#mail.com", "user2#mail.com", "user3#mail.com")
$attachments = #("C:\testMail\file.txt", ""C:\testMail\file2.txt", "C:\testMail\file3.txt")
# create mail and server objects
$message = New-Object -TypeName System.Net.Mail.MailMessage
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient($buildInfoData.BuildReports.Mail.Server)
# build message
$recipients | % { $message.To.Add($_) }
$message.Subject = $subject
$message.From = New-Object System.Net.Mail.MailAddress($emailCredentials.UserName)
$message.Body = $mailHtml
$message.IsBodyHtml = $true
$attachments | % { $message.Attachments.Add($(New-Object System.Net.Mail.Attachment $_)) }
# build SMTP server
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient(smtp.googlemail.com)
$smtp.Port = 572
$smtp.Credentials = [System.Net.ICredentialsByHost]$emailCredentials
$smtp.EnableSsl = $true
# send message
$smtp.Send($message)
Write-Host "Email message sent"
}
catch
{
Write-Warning "$($_.Exception | Select Message, Source, ErrorCode, InnerException, StackTrace | Format-List | Out-String)"
}
finally
{
Write-Verbose "Disposing Smtp Object"
$message.Dispose()
$smtp.Dispose()
}

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 = "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 ?

How to send email with PowerShell

I'd like to send email from PowerShell,
so I use this command:
$EmailFrom = "customer#yahoo.com"
$EmailTo = "receiver#ymail.com"
$Subject = "today date"
$Body = "TODAY SYSTEM DATE=01/04/2016 SYSTEM TIME=11:32:05.50"
$SMTPServer = "smtp.mail.yahoo.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential("customer#yahoo.com", "password")
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
This command didn't work for Yahoo mail or Outlook mail, but works for my Gmail.
Is there anything wrong that I have done?
Following code snippet really works for me:
$Username = "MyUserName";
$Password = "MyPassword";
$path = "C:\attachment.txt";
function Send-ToEmail([string]$email, [string]$attachmentpath){
$message = new-object Net.Mail.MailMessage;
$message.From = "YourName#gmail.com";
$message.To.Add($email);
$message.Subject = "subject text here...";
$message.Body = "body text here...";
$attachment = New-Object Net.Mail.Attachment($attachmentpath);
$message.Attachments.Add($attachment);
$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "587");
$smtp.EnableSSL = $true;
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message);
write-host "Mail Sent" ;
$attachment.Dispose();
}
Send-ToEmail -email "reciever#gmail.com" -attachmentpath $path;
I use this:
Send-MailMessage -To hi#abc.com -from hi2#abc.com -Subject 'hi' -SmtpServer 10.1.1.1
You can simply use the Gmail smtp.
Following is The powershell code to send a gmail message with an Attachment:
$Message = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", 587)
$smtp.Credentials = New-Object System.Net.NetworkCredential("From#gmail.com", "password");
$smtp.EnableSsl = $true
$smtp.Timeout = 400000
$Message.From = "From#gmail.com"
$Message.To.Add("To#gmail.com")
$Message.Attachments.Add("C:\foo\attach.txt")
$smtp.Send($Message)
On the sender Google Account (From#gmail.com),
Make sure you have Turned ON Access for less-secure apps option,
from google Account Security Dashboard.
Finally, Save this Script As mail.ps1
To invoke the above Script Simple run below on Command Prompt or batch file:
Powershell.exe -executionpolicy remotesigned -File mail.ps1
By Default, For sending Large Attachments Timeout is Around 100 seconds or so.
In this script, it is increased to Around 5 or 6 minutes
Sometimes you may need to set the EnableSsl to false (in this case the message will be sent unencrypted over the network)

powershell send email with binary attachment

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