【问题标题】:Unable to attach an eml file as an attachment when sending an email using c#?使用c#发送电子邮件时无法将eml文件作为附件附加?
【发布时间】:2014-07-04 10:55:06
【问题描述】:

我正在通过 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;

如您所见,我打印了 Stream size - 打印出来的内容类似于 4790Bytes (4KB) 但是当我收到邮件时,我只得到一个 1KB 大小的 eml 文件,并且 eml 文件是空的。

我检查了文件路径,并确保在我的报告邮件发出之前,电子邮件就在那里。 我还验证了内容类型是message/rfc822。

一切似乎都在检查。不知道是什么问题。

【问题讨论】:

标签: c# email stream email-attachments eml


【解决方案1】:

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

所以确保在将流添加到AttachmentCollection 之前将其重新定位回原点,类似于

Seek(0, SeekOrigin.Begin)

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

【讨论】:

    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 2013-03-18
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多