Powershell outlook application

Powershell outlook application DEFAULT

Outlook Email Automation with PowerShell

Developer

In this post, App Dev Manager Edward Fry demonstrates how to use Microsoft Outlook Object Library from PowerShell.


Time is a precious commodity. For many professionals, there just aren’t enough hours to accomplish all the tasks in a day. Thankfully, today’s world thrives on automation. Computers can perform painstaking, mundane tasks in a matter of seconds, leaving you the extra time to work on a multitude of more mentally intensive jobs. Whether you have an advanced technical degree or just use the computer for day-to-day tasks, it isn’t too hard to make the computer your personal assistant.

For this article, let’s focus on a specific type of task that is common for many professionals: sending out reports. While the specifics will vary, this scenario typically involves generating reports on some area of business interest and then sending those reports to recipients of interest. Of course, one way to approach this task would be to have each interested party look at their own reports or dashboards.

However, this isn’t always feasible. For instance, your users may be executives who don’t have the time for managing their own reporting. Or you might be in sales or services and need to share reports with your customers. Sharing that information is just part of the service that you provide, so it wouldn’t be appropriate to offload such a task to your customers. These are only two possible scenarios where you need to push reports to others rather than (or in addition to) having them pull their own.

An additional constraint, though, is that your report recipients must all be separated from each other. One executive might not need to know or care about another’s area of focus. One customer should not see or even be aware of other customers’ reports for privacy reasons. This constraint adds some complexity and work to the process. Wouldn’t it be nice to have the computer be your personal assistant and take care of all that for you?

Our goal in this article is to automate the download of periodic reports, associated processing, and dissemination to recipients via discrete outgoing messages with relevant attachments. For this article, I am assuming that the reports come from a reporting tool that allows email subscriptions, like SQL Server Reporting Services (SSRS), that Outlook is the email client, and some basic PowerShell knowledge.

By the way, you don’t have to be a seasoned developer in order to pull this off; anyone with a little PowerShell experience can benefit. Every information professional will benefit from some basic scripting ability in a language like PowerShell, and I highly recommend setting aside some time to learn this useful practical skill. If you need the basics, check out some of the free resources that are available.

Before we get to the scripting, we need to set some things up. This will make the script easier to code, and it will enable easier management as things change over time.

Report Delivery

A key component of this solution is that the reports you need to send out are delivered to your inbox. Of course, it’s possible to run them manually and save them off, and there’s a solution for automating those, too (though that is outside the scope of this article), but it is much easier to have them come to you.

Oftentimes, people are not aware that you can automate report delivery in SSRS. It is quite simple and involves just pre-selecting the filters of interest and a delivery schedule – for instance, once a month or once a week, etc.

When you set up your subscription, be sure to select the type of report that you wish to distribute. Since PDF is the most common file type for this sort of scenario, we will assume the reports are delivered in PDF format for the rest of this article.

Recipients

Typing in a list of recipients each time you need to send out reports is tedious and error-prone. Instead of doing that, let’s add a layer of abstraction to the process. In our case, we will use Outlook groups to refer to recipients as a group rather than by name. As you can see in the image below, you create a group for each type of recipient for each destination. For instance, our example here assumes customer recipients. You would make an Outlook group for primary recipients, one for CC, etc. Check out how to make groups in Outlook HERE.

For each group, then, you simply add the actual people who will need to receive the reports. That could be one person or a lot of people. As contacts change, all you need to do is keep these groups up to date, and the automation script will implicitly pick those changes up without any need to modify the code.

Template Emails

We also need a template email. In the image above, you can see that our template includes the message that we want to send to our recipients along with some tags that will be replaced in our script. To create an email template, go HERE.

File System

In this optional but recommended step, organize your folder structure so that you can save a copy of each report automatically for your records. Setting up an organized filing system is key to keeping the files organized and easy to locate in the future.

Once the reports of interest show up in your inbox at the designated time from SSRS, our automation will follow these steps:

  1. Connect to Outlook
  2. Open the emails and save the PDF to the proper folder in your filing system for backup purposes. I like to rename each PDF with something meaningful to the recipient and report. For example: (CompanyName)(ReportTitle)(Date).pdf
  3. Process Reports
    1. Attach the PDF into the analogous email template.
    2. Expand the To and CC recipient groups.
    3. Customize the message as needed.
  4. Send the emails.
  5. Disconnect from Outlook

Connect to Outlook

The real magic of this solution is that we can control Outlook remotely through PowerShell. We are taking advantage of the fact that PowerShell makes the entire .NET framework available to us. That means that any functionality exposed by the framework can be accessed by PowerShell. This also means that you could modify this code to control other Office products like Word or Excel. Here is the code, which you can just copy and paste:

Add-Type -assembly "Microsoft.Office.Interop.Outlook" add-type -assembly "System.Runtime.Interopservices" try { $outlook = [Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')     $outlookWasAlreadyRunning = $true } catch {     try     {         $Outlook = New-Object -comobject Outlook.Application         $outlookWasAlreadyRunning = $false     }     catch     {         write-host "You must exit Outlook first."         exit     } } $namespace = $Outlook.GetNameSpace("MAPI")

Process Reports

Now we can finally process those emails that were sent by SSRS automatically with the report PDFs.

With our handy Outlook namespace object in hand, we can now get references to other objects and commands within Outlook. First, we’ll get a reference to the inbox and the emails that match our criteria within the inbox.

$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox) $emails = $inbox.Items | Where-Object {$_.Subject -like $subjectComparisonExpression} The $emails variable will contain a list of just those emails that were sent from SSRS.  Now, for each of those, we can apply some processing.  For instance: # Process the reports by recipient ForEach ($email in $emails) {     # Look at all the attachments in a single email     ForEach ($attach in $email.Attachments)     {         # Not the most robust way to do it, but extract only the first pdf.. there shouldn't be more than one anyway         if ($attach.filename.contains("pdf"))         {              # Set the customer filename and paths and save off their report              # Save the main file           # Prepare outgoing emails (see following article section)       } } }

Prepare Outgoing Emails

Within the looping structure above (in place of the “Prepare outgoing emails” comment above), we can now get our emails ready. This will utilize the email template and groups that we prepared earlier. Here is some sample code to get you started:

             # Now that we've saved the attachments, send notices out to the recipients             $template = get-childitem $emailTemplatePath -Filter "$emailTemplatePattern$customer.oft"             if ((Test-Path $template.FullName) -eq $true) # Make sure there's a template to use             {                 # Create the email from a template                 $emailToCustomer = $outlook.CreateItemFromTemplate($template.FullName.ToString())                 # Expand the contact groups                 #  Start with the To line                 $toListOriginal = $emailToCustomer.To                 $toListNew = $null                 $contacts = $namespace.GetDefaultFolder($olFolderContacts).Items  # All the contacts in outlook                 foreach ($to in $toListOriginal) # Enumerate the list of To's                 {                     $toContacts = $contacts.Item($to)                     for ($i = 1; $i -le $toContacts.MemberCount; $i++)                      {                           $toContact = $toContacts.GetMember($i)                         [array]$toListNew = $toListNew + $toContact                     }                  }                 # Expand the CC line                 $ccListOriginal = $emailToCustomer.CC                 $ccListNew = $null                 $contacts = $namespace.GetDefaultFolder($olFolderContacts).Items  # All the contacts in outlook                 foreach ($cc in $ccListOriginal) # Enumerate the list of CC's                 {                     $ccContacts = $contacts.Item($cc)                     for ($i = 1; $i -le $ccContacts.MemberCount; $i++)                      {                           $ccContact = $ccContacts.GetMember($i)                         [array]$ccListNew = $ccListNew + $ccContact                     }                  }                 # Convert to string                 if ([string]::IsNullOrEmpty($toListNew) -eq $false)                 {                     $toListFinal = $null                     foreach ($to in $toListNew) { $toListFinal = $toListFinal + $to.Address + ";" }                     $toListFinal = $toListFinal.Substring(0, $toListFinal.Length - 1)  # Trim final ;                     $emailToCustomer.To = $toListFinal                 }                 if ([string]::IsNullOrEmpty($ccListNew) -eq $false)                 {                     $ccListFinal = $null                     foreach ($cc in $ccListNew) { $ccListFinal = $ccListFinal + $cc.Address + ";" }                     $ccListFinal = $ccListFinal.Substring(0, $ccListFinal.Length - 1)  # Trim final ;                     $emailToCustomer.CC = $ccListFinal                 }                                  # Customize the rest of the message as needed                 $emailToCustomer.Attachments.Add($fileFullPath) | Out-Null                 $emailToCustomer.HTMLBody = $emailToCustomer.HTMLBody.Replace("[Month]", $priorMonth)                 $emailToCustomer.HTMLBody = $emailToCustomer.HTMLBody.Replace("[Year]", $priorYear)                 $emailToCustomer.Save()             }

As you can see, we first use a template denoted by the constant $emailTemplatePattern for each recipient or customer to create a new email. Next, we expand the contact groups specified in the To and CC lines of the new email. Finally, we replace the tags that were denoted by “[tag]” in the template with appropriate data points meaningful to each recipient. This data is usually pulled directly off of the title or file name of the reports sent by SSRS. You could also parse information out of the attachments themselves, though such an activity is beyond the scope of this article.

Note: You can also have the script automatically send out your emails. I prefer to double check before they go out to make sure that everything looks ok.

Wrapping Up

Once everything is ready, you can either review and manually send out the resulting emails, or you can just sit back since PowerShell did it for you, depending on your choice above to Save or Send.

It is important to shut down any Outlook processes that were spawned during the script so as to maintain idempotency. Here is some code to do that:

# Close outlook if it wasn't opened before running this script if ($outlookWasAlreadyRunning -eq $false) {     Get-Process "*outlook*" | Stop-Process –force }

We examined how to configure and connect to Outlook through PowerShell in order to process periodic reports. Those reports are delivered automatically by SSRS as email attachments. PowerShell uses .NET to control Outlook programmatically, file away the reports, and create customized emails for each recipient. This technique could easily be modified to perform other types of email processing or to automate other Office products. We hope that this saves you some time, which is, after all, our most limited commodity of all.

Developer Support

App Dev Customer Success Account Manager, Microsoft Developer Support

Follow

Sours: https://devblogs.microsoft.com/premier-developer/outlook-email-automation-with-powershell/

Create new Outlook folders using PowerShell

I have a PowerShell sample to delete folders from Outlook and user asked how to use PowerShell to create folders. The PowerShell samples on this page create subfolders in the Inbox, or, by changing one line, add the folders to the root of the mailbox, at the same level as the Inbox.

The first PowerShell has the folder name in the Folders.Add line. If you need more than one folder, repeat the line. However, it is generally much easier to create a text file with one folder name per line than to copy and edit each line. The second set of PowerShell scripts use a text file for the folder names.

folders added using powershell

To add the folder at the same level as the Inbox, change this line:

to

$olApp = new-object -comobject outlook.application $namespace = $olApp.GetNamespace("MAPI") # Get Inbox $Folder = $namespace.GetDefaultFolder(6) # Repeat this line as needed, changing the folder name in each line $Folder.Folders.Add("Scripts") # End Inbox $olApp.Quit | Out-Null [GC]::Collect()

 

This PowerShell script reads the folder names from a text file. Use this is you need to frequently create new folders as the text file is generally easier to update.

To add the folders at the same level as the Inbox, change this line:

to

Don't forget to change the path to the text file!

Enter your folder names in a text file, one name per line.
text file containing the folder names

$olApp = new-object -comobject outlook.application $namespace = $olApp.GetNamespace("MAPI") $Folder = $namespace.GetDefaultFolder(6) $addnewFolders= New-Object System.IO.StreamReader("D:\Documents\newfolders.txt") while (($subfolder =$addnewFolders.ReadLine()) -ne $null) { $Folder.Folders.Add($subfolder) } $addnewFolders.Dispose() $olApp.Quit | Out-Null [GC]::Collect()

Like the script above, this PowerShell script reads the folder names from a text file. It just uses a different method to read the text file.

$olApp = new-object -comobject outlook.application $namespace = $olApp.GetNamespace("MAPI") $Folder = $namespace.GetDefaultFolder(6) foreach($subfolder in Get-Content "D:\Documents\newfolders.txt") { $Folder.Folders.Add($subfolder) } $olApp.Quit | Out-Null [GC]::Collect()

The scripts above work with the default data file; to add the folders to a secondary data file in your profile, you need add another line to identify the data file. You'll also need ot refer to the parent folder by name.

$olApp = new-object -comobject outlook.application $namespace = $olApp.GetNamespace("MAPI") $Folders = $namespace.Folders.Item("[email protected]") #parent folder $Folder = $Folders.Folders.Item("Inbox") foreach($subfolder in Get-Content "D:\Documents\newfolders.txt") { $Folder.folders.Add($subfolder) } $olApp.Quit | Out-Null [GC]::Collect()

 

If you need to delete the folders you added, this PowerShell will read the text file and delete the folders. This script moves the folders to the deleted items folder. To delete them from the Deleted Items folder, change 6 to a 3 in this line:

$olApp = new-object -comobject outlook.application $namespace = $olApp.GetNamespace("MAPI") # delete subfolders from Inbox folder $Folder = $namespace.GetDefaultFolder(6) foreach($subfolder in Get-Content "D:\Documents\newfolders.txt") { $Folder.Folders.item($subfolder).Delete() } $olApp.Quit | Out-Null [GC]::Collect()

 

To open the PowerShell IDE, type powershell on the start menu and click on Windows PowerShell ISE when the PowerShell app is found. Paste the script in the editing window.

powershell ise

Note: This PowerShell script will not work with the Windows Store version of Office. You'll need to use the macro version if you have the Windows store version of Office installed.

Saving PowerShell Scripts

If you want to save the script as a .ps1 file, paste it into Notepad and save it with the extension .ps1. To open it in the PowerShell IDE, type powershell on the start menu and click on Windows PowerShell ISE when the PowerShell app is found. Paste the script in the editing window.

To use it, you need to allow local scripts by running this command:

Set-ExecutionPolicy RemoteSigned

To run your saved .ps1 file, right-click on the script and choose Run with PowerShell.

Sours: https://www.slipstick.com/outlook/create-folders-powershell/
  1. Mate factor tea
  2. Ebay traps for sale
  3. Large metal horse wall art
  4. Mobile mini salary

A few days ago, I had to find a way to automatically send an email with attachments, at a predetermined time, using Outlook and PowerShell. I decided to use a Windows Scheduled Task, that would wake up at that time and invoke a PowerShell script.

The script below is the result of a collection of snippets and bits of code I found in various places around the Internet that allowed me to solve this problem.

For this example, I only want to send the files which have a specific extension (.html) and that exist in a specific folder (passed as parameter to the PowerShell script). Of course, you are free to remove this extension filtering for your own purposes.

Also, note that Outlook must have a configured email account for the sending process to succeed.

# Check to see we have all the arguments if($args.Count -lt 1) { Write-Host "Use: SendMail.ps1 <Path>" Write-Host Write-Host " <Path>: Full path for the folder which contains the files" Write-Host exit } $FullPath=$args[0] #Get an Outlook application object $o = New-Object -com Outlook.Application $mail = $o.CreateItem(0) #2 = High importance message $mail.importance = 2 $mail.subject = "This is the subject of the mail" $mail.body = "This is the body of the email. It has been automatically generated by a script." #separate multiple recipients with a ";" $mail.To = <INSERT THE RECIPIENT HERE> #$mail.CC = <OTHER RECIPIENT 1>;<OTHER RECIPIENT 2> # Iterate over all files and only add the ones that have an .html extension $files = Get-ChildItem $FullPath for ($i=0; $i -lt $files.Count; $i++) { $outfileName = $files[$i].FullName $outfileNameExtension = $files[$i].Extension # if the extension is the one we want, add to attachments if($outfileNameExtension -eq ".html") { $mail.Attachments.Add($outfileName); } } $mail.Send() # give time to send the email Start-Sleep 20 # quit Outlook $o.Quit() #end the script exit

You can invoke the script presented above, by using a simple command window and giving the following command:

PowerShell Command

I hope this helps!

Sours: https://blogit.create.pt/andresilva/2017/12/07/sending-an-email-with-attachments-using-outlook-and-powershell/
Connecting to Exchange Online in PowerShell

PowerShell Retrieves Outlook Addresses

How PowerShell Interacts with OutlookPowerShell Gets Outlook Address

The purpose of this page is to employ PowerShell to GetNameSpace("MAPI"), and thus make it possible to interact with Microsoft's Outlook client.

PowerShell with Outlook

 ♣

Planning: PowerShell Interrogates Outlook

Stage 1: We create a new ComObject
New-Object -ComObject Outlook.Application

Next, we set the namespace
$Namespace = $Outlook.GetNameSpace("MAPI")
$NameSpace.Folders.Item(1)

Stage 2: We will retrieve information about the actual messages.

Stage 1: PowerShell Lists Outlook's Folders

Clear-host
Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$NameSpace.Folders.Item(1).Folders | FT FolderPath

Stage 2: List Senders' Addresses Stored in Outlook's Inbox

This script connect to the logged on user's Outlook Inbox, then enumerates the email addresses of each message's sender.

Clear-Host
$Folder = "InBox"
Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$NameSpace.Folders.Item(1)
$Email = $NameSpace.Folders.Item(1).Folders.Item($Folder).Items
$Email | Sort-Object SenderEmailAddress -Unique | FT SenderEmailAddress

Note 1: Folders.Item(1).Folders.Item($Folder).items is correct

Instructions: Creating a PowerShell Function

By wrapping the above instructions in a function we introduce extra flexibility, for example, changing the folder from Inbox to Customers.

Function: Get-EmailAddressPowerShell Gets Outlook Address

Function Global:Get-EmailAddress{
Param(
[Parameter(Mandatory=$False,Position=0)]
[string]$Folder ="InBox"
     )
Process {
Clear-Host
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$NameSpace.Folders.Item(1)
$Email = $NameSpace.Folders.Item(1).Folders.Item($Folder).Items
$Email | Sort-Object SenderEmailAddress -Unique | FT SenderEmailAddress, To -Auto
     } # End of Process
}
Get-EmailAddress #-Folder Customers

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Ideas for Analyzing Outlook Emails

I love discovering additional properties to incorporate in my PowerShell scripts; for this research my cmdlet of choice is Get-Member.

Clear-Host
$Folder = "InBox"
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$NameSpace.Folders.Item(1)
$Email = $NameSpace.Folders.Item(1).Folders.Item($Folder).Items
$Email | Get-Member -MemberType Properties |Ft Name

Note 2: Using this technique I discovered the 'To' property for my Get-EmailAddress function.  Get-Member also introduced me to properties such as 'Importance' and 'Unread'.

Another Example Reading Email Subjects

The design brief: To filter out 'Unread', then sort on a variety of criteria; finally, list the subject and sender of each matching email.

At the heart of any PowerShell function is the Process.  What this Get-Email function does is create an Outlook object, and then retrieve messages from a named folder.  The default location is set to the Inbox, but the benefit of a function is that you can amend the source of messages using the -Folder parameter.

Function Global:Get-Email {
Param(
[String]$Folder = "InBox",
[String]$Test ="Unread",
[String]$Compare =$True
    )
Process{
$Folder = $Folder
Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$NameSpace.Folders.Item(1)
$Email = $NameSpace.Folders.Item(1).Folders.Item($Folder).Items
Clear-Host
Write-Host "Trawling through Outlook, please wait …."
$Email | Where-Object {$_.$Test -match $Compare} | Sort-Object -Property `
@{Expression = "Unread";Descending=$true}, `
@{Expression = "Importance";Descending=$true}, `
@{Expression = "SenderEmailAddress";Descending=$false} -Unique `
| Format-Table Subject, " ", SenderEmailAddress -AutoSize
    } # End of main section 'Process'
}

Get-Email  #-Compare false

Note 3: This function has three parameters

-Folder:  Specifies on of the yellow directories seen in Outlook

-Test: Allows you to change the criterion.

-Compare: Enables you to switch false to true, or use a string if that is more appropriate.

Note 4: @Expression enables us to sort on a variety of criteria.

Other Outlook Tasks for PowerShell

If you remember, I used Get-Member to list properties; we could modify the output to list methods.  Methods open up more possibilities, for example, to delete emails, and even add 'Rules' for Outlook to handle incoming messages.  Here is a case in point:

Clear-Host
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
# Try this
$Namespace | Get-Member -MemberType Property
 # and then
$NameSpace.DefaultStore | Get-Member -MemberType Method

This is how I discovered:
$Rules = $Namespace.DefaultStore.GetRules()
$Rules | Format-Table Name

Vaguely Related Topic: Test-Email Function

I came accross this little function to check the validity of an email address; what attracted me was the existence of [System.Net.Mail.MailAddress].

Function Global:Test-Email {
Param(
[String]$Message = "Wrong#gmail.com"
        )
Begin {
Clear-Host
       }
Process {
If ($Message -As [System.Net.Mail.MailAddress])
        {
          Write-Host "$Message is a good email address"
         }
else
        {
          Write-Host "$Message is a bad email address"
        }
      } # End of Process
} # End of function

Test-Email

Note 5: While this function has a default email address, you can easily append your own thus:
Test-Email  guythomas'cp.com.

See my PowerShell Send-Email function »

Summary PowerShell Send-Mail Function

This page shows how PowerShell can interrogate Microsoft Outlook. If you are going to investigate the email messages in detail, then it's worth creating a function with parameters.

If you like this page then please share it with your friends

 


See More PowerShell Function Parameters

• Scripting PowerShell Function   • PowerShell Function Clear-Recyclebin   • PowerShell Get-File

• Create PowerShell Function Get-ServiceStatus  • PowerShell Function Get-Driver  • PowerShell Outlook

• Show-BalloonTip   • PowerShell Function Get-IPConfig   • Free Permissions Analyzer

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

Sours: https://www.computerperformance.co.uk/powershell/outlook-email/

Outlook application powershell

OutlookConnector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function Connect-Outlook {

<#
.SYNOPSIS
OutlookConnector function: Returns Outlook object that can be re-used for multiple consecutive calls in same session.
 
.DESCRIPTION
Returns Outlook COM namespace session object that can be re-used for multiple consecutive calls with other commands.
If you are using only one command, COM object will be created by calling function itself.
But, if you will be calling multiple functions, it is better to assign COM object to a variable, and re-use in consecutive calls.
In case of issues with connecting (usually due to slow or interactive Outlook start), use command Start-Outlook to open application GUI, and then re-try the command.
 
.INPUTS
This function is not accepting any parameters.
 
.OUTPUTS
Function returns COM object linked to Outlook application. Precisly, it returns Outlook MAPI namespace.
This COM object can be used in other module commands.
 
.EXAMPLE
$Outlook = Connect-Outlook
Returns COM object that is saved in variable $Outlook which can be used with other commands.
 
.LINK
about_OutlookConnector
 
.NOTES
NAME: Connect-Outlook
AUTHOR: Igor Iric, [email protected]
CREATEDATE: September 29, 2015
#>
        
# based on function by Microsoft Scripting Guy, Ed Wilson
# http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/26/use-powershell-to-data-mine-your-outlook-inbox.aspx


# ---------------------- [Parameters definitions] ------------------------

[CmdletBinding()] 

Param ()

# ------------------------- [Function start] -----------------------------

# add types
# $olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
# $olSaveAsTypes = "Microsoft.Office.Interop.Outlook.olSaveAsType" -as [type]

# create new Outlook object and return it's MAPI namespace
try {
    Write-Verbose -Message 'Connecting to Outlook session'
    $outlook = new-object -comobject outlook.application
    $outlook.GetNameSpace("MAPI") # this is return object
    # MAPI Namespace https://msdn.microsoft.com/en-us/library/office/ff865800.aspx
    # Session https://msdn.microsoft.com/en-us/library/office/ff866436.aspx
    if ($outlook) {Write-Verbose -Message 'Connected successfully.'}
    } 
catch {
    throw ('Can not obtain Outlook COM object. Try running Start-Outlook and then repeat command. '+($Error[0].Exception))
    }

# ------------------------- [End of function] ----------------------------
        
}
Sours: https://www.powershellgallery.com/packages/OutlookConnector/0.92.1/Content/Connect-Outlook.ps1
Send email from Outlook with Powershell !

Reply to an outlook mail using powershell

I am trying to automate some replies to email that I get on my outlook. I have tried sending mail from my outlook (normal mail) using powershell and it worked successfully. Now I am trying to reply on mail using powershell. This is my current code as of now:

When I run this, I am getting the following error

I have printed the logs in between while debugging and found that it is successfully picking up all the emails in my outlook. The if condition where it matches the mail subject is also working fine. I tried going through various resource on internet but could not find any resolution for this. Any help or direction will be really helpful.

asked Feb 19 at 15:24

visleckvisleck

30111 silver badge55 bronze badges

Sours: https://stackoverflow.com/questions/66280339/reply-to-an-outlook-mail-using-powershell

You will also like:

PowerShell - Managing an Outlook Mailbox with PowerShell

  • 10 minutes to read

March 2013

Volume 28 Number 03

By Joe Leibowitz | March 2013

Have you ever needed to find an e-mail message from one or two years ago that, if you couldn’t find it, might adversely affect your circumstances? Does your company automatically delete messages from your Inbox or Sent Items folders? Do you get tired of copying e-mails to multiple folders when they touch on multiple topics of interest—a particular project, manager, subject matter, company division or the like?

Say an e-mail from Steve Masters comes in regarding the finances on Project X in Dubai. It would be useful to have an automated way to distribute copies of this message to folders for Project X, Steve Masters and Dubai, and ultimately to yet another folder for safekeeping. And all without you having to manually click around the Microsoft Outlook interface multiple times for each item of mail. (And if you receive a large volume of email, it’s all the more vital to automate some of the management tasks involved.)

The rules facility in Outlook is often useful in addressing these kinds of situations, and code I’ll present in this article shows how to automate the creation of rules. For example, copying messages from Steve Masters to a related folder in Outlook is a relatively straightforward matter. And that goes for other standard rules operations.

What’s more difficult to do, and generally outside the capacity of Outlook rules, is to get a single e-mail into multiple folders based on more amorphous criteria than standard rules contemplate. While Steve Masters's e-mail can easily be copied to a related folder, the other relevant factors in his message—that it concerns finance, Dubai and Project X, among other possible criteria—are much more difficult to translate into actions. The subject line might cover one or two of the criteria and be susceptible to formal manipulation by an Outlook rule, but that often places too much trust in any given sender's subject lines. What we need is a quick, automated method to assign values to e-mails in both your Inbox and Sent Items such that a PowerShell script can be run to allocate them to the correct folders.

Programming Outlook Rules

This section takes a stab at demonstrating programmatic creation of two Outlook rules. One rule reads a message’s subject line for the specific string “Notification” and then copies relevant messages to a specified folder (named Notifications).

The first piece of business is to invoke the Outlook API using code such as the following. This code gives us access to the messaging namespace of the Outlook API, in which typical objects are e-mail messages, Outlook rules and mail folders, among other objects (for more information, see https://msdn.microsoft.com/en-us/library/ff866465.aspx).

With the namespace in hand, we specify the originating folder (the Inbox), create a new rule and specify the folder to copy to (Notifications).

Navigating Folders

It’s an interesting exercise to run some lines of code to see how folders are enumerated in the MAPI namespace. The following lines illustrate how to navigate to various levels of depth in the folder tree:

$namespace.Folders
#in my Outlook, gives '[email protected]'
#and 'Public Folders - [email protected]'

$namespace.Folders.Item(1)
#gives '[email protected]'

$namespace.Folders.Item(2).Folders
#gives 'Public Folders - Favorites' and 'Public Folders - All'

$namespace.Folders.Item(1).Folders
#gives all subfolders under '[email protected]' main Folder

$namespace.Folders.Item(1).Folders.Item(1)
#gives one subfolder, 'Deleted Items'

$namespace.Folders.Item(1).Folders.Item('My Projects').Folders
#gives all the subfolders in 'My Projects'

$namespace.Folders.Item(1).Folders.Item('My Projects')
.Folders.Item('Outlook scripts').Items 
#gives all emails under the 'Outlook scripts' subfolder
#of 'My Projects' folder

Having created a new rule instance, we can define its parameters and properties like this:

The first line relates the rule to the subject line of an incoming e-mail. The string to look for (“Completed Notification”) is specified, and the action to take is CopyToFolder (as opposed, for example, MoveToFolder). The invocation recites the action and the destination folder.

Figure 1 shows the second example of programmatically creating a rule, where we look at recipients rather than the subject line.

Figure 1. Creating a Rule for Recipients

All e-mail messages from Maria Gonzalez at the companyname.com domain will be copied to the Francisco subfolder.

For a good general primer on programming Outlook rules, see https://tinyurl.com/ayyack5.

Managing Messages with a Script

Clearly, one can do a lot in Outlook with the built-in rule facility, but what if you want to divide messages into categories like Project, Finance, Human Resources, Recipient Name, Sending Division, Month of Receipt, City, State, Country or any other of a virtually limitless number of categories, where any given e-mail could apply to multiple categories that are not identifiable from the subject or even the body of the message? In cases like these, a custom script can function like a special rule.

In the following example, we manage the Sent Items folder by manually marking the subject line of each message with acronyms ("\\\Admin,FOR", for example), where each acronym relates the message to a target folder (Administrative,Foreign in the example) to which the e-mail should be copied. The process calls for manual action only to mark the subject lines of sent items with your designated acronyms. 

When the script runs, it finds the acronyms and copies the e-mail to as many folders as the acronyms listed in the subject line refer to. In addition, sent items are “aged” out of those folders by code that tests the respective received and sent dates for a given period and moves relevant messages to their respective resting places once the age criteria is met.

The function I wrote is called CopyMove-Email. It has three parameters: a list of acronyms or symbols, the corresponding list of folders and an integer representing the maximum number of days to retain a message under Sent Items before moving it to safekeeping. (For use with Inbox items—the code is not shown—a fourth parameter should be added to indicate the number of days to maintain an Inbox item.)

Then, as with the case of creating a rule, the messaging API is invoked:

If you look in Task Manager, you’ll see two instances of Outlook. One is the original, displayed version that you are working in, and the other is a background Outlook process being used by this script.

Next, we construct a timespan to mark the absolute limit for keeping sent items in that folder, whether the item is marked for copying or not.

Using the timespan, we create the dates against which to test each e-mail item in the Sent Items folder.

We also need a string-formatted date to use in naming text files that will store a specific day's run of this application. The text files will store, respectively, mail that was copied and mail that was moved.

Then we need to accumulate data about moves and copies in temporary holding arrays:

Experience shows that merely looping through all the messages in the Sent Items folder once isn’t enough; on a first loop, some items are handled but others aren’t touched. It may take three or four such loops to handle all the items that need handling. The number of loops probably depends on how many mail items are ready for copy-move operations and other factors in how Outlook interoperates with your computer. In any event, the solution is to use a Do-While structure to keep running the loop until all marked items have been properly managed.

The application is now ready to begin parsing through Sent Items:

Note that [email protected] is the author's Outlook name for the group of folders that includes Sent Items. You should, of course, use the name that shows up in your own Outlook client.

The first If test is against the established maximum-days window and for the existence of either the \\\ tag or the /// tag:

With a matching e-mail in hand, test it for each acronym in the $acronyms parameter:

For each matching acronym, the script makes a copy of the subject e-mail and moves the copy to the folder that matches the acronym. This part of the code is shown in Figure 2. Essentially, this copies the message to the new folder while also leaving it in the original Sent Items folder.

Figure 2. Copying Code Based on Acronyms

The next action for these kinds of mail items (shown in Figure 3) is to move them to Sent Items OLD for more permanent storage and also for later transfer to a text file documenting the move-copy actions.

Figure 3. Moving Items to Sent Items OLD

Then messages in Sent Items that are past the maximum retention period should be moved to Sent Items OLD. Their data is also stored for moving into the related text file. (See Figure 4.)

Figure 4. Managing Message Retention Limits

The last action to take is moving data about moved and copied items into the text files set up to hold that data:

You can call the CopyMove function with parameters, including the list of acronyms and the list of related folder names, plus the maximum number of days to keep sent items in that folder before saving them to Sent Items OLD:

Wrapping Up

All the power and flexibility of Office applications is exposed in their APIs and open to being adapted
to endless scenarios and needs by using PowerShell—or C# and other languages.  I use PowerShell because I find that it’s more fun than the others!

As an afterword, I’d note that scheduled tasks can be configured to include the code I’ve shown, but a certain number of gotchas will manifest themselves in the process, not least of which is that the task will not run if the machine is not connected to the network. So, remote users relying on a VPN, for example, might be out of luck if, as is usually the case, the connection automatically shuts down after a certain period of nonuse (like when you go to bed at night). Thus, the app can be scheduled to run only during times when you know the network connection is active.


Joe Leibowitzis an infrastructure consultant who specializes in Microsoft’s identity management products.

Sours: https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/powershell-managing-an-outlook-mailbox-with-powershell


503 504 505 506 507