简体   繁体   English

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

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

I am receiving emails through hmailserver and sending those emails as .eml file as an attachment of another report email. 我正在通过hmailserver接收电子邮件,并将这些电子邮件作为.eml文件作为另一个报告电子邮件的附件发送。

I am having issues in reading and sending those emails as an attachment. 我在阅读和发送这些电子邮件作为附件时遇到问题。

This is what I am doing. 这就是我在做什么。

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);
    }

Then, 然后,

            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;

as you see i print the Stream size - which prints out as something like 4790Bytes (4KB) But when i receive the email, i only get an eml file with size 1KB and the eml file is empty . 如您所见,我打印了Stream大小 -打印出的内容类似于4790Bytes(4KB),但是当我收到电子邮件时,我只收到一个大小为1KB的eml文件,而eml文件为空

I have checked the file paths and also made sure that the email is there until my report mail is sent out. 我检查了文件路径,并确保在发送报告邮件之前,该电子邮件一直存在。 I have also verified content type is message/rfc822 . 我还验证了内容类型为message/rfc822

Everything seems to check out. 一切似乎都结帐了。 Not sure what the issue is. 不知道是什么问题。

I was able to resolve it. 我能够解决它。 Looks like the MemoryStream have the correct stream and also the ContentStream of the message object has the correct sizes, but the Stream postion had moved to the end of the stream and hence when the message is actually being sent, it actualy has nothing. 看起来MemoryStream具有正确的流,并且消息对象的ContentStream也具有正确的大小,但是Stream 位置已经移到的末尾,因此,当实际上发送消息时,它实际上没有任何内容。

So make sure to reposition the stream back to origin before adding it to AttachmentCollection , something like 因此,在将流添加到AttachmentCollection之前,请确保将流重新定位回原始位置 ,例如

Seek(0, SeekOrigin.Begin)

especially when using streams wrapped in dlls, something might have moved them. 特别是当使用包裹在dll中的流时,可能是某些东西移动了它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM