首页 > 解决方案 > 使用 MailKit 将 xlsx 文件附加到电子邮件

问题描述

我正在创建 xlsx 文件并将其保存到目录。我想将此 excel 文件通过电子邮件发送给用户,但一直失败。在网上搜索,但找不到任何有效的。到目前为止,我这样做了,但收到的文件大小为零。

        public void SendSingle2(string filePath)
    {
        var emailMessage = new MimeMessage();
        emailMessage.From.Add(new MailboxAddress("Name", "test@gmail.com"));
        emailMessage.To.Add(new MailboxAddress("MnM", "test@hotmail.com"));
        emailMessage.Subject = "Report";

        var builder = new BodyBuilder { HtmlBody = "Incident Report." };
        if (filePath != null)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    file.CopyTo(memoryStream);
                builder.Attachments.Add("Report.xlsx",memoryStream);
            }
        }

        emailMessage.Body = builder.ToMessageBody();



        using (var emailClient = new SmtpClient())
        {

            emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);


            emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

            emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);

            emailClient.Send(emailMessage);

            emailClient.Disconnect(true);
        } 

标签: c#asp.net-core

解决方案


推荐阅读