I'm making a script to automate Outlook 2016. I have one account with two different inboxes from clients.
At the end of the script, I need to send an email from the name of the inbox the script is run from. I'm authorized to send email in the name of both inboxes, but I can't get the script to do it. I post my actual code:
The code:
Function Send-Email {
param ([String]$desde,[String]$subject,[String]$buzon,[String]$inc)
$mail = $Outlook.CreateItem(0)
$firma ="
Textplan
"
$mail.subject = "Closed Ticket "+$subject
[String]$cuerpo =#"
Dear colleague,
bla bla bla
Thank you.
"#
$mail.sender = $buzon
$mail.body = $cuerpo+" "+$firma
$mail.To = $desde
$mail.Send()
Start-Sleep 3
}
$Outlook = New-Object -ComObject Outlook.Application
$desde = client2#mail.com
$buzon = inbox1#mail.com
$inc = 000000001
$subject = "Automat request"
Send-Email -desde $desde -subject $asunto -buzon $Buzon1 -inc $inc
Your issues look to be:
Object defined outside the function it's being used in:
$Outlook = New-Object -ComObject Outlook.Application
Unquoted strings in variables:
$desde = client2#mail.com
$buzon = inbox1#mail.com
$inc = 000000001
Mix and match of single and double quotes
I'd recommend reading about_quoting_rules to understand the difference as this is quite crucial when using variables within strings.
the function param $inc is defined has data but is not used for anything?
Recommend to remove this if it's not used.
Not specifically an issue, but I've changed the here string (#" "#) to a normal string with line breaks (`r`n`)
After resolving the issues and tidying the code:
Function Send-Email {
param (
[String]$desde,
[String]$subject,
[String]$buzon,
[String]$inc
)
$firma = 'Textplan'
$cuerpo = "Dear colleague,`r`nbla bla bla`r`nThank you."
$Outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.subject = 'Closed Ticket ' + $subject
$mail.sender = $buzon
$mail.body = "$cuerpo $firma"
$mail.To = $desde
$mail.Send()
Start-Sleep 3
}
$desde = 'client2#mail.com'
$subject = 'Automat request'
$buzon = 'inbox1#mail.com'
$inc = '000000001'
Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc
I don't have Outlook to test the code, but from checking it over with the Outlook.Application documentation it now seems to be valid.
I finally used this lines and work well:
$mail.SentOnBehalfOfName = "inbox1d#mail.com"
$mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}
Function Send-Email {
param (
[String]$desde,
[String]$subject,
[String]$buzon,
[String]$inc
)
$firma = 'Textplan'
$cuerpo = "Dear colleague,`r`nbla bla bla`r`nThank you."
$Outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.subject = 'Closed Ticket ' + $subject
$mail.sender = $buzon
$mail.body = "$cuerpo $firma"
$mail.SentOnBehalfOfName = "inbox1d#mail.com"
$mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}
$mail.Send()
Start-Sleep 3
}
$desde = 'client2#mail.com'
$subject = 'Automat request'
$buzon = 'inbox1#mail.com'
$inc = '000000001'
Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc
Related
I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I'm trying to write a PowerShell script which parses a list of email addresses and send a mail to them.
The file is formatted this way:
a.a#domain.com
b.b#domain.com
c.c#domain.com
...
I figured something like:
$recipients = Get-Content -Path MY_FILE.txt
$outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.To = $recipients # here's the problem
$mail.Subject = "MY_SUBJECT"
$mail.HTMLBody = "MY_HTML_BODY"
$mail.Send()
My problem, as you can see is: how can I assign the addresses in $recipients to $mail.To?
When in doubt, read the documentation:
MailItem.To Property (Outlook)
Returns or sets a semicolon-delimited String list of display names for the To recipients for the Outlook item.
Read/write.
[...]
Remarks
This property contains the display names only. The To property corresponds to the MAPI property PidTagDisplayTo. The Recipients collection should be used to modify this property.
Emphasis mine.
To send one mail to all recipients change this line:
$mail.To = $recipients
into this:
foreach ($addr in $recipients) {
$mail.Recipients.Add($addr)
}
and the code should do what you want.
If you want to send every address in your file a separate email do it this way:
$recipients = Get-Content -Path MY_FILE.txt
$outlook = New-Object -ComObject Outlook.Application
ForEach ($recipient in $recipients) {
$mail = $Outlook.CreateItem(0)
$mail.To = $recipient
$mail.Subject = "MY_SUBJECT"
$mail.HTMLBody = "MY_HTML_BODY"
$mail.Send()
}
Also make sure you close the COM Object by adding the following to the end of your file:
$outlook.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($outlook) | Out-Null
You could try something like this:
$file = "$PSScriptRoot\MY_FILE.txt"
# Add a List of recipients
$to = #()
foreach ($email in (Get-Content $file)) {
$to += "$email;"
}
Write-Host "Complete recipient-list: $to"
$outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.To = "$to"
$mail.Subject = "MY_SUBJECT"
$mail.HTMLBody = "MY_HTML_BODY"
$mail.Send()
I have a piece of code comparing two values, and if the condition is satisfied it sends out an email. But it is not working, help is appreciated.
code:
$filesize = Get-ChildItem $filename | Select-Object Length | Format-Wide
$filesize
$num=1265
$num
if("$filesize" -gt "$num")
{
$SMTPServer = "10.20.19.94"
$SMTPPort = 25
$username = "vcenter#somosadc.com"
#Define the receiver of the report
$to = "jeevan.m2#hcl.com"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = new-object Net.Mail.Attachment($filename)
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $false
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}
output:
1262
1265
Mail Sent
Why is it sending email if $filesize=1262 is less than $num=1265. It is killing me.
Because you're not comparing two numbers, you're comparing two strings.
Remove the Format-Wide command from the first pipeline, and remove the quotes around the arguments in your if condition:
$filesize = Get-ChildItem $filename | Select-Object Length
$num = 1265
if($filesize.Length -gt $num) {
<# ... #>
}
We have some powershell automation in place which sends an email with outlook with one email account but we are looking for a way to be able to set the sender email address to a different outlook account we have access to.
I've tried googling and looking round on here and cant seem to find the way of doing it.
here is the code we are using.
$Outlook = New-Object -comObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
start-sleep 5
$Mail.subject = ""
$mail.
$Mail.To = ""
$Mail.Cc = ""
$Mail.Body = "Test"
$Mail.Display()
$Mail.Send()
Just use the below Outlook function to send the email. You are actually doing the same over there. Is there any error you are getting ? Anyways, Use the below one:
Follow all the comments in the function for your reference.
Function Global:Send-Email {
[cmdletbinding()]
Param (
[Parameter(Mandatory=$False,Position=0)]
[String]$Address = "user2#domain.com",
[Parameter(Mandatory=$False,Position=1)]
[String]$Subject = "Mail Subject",
[Parameter(Mandatory=$False,Position=2)]
[String]$Body = "MailBody"
)
Begin {
Clear-Host
# Add-Type -assembly "Microsoft.Office.Interop.Outlook"
}
Process {
# Create an instance Microsoft Outlook
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "$Address"
$Mail.Subject = $Subject
$Mail.Body =$Body
# $Mail.HTMLBody = "HTML BODY"
# $File = "D:\CP\timetable.pdf"
# $Mail.Attachments.Add($File)
$Mail.Send()
} # End of Process section
End {
# Section to prevent error message in Outlook
$Outlook.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook)
$Outlook = $null
} # End of End section!
} # End of function
# Example of using this function
Send-Email #-Address User2#domain.com
Note: If you want to send email from someone's behalf then you have to enable anonymous mail from the connectors or the user should have the permission to send mail from someone's behalf. In that case, you can add one more object as
$mail.From=""
One sample example to send mail from GMAIl as reference.
$From = "YourEmail#gmail.com"
$To = "AnotherEmail#YourDomain.com"
$Cc = "YourBoss#YourDomain.com"
$Attachment = "C:\temp\Some random file.txt"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (Get-Credential) -Attachments $Attachment
Hope it helps...
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)