簡體   English   中英

使用C#發送電子郵件時,無法將eml文件作為附件附加?

[英]Unable to attach an eml file as an attachment when sending an email using c#?

我正在通過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大小 -打印出的內容類似於4790Bytes(4KB),但是當我收到電子郵件時,我只收到一個大小為1KB的eml文件,而eml文件為空

我檢查了文件路徑,並確保在發送報告郵件之前,該電子郵件一直存在。 我還驗證了內容類型為message/rfc822

一切似乎都結帳了。 不知道是什么問題。

我能夠解決它。 看起來MemoryStream具有正確的流,並且消息對象的ContentStream也具有正確的大小,但是Stream 位置已經移到的末尾,因此,當實際上發送消息時,它實際上沒有任何內容。

因此,在將流添加到AttachmentCollection之前,請確保將流重新定位回原始位置 ,例如

Seek(0, SeekOrigin.Begin)

特別是當使用包裹在dll中的流時,可能是某些東西移動了它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM