Geeks With Blogs

Lance's TextBox

The question was posed on the newsgroup: how do I delete emails (over POP or IMAP) on a remote mail server through PowerShell?

Here’s an example of one way to do it – through the use of the get-imap, set-imap, and get-pop cmdlets that are included in NetCmdlets.

## deleteemail.ps1: Delete all email from a particular sender ## deletes emails from an IMAP or POP server. ## Returns a collection of objects containing information about deleted emails (from, to, subject) or mailboxes (name, flags) in a mail server. ##  ## By default, IMAP will be used.  To use pop, add set the pop argument to 1.  param( [string] $server = "",
[System.Management.Automation.PSCredential] $cred,
[string] $sender = "",
[int] $pop = 0,
[int] $imapexpunge = 0

function get-emailaddress($header) {
[int]$index = $header.IndexOf("<")
if ($index -gt -1) {
$retval = $header.Substring($index+1)
$index = $retval.IndexOf(">")
$retval = $retval.Remove($index)
return $retval;
else {
return $header;

if ($server -eq "") {
$server = read-host "Mail Server [localhost]" if ($server -eq "") { $server = "localhost" }

if ($pop -eq 1) {
$msgs = (get-pop -server $server -cred $cred)
else {
$msgs = (get-imap -server $server -cred $cred)

Foreach ($msg in $msgs) {
$address = get-emailaddress($msg.From)
if ($address -eq $sender) {
if ($pop) {
get-pop -server $server -cred $cred -deletemessage $msg.Id
else {
set-imap -server $server -cred $cred -message $msg.Id -expunge:$imapexpunge -delete

write-host "Exception occurred (please find more information below), script execution was terminated." break }

There you are.  First I have defined a function to take a sender address and parse out the email address (in case the sender address includes a friendly name – if you’re not familiar with this, its not really important anyway).  Then I check to make sure we have a server to connect to, and depending on whether or not we’re using POP or IMAP, I connect to the server and get a list of waiting messages using get-pop or get-imap.  Finally, I loop through each message, and if the sender address matches the one I’m looking for, I output and then delete the message.  








Technorati Tags: , , , ,
Posted on Wednesday, September 24, 2008 3:44 PM PowerShell | Back to top

Comments on this post: Deleting emails from PowerShell

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Lance Robinson | Powered by: