【问题标题】:Unable to send mail with excel attachment in c#无法在c#中发送带有excel附件的邮件
【发布时间】:2019-08-12 08:59:32
【问题描述】:

我正在尝试发送带有 excel 附件的邮件,邮件正在发送,但附件在 filename.xlsx.txt 中,没有内容(空白 .txt 文件)

    public void SendEmail()
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.test.net");
        mail.From = new MailAddress("test@test.com");
        mail.To.Add("test@test.com");
        mail.Subject = "Test Mail - 1";
        mail.Body = "mail with attachment";


        Attachment attachment;
        attachment = new Attachment(File.Open(AppDomain.CurrentDomain.BaseDirectory + "result.xlsx", FileMode.Open), "result.xlsx");
        attachment.ContentType = new ContentType("application/vnd.ms-excel");
        mail.Attachments.Add(attachment);

        SmtpClient client = new SmtpClient("smtp.test.net");
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        NetworkCredential credetial = new NetworkCredential("test@test.com", "******", "test.com");
        client.UseDefaultCredentials = true;
        client.EnableSsl = true;
        try
        {
            System.Threading.Thread.Sleep(5000);
            client.Send(mail);
        }
        catch (Exception e)
        {

        }

    }

电子邮件附件:

【问题讨论】:

  • 306 字节 = 没有内容?这 306 个字节是什么?
  • 或许您不应该将其重命名为 .txt
  • @Lasse Vågsæther Karlsen 只是一个空白文本文件,而不是带有内容的 excel
  • @Alander 我不会将其重命名为 .txt
  • 您的编码可能有误,请在此处尝试 flindeberg 的答案:stackoverflow.com/questions/13223200/…

标签: c# excel asp.net-mvc email attachment


【解决方案1】:

您实际上并没有附加文件,而是打开文件并将其保存为result.xlsx,保存时默认为.txt 扩展名。这就解释了为什么你会收到result.xlsx.txt

代替

Attachemnt attachment = new Attachment(File.Open(AppDomain.CurrentDomain.BaseDirectory + "result.xlsx", FileMode.Open), "result.xlsx");
attachment.ContentType = new ContentType("application/vnd.ms-excel");

使用

message.Attachments.Add(new Attachment(PathToAttachment));

只需传递文件的路径即可。

再次不确定您是否需要内容类型位。

【讨论】:

  • 相同结果是什么意思?,是result.xlsx.txt吗?希望你重建你的代码
  • 是的,相同的 result.xlsx.txt 没有数据
【解决方案2】:

我有一个像这样附加的电子表格... (使用您的对象名称“mail”)

mail.Attachments.Add(new Attachment(mail, "result.xls", "application/vnd.ms-excel"));

代替:

Attachment attachment;
attachment = new Attachment(File.Open(AppDomain.CurrentDomain.BaseDirectory + "result.xlsx", FileMode.Open), "result.xlsx");
attachment.ContentType = new ContentType("application/vnd.ms-excel");
mail.Attachments.Add(attachment);

【讨论】:

  • 看看你是否可以打开你用 Excel 创建的文件...也许你只是创建一个文本文件。
  • 不,我已经检查过我正在创建的文件已成功创建并使用正确的数据,但是当我通过邮件发送它时,我得到了上面没有数据的 result.xlsx.txt 文件。跨度>
猜你喜欢
  • 2011-07-05
  • 2011-07-26
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 2021-11-24
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多