Sunday, 20 July 2014

Disable Active Directory User Account and Send Report to your mailbox using Powershell

This script disables AD account, removes all group membership and sends the report to your inbox.

  • Save the script to Process-Leaver.ps1 file.
  • Run it from PowerShell console.
  • It will prompt you to enter the user name you want to disable.
  • The user who runs the script must have the right to send emails on exchange server.
  • Change the script as necessary to align with your needs.

_______________________________________________________________________________

Import-Module ActiveDirectory
$Adleaver = @{}
[String]$leaver = Read-Host "Enter the leaver account"
Try {
    $Adleaver = Get-AdUser $leaver -Properties WhenCreated,mail -ErrorAction Stop | Select Name,SamAccountName,ObjectClass,UserprincipalName,Mail,SID,WhenCreated,Enabled
    If(((Get-ADuser $leaver).enabled) -eq $False) { Write-Host "Account is already Disabled"; Return }
    Else { $Adleaver }
}
Catch {
    Write-Host "The user can't be found. Please check the name again."
    Write-Host "$_.Exception.Message"
    Return
}
$bool = Read-Host "Is this the right user? (y=yes) or (anything else=no)"
If (!($bool -eq 'y')) {
    Return
}
Else {
    # Whoami ~ Powershell
    [String]$Usr = $env:USERDOMAIN + "\" + $env:USERNAME

    $a = "<style>"
    $a += "BODY{background-color:white;}"
    $a += "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
    $a += "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:lightgrey}"
    $a += "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:lightblue}"
    $a += "</style>"

    $Pre = "<h3>The Report on Leaver Account</h3>"
    $Pre += "Full Name: "
    $Pre += @($Adleaver."Name")
    $Pre += "<br/> SamAccountName: "
    $Pre += @($Adleaver."SamAccountName")
    $Pre += "<br/> ObjectClass: "
    $Pre += @($Adleaver."ObjectClass")
    $Pre += "<br/> UserPrincipalName: "
    $Pre += @($Adleaver."UserPrincipalName")
    $Pre += "<br/> Email Address: "
    $Pre += @($Adleaver."Mail")
    $Pre += "<br/>SID: "
    $Pre += @($Adleaver."SID")
    $Pre += "<br/>Account Created on: "
    $Pre += @($Adleaver."WhenCreated")
    $Pre += "<br/><br/><hr>"
    $Pre += "<h4>User's Group Membership Details</h4>"
   
    $Post = "<p>The user account is disabled by automated Powershell script.<br/>"
    $Post += "<br/>Run On: "
    $Post += $env:COMPUTERNAME
    $Post += "<br/>Domain: "
    $Post += $env:USERDNSDOMAIN
    $Post += "<br/>By: "
    $Post += $Usr
    $Post += "<br/>Date: "
    $Post += (Get-Date)
    $Post += "</p>"
    $Post += "Note: Please keep the attachment in case you need to recover the user account ."
     
    Write-Host "Pulling user's groupmembership from AD..."
    Get-ADPrincipalGroupMembership $leaver | Select SamAccountName,Name,GroupCategory,GroupScope | Sort Name | Out-String
 
    #Building HTML Report body
    $mBody = Get-ADPrincipalGroupMembership $leaver | Select SamAccountName,Name,GroupCategory,GroupScope | Sort Name | ConvertTo-HTML -head $a -PreContent $Pre -PostContent $Post | Out-String
    #$mBody | Out-File "$leaver_report.html"

    Get-ADPrincipalGroupMembership $leaver | Select SamAccountName,Name,GroupCategory,GroupScope | Export-Csv "MemberOf_$leaver.csv" -notypeinformation
 
    #Strip out all group membership and disable the account
    Remove-ADPrincipalGroupMembership $leaver
    Disable-ADUser $leaver

    $From = "leaver@mydomain.co.uk"
    $To = "it.help@mydomain.co.uk"
    $Sub = "AD User Terminated: $leaver"
    $Smtpsrv = "mysmarthost.server"
 
    Send-MailMessage -From $From -To $To -Subject $Sub -Body $mBody -BodyAsHtml -SmtpServer $SmtpSrv -Attachment "MemberOf_$leaver.csv"
    Remove-Item "MemberOf_$leaver.csv"
}
________________________________________________________________________________

Saturday, 21 June 2014

Get Active Directory Group Membership Report to your mailbox using PowerShell

This script creates the AD group membership report and sends it to your mailbox.

  • Save the script to a file called Get-GroupReport.ps1.
  • The user who runs the report must have the right to send emails on the exchange server. 
  • Change the script as necessary to align with your needs.
________________________________________________________________________

Param([Parameter(Mandatory=$true)] [String]$GroupName)
Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter {Name -like $GroupName} -Properties * | Select Name,WhenChanged

<#
.SYNOPSIS
This script produces a report for the given AD security group
.DESCRIPTION
The report includes the name of the matching group, the total number of group member, when the group was last modified and a list of user in the group.
.SYNTAX
.\Get-GroupReport -GroupName <string[]>
.EXAMPLES
Get-GroupReport -GroupName *Admin*
This will create a report for all group whose name includes Admin
#>

$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:lightgrey}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:lightblue}"
$a = $a + "</style>"

$gcount = $groups.length
$today = ((Get-Date).ToString('dd/MM/yyyy'))
$Global:frag = ""

$rheader = "Report Created Date : "
$rheader = $rheader + $today
$rheader = $rheader + "<br />"
$rheader = $rheader + "Total Group : "
$rheader = $rheader + $gcount
$rheader = $rheader + "<hr>"

$FootNote = "<br/>End of report<hr> The story you have read is true. Only the names have been changed to protect the innocent."

Function Get-Members ($group){
$Members = Get-ADGroupMember $group | Select Name,SamAccountName,ObjectClass | Sort Name
return $Members
}

Foreach ($group in $groups) {
    $count = (@(Get-AdGroupMember $group.Name).count)
    $dateChanged = (($group.WhenChanged).ToString('dd/MM/yyyy hh:mm:ss'))
    $Name = "<h4>"
    $Name = $Name + $group.Name
    $Name = $Name + "</h4>"
    $Name = $Name + "Total Member(s) : "
    $Name = $Name + $count
    $Name = $Name + "<br/>"
    $Name = $Name + "Last Modified : "
    $Name = $Name + $dateChanged
    $Name = $Name + "<br/><br/>"

    $Global:frag += Get-Members $group.Name | ConvertTo-HTML -Fragment -PreContent $Name | Out-String
}

$ReportBody = ConvertTo-HTML -head "$a$rheader" -Body $frag -PreContent $FootNote | Out-String
#$ReportBody | Out-File "GroupMembershipReport.html"

$Subject = "Group Report on "
$Subject = $Subject + $GroupName
$To = "it.helpdesk@yourdomain.com"
$From = "admin@yourdomain.com"
$ExchangeServer = "YourExchangeServer"

#$cred=get-credential
$user = "admin@yourdomain.com"
$pass = ConvertTo-SecureString -AsPlainText "Pa55w0rd!01"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user,$pass

Send-MailMessage -From $From -To $To -Subject $Subject -Body $ReportBody -BodyAsHtml -SmtpServer $ExchangeServer -Credential $cred
#-Attachments "GroupMembershipReport.html"
________________________________________________________________________

Sunday, 19 January 2014

PowerShell Text formatting for Out Of Office message

PowerShell allows you to embed special characters within the string. These special characters are denoted using escape sequences. Escape sequences begin with the back tick (`), the one next to number 1 key on your keyboard.

`b => Backspace
`r => Carriage return
`n => New line
`t => Tab

Alternatively, if you are using PowerShell ISE, you can use preformatted text variable beginning with @” and ending with “@. In order to make this work, @” has to be the last thing where you define your string variable and “@ has to be on the new line at the end of your text and the first thing on that line. Otherwise it won’t work.
For instance,

$OOFMsg = @”
Thanks for your email.
I am out of office at the moment and will get back to you upon my return.
Regards,
Naw
“@

To Enable the Out of Office message

Unfortunately, the text formatting from PowerShell doesn't work on Exchange Mailboxes. Instead you will have to use html tags to embed line break as below.

$OOFMsg = “Thanks for your email.<br><br>I am out of office at the moment and will get back to you upon my return. <br><br>Regards, <br><br>Naw”

Set-MailboxAutoReplyConfiguration “Naw Awn” –AutoReplyState enabled –ExternalAudience all –ExternalMessage $OOFMsg –InternalMessage $OOFMsg



Out of Office Message begins from tomorrow till the next 3 days

Set-MailboxAutoReplyConfiguration “Naw Awn” –AutoReplyState scheduled –StartTime (Get-Date –uformat “%d/%m/%y”(Get-Date).AddDays(1)) –EndTime (Get-Date –uformat “%d/%m/%y”(Get-Date).AddDays(4)) ExternalAudience all –ExternalMessage $OOFMsg –InternalMessage $OOFMsg

To disable the Out of Office message

Set-MailboxAutoReplyConfiguration “Naw Awn” –AutoReplyState disabled

MS Exchange 2013 PowerShell Cmdlets Collection - Part 3

Sharing and Collaboration Cmdlets

Sharing Cmdlets

Get|New|Remove|Set|Test-OrganiztionRelationshihp
Get|New|Remove|Set-SharingPolicy

Public Folder Cmdlets

Get|New|Remove|Set-PublicFolder
Update-PublicFolderMailbox
Get-PublicFolderMailboxDiagnostics
Get|Set|Disable|Enable-MailPublicFolder
Add|Get|Remove-PublicFolderClientPermission
Get|New|Remove|Set|Suspend|Resume-PublicFolderMigrationRequest
Get-PublicFolderMigrationRequestStatistics
New-MoveRequest
New-PublicFolderMoveRequest
.\Move-PublicFolderBranch.ps1

Site Mailbox Cmdlets

Get|Set|Test|Update-SiteMailbox
Get-SiteMailboxDiagnostic
Get|New|Remove|Set-SiteMailboxProvisioningPolicy

Move and Migration Cmdlets

Get|Set-MigrationConfig
Get|Remove-MigrationUser
Get|New|Set-MigrationEndPoint
Get-MigrationStatistics
Get-MigrationUserStatistics
Get|New|Remove|Set|Start|Stop|Complete-MigrationBatch
Export-MigrationReport
Test-MigrationServerAvailability
Get|New|Remove|Resume|Suspend|Set-MoveRequest
Get-MoveRequestStatistics

Federation and Hybrid Configuration Cmdlets

Federation Cmdlets

Add|Remove-FederatedDomain
Get-FederatedDomainProof
Get|Set-FederatedOrganizationIdentifier
Get-FederationInformation
Get|New|Remove|Set|Test-FederationTrust
Test-FederationTrustCertificate
Get|Set-PendingFederatedDomain

Hybrid Configuration Cmdlets

Get|New|Remove|Set|Update-HybridConfiguration
Get|Set-HybridMailFlow
Get-HybridMailflowDataCenterIPs
Get|New|Remove|Set-OnPremisesOrganization

Monday, 13 January 2014

MS Exchange 2013 PowerShell Cmdlets Collection - Part 2

Email Address & Address Book Cmdlets

Address Book Policy

Get|New|Set|Remove-AddressBookPolicy

Address List

Get|Move|New|Remove|Set|Update-AddrerssList
Disable|Enable-AddressListPaging
Get|Set|Restore-DetailsTemplate
New|Get|Remove|Set|Update-GlobalAddressList

Email Address Policy

Get|New|Remove|Set|Update-EmailAddressPolicy

Offline Address Book

Get|New|Remove|Move|Set|Update-OfflineAddressBook
Get|New|Remove|Set-OabVirtualDirectory

Client Access Cmdlets

Client Access

Get|Set-CasMailbox
New|Remove|Get|Set-WebServicesVirtualDirectory
Get|Set-ClientAccessServer
Test-WebServiceConnectivity
Enable|Disable-ServiceEmailChannel
Get-TextMessagingAccount
Get|Set-RpcClientAccess
Get-ClientAccessArray
Send-TextMessagingVerificationCode

OWA

Get|Set|New|Remove-OwaVirtualDirectory
Get|Set|New|Remove-OwaMailboxPolicy

ActiveSync

Get|Clear|Remove-ActiveSyncDevice
Get|Clear|Remove-MobileDevice
Get|RemoveNew|Set-ActiveSyncVirtualDirectory
Test-ActiveSyncConnectivity
Get-ActiveSyncDeviceStatistics
Get|New|Remove|Set-ActiveSyncMailboxPolicy
Get|New|Remove|Set-MobileDeviceMailboxPolicy
Export-ActiveSyncLog

POP3 & IMAP4

Get|Set-PopSettings
Get|Set-ImapSettings
Test-PopConnectivity
Test-ImapConnectivity

AutoDiscover

Export-AutoDiscoverConfig
New|Remove|Get|Set-AutodiscoverVirtualDirectory
New|Remove|Get|Set-OutlookProvider

Availability

Add|Get|Remove-AvailabilityAddressSpace
Get|Set-AvailabilityConfig

Outlook Anywhere

Get|Set-OutlookAnyWhere

Powershell Virtual Directory

Get|New|Remove|Set-PowershellVirtualDirectory
Test-PowershellConnectivity

High Availability Cmdlets

DAG

Add|Remove-DatabaseAvailabilityGroupServer
Get|New|Remove|Restore|Set|Start|Stop-DatabaseAvailabilityGroup

DAG Network

Get|New|Remove|Set-DatabaseAvailabilityGroupNetwork

Mailbox Database Copy

Add|Remove|Resume|Set|Suspend|Update-mailboxDatabaseCopy
Move-ActiveMailboxDatabase

Health & Status

Get-MailboxDatabaseCopyStatus
Test-ReplicationHealth

Active Directory Cmdlets

Get|Set-AdServerSettings
Get|Set-OrganizationConfig
Get-DomainController
Get-OrganizationalUnit

Server health, Monitoring & Performance Cmdlets

New|Remove|Get|Set-ThrottlingPolicy
Get|Set-ThrottlingPolicyAssociation
New|Remove|Get|Set-ResourcePolicy
New|Remove|Get-WorkloadManagementPolicy
New|Remove|Get|Set-WorkloadPolicy
Get|Set-EventLogLevel
Dump|Reset-ProvisioningCache
Get-MonitoringItemIdentity
Get-ServerHealth
Get|Set-ServerComponentState
Get-MonitoringItemHelp
Get-HealthReport
Add|Get|Remove-GlobalMonitoringOverride
Add|Get|Remove-ServerMonitoringOverride
Invoke-MonitoringProbe

Global Cmdlets

Test-ServiceHealth
Update-ExchangeHelp
Get|Set-ExchangeServer
Get-ExchangeServerAccessLicenseUser
Get-ExchangeServerAccessLicense
Get|Set-ExchangeAssistanceConfig
Get|Set-Notification

Cmdlet Extension Agent

Get|Set|Disable|Enable-CmdletExtensionAgent

Anti-Spam & Anti-Malware Cmdlets

Anti-Malware

Get|Set-MalwareFilteringServer
Get|New|Remove|Set-MalwareFilterPolicy
Disable|Enable-MalwareFilterRule
Get|New|Remove|Set-MalwareFilterRule

Anti-Spam Connection Filter

Get|Set-IPAllowListConfig
Add|Get|Remove-IPAllowListEntry
Add|Get|Remove|Set|Test-IPAllowListProvider
Get|Set-IPAllowLlistProviderConfig
Get|Set-IPBlockListConfig
Add|Get|Remove-IPBlockListEntry
Add|Get|Remove-IPBlockListProvider
Get|Set-IPBlockListProviderConfig

Anti-Spam Content Filter

Get|Set-ContentFilterConfig
Add|Get|Remove-ContentFilterPhrase
Update-SafeList

Recipient Filter

Get|Set-RecipientFilterConfig

Sender Filter

Get|Set-SenderFilterConfig

Sender ID

Get|Set-SenderIdConfig
Test-SenderId

Sender Reputation

Get|Set-SenderReputationConfig

Mailbox Junk Email Configuration

Get|Set-MailboxJunkEmailConfiguration

Anti-Spam & Anti-Malware Management

Get-AgentLog

Saturday, 11 January 2014

MS Exchange 2013 PowerShell Cmdlets Collection - Part 1

Mailbox Related Cmdlets

Server Cmdlets

Get|Set-MailboxServer
Test-MapiConnectivity
Export-MailboxDiagnosticLogs
Test-AssistantHealth

Database Cmdlets

New|Get|Set|Remove-MailboxDatabase
Remove-StoreMailbox
Get-StorageUsageStatistics
Dismount|Mount-Database
Move-DatabasePath
Get-FailedContentIndexDocuments

Other Mailbox Cmdlets

Test-ExchangeSearch
Get-MessageCategory
Search-Mailbox
New|Get|Set|Enable|Disable|Remove-InboxRule

MailFlow Related Cmdlets

Message Tracking Cmdlets

Get-MessageTrackingLog
Get-MessageTrackingReport
Search-MessageTrackingReport

Queue Management Cmdlets


Get|Export|Redirect|Remove|Resume|Suspend-Message
Get|Resume|Retry|Suspend-Queue
Get-QueueDigest
Add|Get|Remove|Set-ResubmitRequest

Delivery Status Notification, DSN, Cmdlet


Get|New|Remove|Set-SystemMessage

Transport Core Cmdlets


Get|Set-AdSite
Get|Set-AdSiteLink
Get|Set-FrontendTransportService
Get|Set-MailboxTransportService
Get-NetworkConnectionInformation
Get|Set-TransportConfig
Get-TransportPipeline
Get|Set-TransportServer
Get|Set-TransportService
Test-MailFlow
Test-SmtpConnectivity

Connector Cmdlets


Get|New|Remove|Set-ReceiveConnector
Get|New|Remove|Set-SendConnector
Get|New|Remove|Set-DeliveryAgentConnector
Get|New|Remove|Set-ForeignConnector

Domain Cmdlets

Get|New|Remove|Set-AcceptedDomain
Get|New|Remove|Set-RemoteDomain
Get|New|Remove|Set-X400AuthoritativeDomain

Edge Cmdlets

Get|New|Remove-EdgeSubscription
Start|Test-EdgeSynchronization
Get|New|Set-EdgeSyncServiceConfig

Transport Agent Cmdlet

Disable|Enable|Get|Install|Set|Unistall-TransportAgent

Recipient Related Cmdlets

Calendar Cmdlets

Get-CalendarDiagnosticLog
Get|Set-CalendarNotification
Get|Set-CalendarProcessing
Test-CalendarConnectivity

Group Cmdlets

Disable|Enable|Get|New|Remove|Set-DistributionGroup
Add|Get|Remove|Update-DistributionGroupMember
Get|New|Remove|Set-DynamicDistributionGroup
Get|Set|-Group –anr (ambiguous name resolution)


Import Export Mailbox Cmdlets


Get|New|Remove|Resume|Set|Suspend-MailboxExportRequest
Get-MailboxExportRequestStatistics
Get|New|Remove|Resume|Set|Suspend-MailboxImportRequest
Get-MailboxImportRequestStatistics

Configuration Cmdlets


Get|Set-MailboxAutoReplyConfiguration
Get|Set-MailboxCalendarConfiguration
Get|Set-MailboxCalendarFolder
Get|New-MailboxFolder
Get|Set-MailboxMessageConfiguration
Get|Set-MailboxRegionalConfiguration
Get|Set-MailboxSpellingConfiguration
Export|Import-RecipientDataProperty

Mailbox, User and Contact Cmdlets

Disable|Enable|Get|New|Remove|Set-App
Get|Set-Contact
New-MailMessage
Connect|Disable|Enable|Get|New|Remove|Set-Mailbox
Disable|Enable-MailboxQuarantine
Disable|Enable|Get|New|Remove|Set-MailContact
Disable|Enable|Get|New|Remove|Set-MailUser
Get|Update-Recipient
Get|Set-ResourceConfig
Get|Set-User
Get|Remove|Set-UserPhoto
Get-UserPrincipalNameSuffix

Mailbox Repair Cmdlet

Get|New|Remove-MailboxRepairRequest

Permission Cmdlets

Add|Get|Remove|Set-MailboxFolderPermission
Add|Get|Remove-MailboxPermission

Reports Cmdlets

Get-MailboxFolderStatistics
Get-MailboxStatistics

Remote Mailbox Cmdlet

Disable|Enable|Get|New|Remove|Set-RemoteMailbox

Restore Mailbox Cmdlets

Get|New|Remove|Resume|Set|Suspend-MailboxRestoreRequest
Get-MailboxRestoreRequestStatistics

Role Based Permission Related Cmdlets

Role Group cmdlets

New|Remove|Get|Set-RoleGroup
Add|Remove|Get|Update-RoleGroupMember

Management Role Cmdlet

Get|New|Remove-ManagementRole

Role Entry Cmdlet

Get|Add|Remove|Set-ManagementRoleEntry

Role Scope Cmdlet

Get|New|Remove|Set-ManagementScope

Role Policy Cmdlet

Get|New|Remove|Set-RoleAssignmentPolicy

Role Assignment Cmdlet

Get|New|Remove|Set-ManagementRoleAssignment

Security Related Cmdlets

Add|Get|Remove-ADPermission
Get|Set-AuthConfig
Get|New|Remove|Set-AuthServer
Enable|Export|Import|Get|New|Remove-ExchangeCertificate
Test-OAuthConnectivity
Get|New|Remove|Set-PartnerApplication
Get-SecurityPrincipal
Get-Trust

Messaging Policy & Compliance Cmdlets

Administrator Audit Log

Get|Set-AdminAuditLogConfig
New-AdminAuditLogSearch
Search-AdminAuditLog

Mailbox Audit Log

New-MailboxAuditLogSearch
Search-MailboxAuditLog

Message Classification

Get|New|Remove|Set-MessageClassification

Data Loss Prevention

Get|New|Remove|Set-ClassificationRuleCollection
Get-DataClassification
Get-DlpPolicy
Export|Import-DlpPolicyCollection
Get|Import|Remove-DlpPolicyTemplate

Transport Rules

Disable|Enable|Get|New|Remove|Set-TransportRule
Get-TransportRuleAction
Export|Import-TransportRuleCollection
Get-TransportRulePredicate

IRM

Get|Set|Test-IRMConfiguration
Disable|Enable|Get|New|Remove|Set-OutlookProtectionRule
Get-RMSTemplate

Journaling

Disable|Enable|Get|New|Remove|Set-JournalRule
Export|Import-JournalRuleCollection

MRM

Get|New|Remove|Set-ManagedContentSettings
Get|New|Remove|Set-ManagedFolder
Start|Stop-ManagedFolderAssistant
Get|New|Remove|Set-MaganedFolderMailboxPolicy
Get|New|Remove|Set-RetentionPolicy
Get|New|Remove|Set-RetentionPolicyTag

In-Place eDiscovery & In-Place Hold

Get|New|Remove|Set|Start|Stop-MailboxSearch

Saturday, 28 December 2013

Outlook VB Script - Detach attachments, Embed hyper link and Move email

The following VB script on outlook will move the email to a subfolder, detach the attachments, save them on the hard drive and embed the link on your receiving email. Tried and tested with MS Outlook 2007/2010 and worked perfectly fine but amend as necessary and use it at your own risk.
  • Task 1: Create an MS Access database and a table as described on database section
  • Task 2: copy and paste the code into Outlook Visual Basic Editor (Alt+F11), under Microsoft Office Outlook Objects, ThisOutlookSession.
  • Task 3: change the ConnectStr path to reflect the location of your Access Database and ensure the user has the necessary right on that folder.


Assumption
Inbox subfolder in Outlook has to be created beforehand.
Network share folders where the attachments are saved must be created and assigned necessary permissions beforehand.
Network share folders name (FsFolder) on the database table must end with “\”
e.g. if sharename is \\FileServer\Users\Someone, sharename must be entered as \\FileServer\Users\Someone\ in the FsFolder field.

Script Logic

Database: EmailContacts.accdb
Table: Email
ID
Auto Number
EmailAddress
Text
SubFolder
Text
FsFolder
Text



Option Explicit
Dim SFolder As String
Dim SaveLocation As String

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
'Check the sender email address and move the mail to corresponding folder
Dim InboundEmails
Dim Email
Dim i As Integer
Dim DestFolder As Outlook.MAPIFolder
Dim olAttachments As Outlook.Attachments
Dim olAttachFile As Outlook.Attachment
Dim AttachCount As Integer
Dim intIndex As Integer
Dim FilePath As String
Dim FileLink As String

SFolder = "Service"
InboundEmails = Split(EntryIDCollection, ",")

'loop all incoming email items
For i = 0 To UBound(InboundEmails)
Set Email = Application.Session.GetItemFromID(InboundEmails(i))
If CheckAddress(Email.SenderEmailAddress) Then
    ‘MsgBox "You Just have recieved a mail from " & Email.SenderEmailAddress & "." & Chr(13) & Chr(10) & "and he said : " & Email.Subject   
    AttachCount = Email.Attachments.Count
    If AttachCount > 0 Then
        ‘MsgBox "This email has " & AttachCount & " attachments."
        For intIndex = AttachCount To 1 Step -1
            Set olAttachFile = Email.Attachments.Item(intIndex)
            Dim ReNameFile As String
            ReNameFile = Time
            ReNameFile = Replace(ReNameFile, Chr(58), Chr(46))
            ReNameFile = ReNameFile & "." & olAttachFile.FileName
            FilePath = SaveLocation & ReNameFile
            olAttachFile.SaveAsFile FilePath           
            FileLink = FileLink & Chr(34) & FilePath & Chr(34) & Chr(32) & vbCrLf
            olAttachFile.Delete
        Next
        Email.Body = Email.Body & vbCrLf & vbCrLf & "Removed Attachments" & vbCrLf & vbCrLf & FileLink
        Email.Save
    End If
    Set DestFolder = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Folders(SFolder)
    Email.Move DestFolder
End If
Next
Set Email = Nothing
Set InboundEmails = Nothing

End Sub


Function CheckAddress(ByVal eAddress As String) As Boolean

Dim Connect As New ADODB.Connection
Dim Cmd As New ADODB.Command
Dim RecSet As New ADODB.Recordset
Dim ConnectStr As String

ConnectStr = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};" & _
            "DBQ=C:\Documents and Settings\N Awn\My Documents\EmailContacts.accdb;" & _
            "DefaultDir=C:\Documents and Settings\N Awn\My Documents;" & _
            "UID=admin;"

On Error Resume Next
Connect.ConnectionString = ConnectStr
Connect.Open
'Set RecSet = Connect.Execute("SELECT EmailAddress FROM Email")
Cmd.ActiveConnection = Connect
Cmd.CommandText = "SELECT EmailAddress, SubFolder, FsFolder FROM Email"
Set RecSet = Cmd.Execute

Dim Sender As String
Do While Not RecSet.EOF
    Sender = Trim(RecSet("EmailAddress"))
    If eAddress = Sender Then
        CheckAddress = True
        SFolder = Trim(RecSet("SubFolder"))
        SaveLocation = Trim(RecSet("FsFolder"))
        RecSet.Close
        Set RecSet = Nothing
        Connect.Close
        Connect.ConnectionString = ""
        Exit Function
    Else
    CheckAddress = False
    End If
    RecSet.MoveNext
Loop

RecSet.Close
Set RecSet = Nothing
Connect.Close
Connect.ConnectionString = ""

End Function
'coded By Naw Awn 24/02/2013. Amended on 31/03/2013