Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create Attachments from Sitecore MediaItems and attach to emails
private List<Attachment> RetrieveAttachments(ID formId, IEnumerable<AdaptedControlResult> fields)
{
var attachments = new List<Attachment>();
Item item = Sitecore.Context.Database.Items[formId];
if (item != null)
{
var mediaItemIds = new List<string>();
var formItem = new FormItem(item);
foreach (AdaptedControlResult field in fields)
{
GetMediaIds(formItem, field, mediaItemIds);
}
GetAttachmentsFromMediaItems(mediaItemIds, attachments);
}
return attachments;
}
private static void GetMediaIds(FormItem formItem, AdaptedControlResult field, List<string> mediaItemIds)
{
if (formItem.Fields.Any(f => f.ID.ToString() == field.FieldID))
{
FieldItem fieldItem = formItem.Fields.First(f => f.ID.ToString() == field.FieldID);
if (fieldItem.Type.ID == Enumerators.SitecoreConfig.Guids.Templates.HiddenEmailAttachmentId)
{
var value = HttpUtility.HtmlDecode(field.Value);
var regex = new Regex(@"<item>(.*?)</item>");
var matches = regex.Matches(value);
foreach (Match match in matches)
{
if (!string.IsNullOrEmpty(match.Groups[1].Value))
{
mediaItemIds.Add(match.Groups[1].Value);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment