Chilkat Email Components Home

Email Programming - Saving Attachments

Back

Question:
How to save individual attachments? One at a time? I could see there is an option for saving all attachments but none for saving individual files. I am asking this what if I have emails sent by 2 different people with the same attachment name? In that case A.zip will be overwritten by A.zip from another sender.

Answer:
The C# example program below demonstrates how to save individual attachments and handle the existing-file issue you described:

// This example demonstrates how to save email attachments individually.
Chilkat.MailMan mailman = new Chilkat.MailMan();
mailman.UnlockComponent("30-day trial");

mailman.MailHost = "mail.chilkatsoft.com";
mailman.PopUsername = "***";
mailman.PopPassword = "***";

Chilkat.EmailBundle bundle = mailman.CopyMail();

int i;
int n = bundle.MessageCount;
for (i=0; i<n; i++)
{
	Chilkat.Email email = bundle.GetEmail(i);

	// Set OverwriteExisting = false if you do not want
	// SaveAttachedFile to overwrite existing files with the same
	// filename.  In that case, the filename is appended with
	// a few random characters to make it unique. You may then
	// get the actual filename saved by calling GetAttachmentFilename
	// after the SaveAttachedFile method call.
	email.OverwriteExisting = false;

	int numAttachments = email.NumAttachments;
	int j;

	for (j=0; j<numAttachments; j++)
	{
		string filenameBefore = email.GetAttachmentFilename(j);
		email.SaveAttachedFile(j,"c:/myAttachments");
		string filenameAfter = email.GetAttachmentFilename(j);		    
	}
}