Sie sind auf Seite 1von 2

// Connect to Exchange 2007 IMAP server (locally), without SSL.

using (ImapClient ic = new ImapClient("<server address>", "<user account>",


"<user password>", ImapClient.AuthMethods.Login, 143, false))
{
// Open a mailbox, case-insensitive
ic.SelectMailbox("INBOX");

// Get messages based on the flag "Undeleted()".


Lazy<MailMessage>[] messages =
ic.SearchMessages(SearchCondition.Undeleted(), false);

// Process each message


foreach (Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;

string sender = m.From.Address;


string fileName = string.Empty;

// Rules by Sender
switch (sender)
{
case "zachary@customerA.com":
fileName = ExtractString(m.Subject, "(", ")");

foreach (Attachment attachment in m.Attachments)


{
attachment.Save(@"C:\Demo\" + fileName +
Path.GetExtension(attachment.Filename));
}
break;

case "hunter@customerB.com":

foreach (Attachment attachment in m.Attachments)


{
string filePrefix = attachment.Filename.Substring(0,
attachment.Filename.IndexOf('_'));

switch (filePrefix)
{
case "DAILY":
fileName = "CustomerB_Inventory";
break;
case "PULL":
fileName = "CustomerB_Pulls";
break;
case "RECEIPT":
fileName = "CustomerB_Receipts";
break;
}

attachment.Save(@"C:\Demo\" + fileName +
Path.GetExtension(attachment.Filename));
}
break;
}

// Delete Message (so it drops out of criteria and won't be double


processed)
ic.DeleteMessage(m);
}
}
}

/// <summary>
/// Helper method to pull out a string between a start and stop string.
/// Example:
/// string story = "The boy and the cat ran to the store.";
/// ExtractString(story, "cat", "to"); //returns "ran"
/// </summary>
/// <param name="stringToParse">String to search</param>
/// <param name="startTag">Starting String Pattern</param>
/// <param name="endTag">Ending String Pattern</param>
/// <returns>String found between the Starting and Ending Pattern.</returns>
static string ExtractString(string stringToParse, string startTag, string endTag)
{
int startIndex = stringToParse.IndexOf(startTag) + startTag.Length;
int endIndex = stringToParse.IndexOf(endTag, startIndex);
return stringToParse.Substring(startIndex, endIndex - startIndex);
}

Das könnte Ihnen auch gefallen