使用c#发送电子邮件时无法将eml文件作为附件附加?

时间:2014-05-15 20:05:04

标签: c# email stream email-attachments eml

我正在通过hmailserver接收电子邮件,并将这些电子邮件作为 .eml 文件发送,作为另一封报告电子邮件的附件。

我在阅读和发送这些电子邮件时遇到问题。

这就是我在做的事。

public void addAttachment(string pathname, bool retry)
    {
        string attachmentname = "";
        do
        {
            try
            {
                attachmentname = Path.GetFileNameWithoutExtension(pathname);
                Stream file = new MemoryStream(File.ReadAllBytes(pathname));
                Log.WriteMessage("Size" + file.Length);
                dtstreamAttach.Add(attachmentname+".eml", file);
                retry = false;
            }
            catch (ArgumentException e)
            {
                string strCurrentTs = DateTime.Now.ToString(strDateFormat);
                attachmentname = attachmentname + "-" + strCurrentTs+".eml";
            }
        } while (retry);
    }

然后,

            MailMessage message = new MailMessage();
            . 
            .
            message.Attachments.Add(new Attachment(kvp.Value, kvp.Key)); // I have an attachment dictionary 
            string contenttype = GetMimeType(".eml");
            ContentType cnttype = new ContentType(contenttype);
            message.Attachments[0].ContentType = cnttype;

如您所见,我打印流大小 - 打印出来像 4790Bytes(4KB) 但是当我收到电子邮件时,我只收到一个大小为1KB且eml文件为空的eml文件。

我检查了文件路径,并确保电子邮件在那里,直到我的报告邮件发送出去。 我还验证了内容类型为message/rfc822

似乎一切都结束了。不确定是什么问题。

1 个答案:

答案 0 :(得分:0)

我能够解决它。看起来MemoryStream具有正确的流,并且消息对象的ContentStream具有正确的大小,但Stream 位置已移至流的末尾,因此当消息实际发送时,它实际上什么都没有。

所以确保将流重新定位回原点,然后再将其添加到AttachmentCollection,例如

Seek(0, SeekOrigin.Begin)

尤其是在使用dll中包含的流时,可能会移动它们。

相关问题