Delete Emails from folders by X numbers of days
$conn
=
new-object
"System.data.sqlclient.SQLconnection"
$con
.ConnectionString =(“Data Source=localhost;Initial Catalog=EmailDW;Integrated Security=SSPI”)
$conn
.open()
$sqlcmd
=
new-object
"System.data.sqlclient.sqlcommand"
$sqlcmd
.connection =
$conn
$sqlcmd
.CommandTimeout = 600000
$Outlook
=
New-Object
-ComObject
Outlook.Application
$EmailsInFolder
=
$Outlook
.Session.Folders.Item(2).Folders.Item(
"Inbox"
).Folders.Item(
"SPAM Mail"
).Items
$Today
=
get-date
foreach
(
$email
in
$EmailsInFolder
)
{
IF
(
$now
-
$Email
.SentOn
-ge
30.)
{
$sent
=
$email
.SentOn
$sub
=
$email
.Subject
$sender
=
$email
.SenderName
$to
=
$email
.To
$sen
=
$email
.Sensitivity
$query
= "INSERT INTO dbo.EmailLog ( emailSentOn , emailSubject , emailSenderName , emailTo , emailSensitivity ) VALUES (
'$sent'
,
'$sub'
,
'$sender'
,
'$to'
,
'$sen'
) ”
$sqlcmd
.CommandText =
$query
$rowsAffected
=
$sqlcmd
.ExecuteNonQuery()
$email
.Delete()
}
}