onsdag den 11. juni 2014

Attaching a Mediaitem to an email from code

This time, we will be looking at how to attach a Mediaitem to an email from code, which can be useful from time to time.

Doing this is really simple - here is how to do it:

public static Attachment CreateMailAttachment(MediaItem mediaItem)
{
    if (mediaItem == null)
    {
        throw new ArgumentNullException("mediaItem", "mediaItem must not be null");
    }

    ContentType contentType = new ContentType(mediaItem.MimeType);
    Attachment attachment = new Attachment(mediaItem.GetMediaStream(), contentType);

    attachment.ContentDisposition.FileName = string.Format("{0}.{1}", mediaItem.Name, mediaItem.Extension);
    return attachment;
}

First we have to figure out the mime type of the attachement, this is made quite easy, since there is a property for this on the Mediaitem itself - so we just create a ContentType object, and use it, together with the stream containing the file data, to create an Attachment.

Then we create the filename, so it has the original filename, and return it.

I know it's not much, but it can be quite helpful when having to generate emails with files attached.