.NET Core 2.0 的 MailKit 电子邮件附件

MailKit email Attachment for .NET Core 2.0

我的问题: 我想从我不断变化的 类 和数据中创建一个 csv 文件,并将其作为附件通过电子邮件发送。

好的: 我可以使用以下代码创建一个 csv 文件。

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());
            }
        }

并被

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

不好的:

                string FromAddress = "myaddress@gmail.com";
                string FromAdressTitle = "Email Title";
                string ToAddress = "someaddress@domain.com";
                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);
                }

这很好用,但我不想创建文件,而是从内存流创建附件。可能吗?

查看 BodyBuilder class 以构建附件列表。

MimeMessage.Attachments 属性 一直是一个 IEnumerable,因此不可能以这种方式添加附件。