Search Email AND output TAB delimited

I was trying to help someone who wanted a TAB delimited output file in PowerShell.
 
After some searching around and some help from the boards, I came up with this;
 
<———— Start POSH —————————————————————–>
 
$info = New-Object -ComObject Outlook.Application
$objNamespace = $info.GetNamespace("MAPI")
$objFolder = $objNamespace.GetDefaultFolder(6).Folders.Item("Reporting")
$colItems = $objFolder.Items
foreach ($item in $colItems) {
 If ($item.SenderEmailAddress -eq "Bill.Smith@myob.com") {
 Write-Host "$($item.SenderEmailAddress) `t $($item.SentOn) `t $($item.Subject)"
                   }
        }
 
<———–End Script ———————————————————————->
 
Or you could output to a file by removing the Write-Host and adding | Add-Content $path
 
<—————– Start POSH ————————————————————–> 
$path = "c:tempemail.txt"
$info = New-Object -ComObject Outlook.Application
$objNamespace = $info.GetNamespace("MAPI")
$objFolder = $objNamespace.GetDefaultFolder(6).Folders.Item("Merchant Reporting")
$colItems = $objFolder.Items
foreach ($item in $colItems) {
 If ($item.SenderEmailAddress -eq "Bill.Smith@myob.com") {
("$($item.SenderEmailAddress) `t $($item.SentOn) `t $($item.Subject)")| Add-Content $path
                   }
        }
 
< ————– End Script —————————————————————————->
What does it do?
 
Searches the In box for a sub folder and then for a sender.
writes them out to the screen or a file in a tab delimited format
Includes Senders name, Date/time sent and subject.
Its the `t that adds the tabs. `n adds a new line.  ‘r adds a line feed  
 

Reading Email with a script and doing stuff


I am setting up HP-Sim for a client. One of the things they wanted was for SIM alerts to go directly to their Incident manager software. If the Email is formatted correctly, it will generate a Trouble Ticket automatically. Unfortunately, the email from HP-Sim is set in stone. You can change the subject line but not the body of the message. And that’s where my customer needs the properly formatted information. So, I set up a Rule in Outlook that runs an application upon receipt of a message with specified words in the Subject line. The scrip reads the mail, and then re-sends it to the help-desk app in the proper format. Here is the script, I think it’s a good example of how to read and act upon an email message.

PS: WordPress is converting the quote “, the ‘less than’ charactor and the ‘greater than’ charactor in my script so be alert!


Set objOL = WScript.CreateObject ("outlook.application")
Set olNS = objOL.GetNameSpace("MAPI")
Set fld = olNS.GetDefaultFolder(6)
set msg = fld.items

  For Each item In msg

    If item.SenderEmailAddress = "system.generated@myob.com" Then ‘      ProductionMsg = item.body ‘       Mailit(ProductionMsg)
    Else
             On Error GoTo 0
             WScript.Quit
    End If
 Next
Sub Mailit(ProductionMsg)
adminmail = "helpdesk@myob.com"
‘
Cat="Category=System Generated Requests" ‘CatSub="CategorySub=HP-SIM" ‘Sev="Severity=Tier 3"  ‘ProductionMsg = Cat & VbCrLf & CatSub & VbCrLf & Sev & VbCrLf &  VbCrLf & ProductionMsg
 smtp = "smtp.myob.com"
 Set mailing = CreateObject("CDO.Message")
 Set wshNet = CreateObject("WScript.Network")

 mailing.From = ("system.generated@myob.com")
 mailing.To = adminmail
 mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
 mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
 mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

‘ Only required if your SMTP server requires a user name and password

‘mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
‘mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "Ja…@company.com"
‘mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "SomePassword"

mailing.Subject = header & "HP-Sim Alert"
 mailing.TextBody = ProductionMsg
 mailing.Configuration.Fields.Update
 mailing.Send
 On Error GoTo 0

End Sub

You can also do stuff with PowerShell;


$info = New-Object -ComObject Outlook.Application
$objNamespace = $info.GetNamespace("MAPI")
$objFolder = $objNamespace.GetDefaultFolder(6).Folders.Item("HPSIMNotify")
$colItems = $objFolder.Items
foreach ($item in $colItems) {
 Write-Host $item.SentOn
}

This looks in the inbox (6) and looks for a sub folder called (“HPSIMNotify”)
It then tells you the date and time the message was sent.

What other folders can you look in?

 
Name

Value

Description

olFolderCalendar

9

The Calendar folder.

olFolderConflicts

19

The Conflicts folder (subfolder of Sync Issues folder). Only available for an Exchange account.

olFolderContacts

10

The Contacts folder.

olFolderDeletedItems

3

The Deleted Items folder.

olFolderDrafts

16

The Drafts folder.

olFolderInbox

6

The Inbox folder.

olFolderJournal

11

The Journal folder.

olFolderJunk

23

The Junk E-Mail folder.

olFolderLocalFailures

21

The Local Failures folder (subfolder of Sync Issues folder). Only available for an Exchange account.

olFolderManagedEmail

29

The top-level folder in the Managed Folders group. For more information on Managed Folders, see Help in Microsoft Office Outlook. Only available for an Exchange account.

olFolderNotes

12

The Notes folder.

olFolderOutbox

4

The Outbox folder.

olFolderSentMail

5

The Sent Mail folder.

olFolderServerFailures

22

The Server Failures folder (subfolder of Sync Issues folder). Only available for an Exchange account.

olFolderSyncIssues

20

The Sync Issues folder. Only available for an Exchange account.

olFolderTasks

13

The Tasks folder.

olFolderToDo

28

The To Do folder.

olPublicFoldersAllPublicFolders

18

The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.

olFolderRssFeeds

25

The RSS Feeds folder.

Want to see what the body of the message looks like?
 
Write-Host $item.body
 
How about the subject?
 
Write-Host $item.Subject
 
All together now;
 
#

$info = New-Object -ComObject Outlook.Application
$objNamespace = $info.GetNamespace('MAPI')
$objFolder = $objNamespace.GetDefaultFolder(6).Folders.Item('HPSIMNotify')
$colItems = $objFolder.Items
foreach ($item in $colItems) {
 Write-Host 'date/time sent: '$item.SentOn
 Write-Host 'Subject: ' $item.Subject
 Write-Host 'Body Text: '$item.body
}

#
 
 

Sending mail with PowerShell

The process to send mail is pretty simple.
It’s the attachment process that gets a little complicated.
 
I found this at http://blogs.inetium.com/blogs/mhodnick/archive/2006/11/29/powershell…

Which answered the question, How do I attach a file?

[System.Net.Mail.Attachment] $attachment = new-object
System.Net.Mail.Attachment $file

It is necessary to cast the $attachment variable to type
System.Net.Mail.Attachment, since new-object (in this instance)
returns a REFERENCE to an object of that type, not an ACTUAL OBJECT of
the type. But $msg.Attachments.Add($attachment) requires an actual
object. Hence the need for the cast.

So, here is my working code, enjoy!
 
#<————– Begin —————————————–>
$file = "r:dailylog.txt" <—-the file you want to attach
$sender = "joe@work.com"
$recipient = "susie@work.com"
$server = "mail.smtp.com"
$subject = "Sending a File " + [System.DateTime]::Now
$body = "I’m sending a file!"
$msg = New-Object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$attachment = New-Object System.Net.Mail.Attachment $file
$msg.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$client.Send($msg)
 $attachment.Dispose()
#<——————–End—————————————–>

from Shay Levy
Windows PowerShell MVP
http://blogs.microsoft.co.il/blogs/ScriptFanatic
PowerShell Toolbar: http://tinyurl.com/PSToolbar

To add 2 recipients
$msg.To.Add("te@domain.com")
$msg.To.Add(te@domain.com)
In the same way add cc and bcc:
$msg.cc.Add(…)
$msg.bcc.Add(…)

To compare and contrast here is basicaly the same thing in vbScript;
 
‘<————Begin———————————————–>
 
adminmail = "somebody@somewhere.com"

 smtp = "mail_server name or IP"
 Set mailing = CreateObject("CDO.Message")
 Set wshNet = CreateObject("WScript.Network")
 
 mailing.From = ("fromSomeone@somewhere.com")
 mailing.To = adminmail
 mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
 mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
 mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
 mailing.Subject = header & "Data Transfer Success logs"
 sFullProductionMessage = "See attached file…"  & vbcrlf
 mailing.TextBody = sFullProductionMessage
 mailing.Configuration.Fields.Update
 mailing.AddAttachment "R:dailylog.txt"
 mailing.Send
 On Error Goto 0
 
‘<—————————- END ———————————–>
 
What if you wanted the Attachment to be the body text?
 
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
‘Open the file for reading
Set f = fso.OpenTextFile("C:SendLogsdailylog.txt", ForReading)
‘The ReadAll method reads the entire file into the variable BodyText
BodyText = f.ReadAll
‘Close the file
f.Close
Set f = Nothing
Set fso = Nothing
 
And in your message function or sub or whatever;
 
 mailing.TextBody = BodyText
 
How about CC?
 
 
 If you want to send an SMS (text) msg to a phone, just use the phone number and the appropriate SMTP gateways.