Search code examples
c#emailbase64eml

Trying to insert eml file as attachment gives error "The input is not a valid Base-64 string as it contains a non-base 64 character"


I have a MailMessage in c# which I want to transform into an EML to insert as an attachment into another system, but the error I get is

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters

textBody is not used.. I am only passing in html

public Task<string> CreateEml(string @from, string to, string subject, string htmlBody, string textBody, List<Attachment> attachments = null)
    {
        using (var message = new MailMessage())
        {               
            message.To.Add(new MailAddress(to));
            message.From = new MailAddress(@from);
            //message.Bcc.Add(new MailAddress(bcc));
            message.Subject = subject;
            message.Body = htmlBody;
            message.IsBodyHtml = true;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            if (attachments != null)
            {
                foreach (var item in attachments)
                {
                    message.Attachments.Add(item);
                }
            }

            if (!string.IsNullOrEmpty(textBody))
            {
                using (var stream = new MemoryStream())
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(textBody);
                    message.AlternateViews.Add(new AlternateView(stream));
                    var eml = message.ToEml();
                    return Task.FromResult(eml);
                }
            }

            return Task.FromResult(message.ToEml());
        }
    }

There is an extension method ToEml() which does this

 public static string ToEml(this MailMessage message)
    {
        var assembly = typeof(SmtpClient).Assembly;
        var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

        using (var memoryStream = new MemoryStream())
        {
            // Get reflection info for MailWriter contructor
            var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);

            // Construct MailWriter object with our FileStream
            var mailWriter = mailWriterContructor.Invoke(new object[] { memoryStream });

            // Get reflection info for Send() method on MailMessage
            var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);

            // Call method passing in MailWriter
            sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);

            // Finally get reflection info for Close() method on our MailWriter
            var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);

            // Call close method
            closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);

            return Encoding.ASCII.GetString(memoryStream.ToArray());
        }
    }    

This resulting data is assigned to data.EmailDataBus and used to insert the email as an attachment to a 3rd party system like this

attachment.FileInfo[0] = new FileInfoClass
            {
                Description = emailDescription,
                Category = "EMAIL",
                FileName = "NewBusiness.eml",
                Data = data.EmailDataBus,
            };

            using (var webService = new ConneXion())
            {
                webService.Url = CloudConfigurationManager.GetSetting("tam.webservice.url");

                var response = webService.InsertAttachment(ref attachment);

The error message I get back is

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters

The data in data.EmailBus looks like this, note I am not including all of the base64 but the header and footer is intact

https://plnkr.co/edit/n71EFK2gHRj6Nn4HX1Sn?p=preview


Solution

  • Turns out I just had to encode the whole thing to base64.. which is a little odd as parts of the data already was base64 .. but I suppose not all of it. Anyway now it all works :) Attachment went in connexion fine.

    byte[] emaildata = Encoding.UTF8.GetBytes(data.EmailDataBus);
     string b64 = Convert.ToBase64String(emaildata);