0

I am creating a sitecore form where I need to attach the uploaded file in the form to the Send Email which comes OOTB in the sitecore forms.

I am not finding any options to attach the files.

Is there a way to attach the files which comes from the form fields?

Any help on this will be great

enter image description here

5

3 Answers 3

1

In the Execute method of the SendEmailAction class, where the FormSubmitContext is a method argument, we can access the File Upload fields, assuming there can be more than one, get the stream of data, and add it to the attachments list. Please see the code snippet below:


var attachments = new List<Attachment>();
var uploadFieldList = formSubmitContext.Fields
      .Where(f => f.GetType() == typeof(FileUploadViewModel));
if (uploadFieldList != null && uploadFieldList.Count() > 0)
{
  foreach (var uploadField in uploadFieldList)
  {
    if (uploadField != null)
    {
      var uploadFieldVM = (FileUploadViewModel)uploadField;
      if (uploadFieldVM.Files != null && uploadFieldVM.Files.Count > 0)
      {
        for (var i = 0; i < uploadFieldVM.Files.Count; i++)
        {
          var uploadFile = uploadFieldVM.Files[i];
          uploadFile.InputStream.Position = 0;
          attachments.Add(new Attachment(
              uploadFile.InputStream, 
              uploadFile.FileName, 
              uploadFile.ContentType));
        }
      }
    }
  }
}

More details and Credit: https://cristinadragos.wordpress.com/2021/03/18/sitecore-forms-and-attaching-the-uploaded-files-when-sending-emails/

Hope it helps!

1
  • Thank you Sumit, that helps.. The custom submit action is getting executed but the uploaded file is not getting attached. I debugged, the file exists in the mailMessage object. Anything else need to be configured? Feb 28, 2023 at 10:25
1

You can also create a Custom Send Email submit action in Sitecore Forms.

This can be achieved in 2 steps

  1. Create a class that inherits from Sitecore.ExperienceForms.Mvc.Processing.SubmitActions.SendEmail and write your custom logic.
  2. Add a Custom Submit Action under /sitecore/system/Settings/Forms/Submit Actions

And in the Execute method, you can get all the fields along with your uploaded file using this code.

if (uploadFieldList != null && uploadFieldList.Count() > 0)
                    {
                        foreach (var uploadField in uploadFieldList)
                        {
                            if (uploadField != null)
                            {
                                var uploadFieldVM = (FileUploadViewModel)uploadField;
                                if (uploadFieldVM.Files != null && uploadFieldVM.Files.Count > 0)
                                {
                                    for (var i = 0; i < uploadFieldVM.Files.Count; i++)
                                    {
                                        var uploadFile = uploadFieldVM.Files[i];
                                        uploadFile.InputStream.Position = 0;
                                        mailMessage.Attachments.Add(new Attachment(
                                            uploadFile.InputStream,
                                            uploadFile.FileName,
                                            uploadFile.ContentType));
                                    }
                                }
                            }
                        }
                    }

Refer to this article for the full source code.

https://sitecorediaries.org/2021/09/08/creating-custom-submit-action-to-send-the-emails-in-sitecore-forms/

6
  • Thank you Sumit, that helps.. The custom submit action is getting executed but the uploaded file is not getting attached. I debugged, the file exists in the mailMessage object. Anything else need to be configured? Feb 28, 2023 at 10:26
  • @SyedAmanulla So you mean you are getting all the fields but not the file using formSubmitContext.Fields.Where(f => f.GetType() == typeof(FileUploadViewModel)) ? Feb 28, 2023 at 10:57
  • I am getting the file in the above mentioned object, and the email is getting triggered. the file is not attached in the email.. Feb 28, 2023 at 11:27
  • I have updated the picture with debugging values of attachment.. does that give any hint? Mar 2, 2023 at 14:53
  • @SyedAmanulla The picture is not too clear. Can you please add it again? Mar 2, 2023 at 15:04
0
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
using Sitecore.ExperienceForms.Mvc.Models.SubmitActions;
using Sitecore.ExperienceForms.Processing;
using Sitecore.Reflection;
using Sitecore.Services.Core.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using KAO.Foundation.Email;
using System.IO;
using System.Text;

namespace KAO.Foundation.ExperienceForms.Extensions
{
    public class CustomSendEmail : Sitecore.ExperienceForms.Mvc.Processing.SubmitActions.SendEmail
    {
        public CustomSendEmail(ISubmitActionData submitActionData) : base(submitActionData)
        {
        }

        private static string GetFieldValue(IViewModel postedField)
        {
            if (postedField.GetType().GetMethod("GetStringValue") != null)
            {
                return ReflectionUtil.CallMethod(postedField, "GetStringValue").ToString();
            }

            return "";
        }

        private static string ReplaceFieldValues(string content, FormSubmitContext formSubmitContext)
        {
            string str = content;
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }
            foreach (IViewModel field in formSubmitContext.Fields)
            {
                str = str.Replace(string.Format("{0}{1}{2}", '[', field.Name, ']'), GetFieldValue(field));
            }
            return str;
        }

        private static void AddRecipients(MailAddressCollection mailAddressCollection, string mailAddresses)
        {
            string[] array = (
                from p in mailAddresses.Split(new char[] { ';' })
                select p.Trim() into p
                where !string.IsNullOrEmpty(p)
                select p).ToArray<string>();
            for (int i = 0; i < (int)array.Length; i++)
            {
                mailAddressCollection.Add(array[i]);
            }
        }

        protected override bool Execute(SendEmailData data, FormSubmitContext formSubmitContext)
        {
            bool flag;
            using (MailMessage mailMessage = new MailMessage())
            {
                try
                {
                    mailMessage.From = new MailAddress(ReplaceFieldValues(data.From, formSubmitContext));
                    mailMessage.Subject = ReplaceFieldValues(data.Subject, formSubmitContext);
                    mailMessage.Body = ReplaceFieldValues(data.Body, formSubmitContext);
                    mailMessage.IsBodyHtml = true;
                    AddRecipients(mailMessage.To, ReplaceFieldValues(data.To, formSubmitContext));
                    AddRecipients(mailMessage.CC, ReplaceFieldValues(data.Cc, formSubmitContext));
                    AddRecipients(mailMessage.Bcc, ReplaceFieldValues(data.Bcc, formSubmitContext));
                    #region Attachment 
                    var attachments = new List<Foundation.Email.EmailService.Attachment>();
                    var uploadFieldList = formSubmitContext.Fields
                          .Where(f => f.GetType() == typeof(FileUploadViewModel));
                    if (uploadFieldList != null && uploadFieldList.Count() > 0)
                    {
                        foreach (var uploadField in uploadFieldList)
                        {
                            if (uploadField != null)
                            {
                                var uploadFieldVM = (FileUploadViewModel)uploadField;
                                if (uploadFieldVM.Files != null && uploadFieldVM.Files.Count > 0)
                                {
                                    for (var i = 0; i < uploadFieldVM.Files.Count; i++)
                                    {
                                        var uploadFile = uploadFieldVM.Files[i];
                                        uploadFile.InputStream.Position = 0;
                                        var attach = new Email.EmailService.Attachment
                                        {
                                            Filename = uploadFile.FileName,
                                            Base64FileContents = ConvertToBase64(uploadFile.InputStream),
                                            
                                        };
                                        attachments.Add(attach);                                       
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                    KAO.Foundation.Email.Email.SendEmailWithAttachments(mailMessage.From.ToString(), mailMessage.To.ToString(), mailMessage.CC.ToString(), mailMessage.Bcc.ToString(), mailMessage.Subject, mailMessage.Body, attachments.ToArray(), true);
                    flag = true;
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    this.Logger.LogError(exception.Message, exception, this);
                    flag = false;
                }
            }
            return flag;
        }

        private static string ConvertToBase64(Stream stream)
        {
            if (stream is MemoryStream memoryStream)
            {
                return Convert.ToBase64String(memoryStream.ToArray());
            }

            var bytes = new Byte[(int)stream.Length];

            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(bytes, 0, (int)stream.Length);

            return Convert.ToBase64String(bytes);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.