Pergunta

Veja também esta pergunta: Can I passar um System.Net.MailMessage a um serviço WCF?

Eu gostaria de adicionar anexos ao e-mail que está sendo enviado. Anexos são ou arquivos no disco local ou Streams criados dinamicamente. Um contrato WCF pode conter um Stream, mas apenas quando todos os argumentos são do tipo Stream. Então, qual é a melhor maneira de passar um ou mais anexos a um serviço WCF?

Foi útil?

Solução

Tudo bem, eu já resolveu isso mesmo. O truque aqui é para converter o anexo para amarrar uma Base64 codifica, tanto os sistemas de e-mail mesma maneira fazer isso. Eu criei uma classe para lidar com isso. Postado aqui para os outros:

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

E no lado do cliente:

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;            
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top