3

另请参阅此问题:我可以将 System.Net.MailMessage 传递给 WCF 服务吗?

我想在发送的邮件中添加附件。附件可以是本地磁盘上的文件,也可以是动态创建的 Streams。WCF 协定可以包含 Stream,但仅当所有参数都是 Stream 类型时。那么,将一个或多个附件传递给 WCF 服务的最佳方式是什么?

4

1 回答 1

8

好吧,我自己解决了这个问题。这里的技巧是将附件转换为 Base64 编码字符串,与电子邮件系统执行此操作的方式非常相似。我创建了一个类来处理这个问题。在这里为其他人发布:

 [DataContract]
    public class EncodedAttachment
    {
        [DataMember(IsRequired=true)]
        public string Base64Attachment;

        [DataMember(IsRequired = true)]
        public string Name;

        /// <summary>
        /// One of the System.Net.Mime.MediaTypeNames
        /// </summary>
        [DataMember(IsRequired = true)]
        public string MediaType;
    }

 public EncodedAttachment CreateAttachment(string fileName)
        {
            EncodedAttachment att = new EncodedAttachment();
            if (!File.Exists(fileName))
                throw new FileNotFoundException("Cannot create attachment because the file was not found", fileName);

            FileInfo fi = new FileInfo(fileName);
            att.Name = fi.Name;
            att.MediaType = System.Net.Mime.MediaTypeNames.Text.Plain;

            using (FileStream reader = new FileStream(fileName, FileMode.Open))
            {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                att.Base64Attachment = Convert.ToBase64String(buffer);
            }
            return att;
        }

在客户端:

public void SendEmail(SmallMessage msg)
        {
            using (MailMessage message = new MailMessage())
            {
                message.Body = msg.Body;
                message.Subject = msg.Subject;
                message.To.Add(new MailAddress(msg.To));
                message.From = new MailAddress(msg.From);
                foreach (EncodedAttachment att in msg.Attachments)
                {
                    message.Attachments.Add(CreateAttachment(att));
                }

                SmtpClient client = new SmtpClient();
                client.Send(message);
            }
        }


Attachment CreateAttachment(EncodedAttachment encodedAtt)
{
    MemoryStream reader = new MemoryStream(Convert.FromBase64String(encodedAtt.Base64Attachment));
    Attachment att = new Attachment(reader, encodedAtt.Name, encodedAtt.MediaType);
    return att;            
}
于 2009-01-16T13:45:02.927 回答