Search code examples
c#optimizationemail-attachmentssmtpclientmailkit

MailKit email Attachment for .NET Core 2.0


My problem: I want to create a csv file from my ever-changing classes and data and email that as an attachment.

The good: I can create a csv file using the following code.

private IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
        {
            FieldInfo[] fields = typeof(T).GetFields();
            PropertyInfo[] properties = typeof(T).GetProperties();
            yield return String.Join(separator, fields.Select(f => f.Name).Union(properties.Select(p => p.Name)).ToArray());
            foreach (var o in objectlist)
            {
                yield return string.Join(separator, (properties.Select(p => (p.GetValue(o, null) ?? "").ToString())).ToArray());
            }
        }

and use it by

    using (TextWriter tw = File.CreateText("filepath" + "filename"))
    {
        foreach (var line in ToCsv(",", data))
        {
            tw.WriteLine(line);
        }
    }

The bad:

                string FromAddress = "[email protected]";
                string FromAdressTitle = "Email Title";
                string ToAddress = "[email protected]";
                string ToAdressTitle = "To address Title";
                string Subject = "RE: some subject line";

                //Smtp Server
                string SmtpServer = "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = 587;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
                mimeMessage.Subject = Subject;

                var builder = new BodyBuilder();
                builder.Attachments.Add(@"filepath");
                mimeMessage.Body = builder.ToMessageBody();

                using (var client = new SmtpClient())
                {
                    client.Connect(SmtpServer, SmtpPortNumber, false);
                    client.Authenticate("username", "password");
                    client.Send(mimeMessage);
                    client.Disconnect(true);
                }

This works fine but I dont want to create a file but create an attachment from memory stream instead. Is it possible?


Solution

  • Take a look at the BodyBuilder class to construct the list of attachments.

    The MimeMessage.Attachments property has always been an IEnumerable, so it was never possible to add attachments in that way.