문제

이 질문도 참조하십시오. System.net.mailMessage를 WCF 서비스에 전달할 수 있습니까?

전송중인 메일에 첨부 파일을 추가하고 싶습니다. 첨부 파일은 로컬 디스크의 파일이거나 동적으로 생성 된 스트림입니다. WCF 계약에는 스트림이 포함될 수 있지만 모든 인수가 유형 스트림 일 때만 가능합니다. 그렇다면 하나 이상의 첨부 파일을 WCF 서비스에 전달하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

좋아, 나는 이것을 직접 해결했다. 여기서 비결은 첨부 파일을 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;            
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top