示例#1
0
        public static MimeMessage FromStub(EmailMessage msg)
        {
            MimeMessage outMsg = new MimeMessage();

            var from = msg.From.FirstOrDefault();

            outMsg.From.Add(from.ToMailAddress());

            EmailAddress.IterateBack(msg.To).ForEach(addr => outMsg.To.Add(addr));
            if (msg.CC != null && msg.CC.Count != 0)
            {
                if (!string.IsNullOrEmpty(msg.CC[0].Name) && !string.IsNullOrEmpty(msg.CC[0].Address))
                {
                    EmailAddress.IterateBack(msg.CC).ForEach(addr => outMsg.Cc.Add(addr));
                }
            }
            if (msg.Bcc != null && msg.Bcc.Count != 0)
            {
                if (!string.IsNullOrEmpty(msg.Bcc[0].Name) && !string.IsNullOrEmpty(msg.Bcc[0].Address))
                {
                    EmailAddress.IterateBack(msg.Bcc).ForEach(addr => outMsg.Bcc.Add(addr));
                }
            }
            outMsg.Subject = msg.Subject;

            var body = new TextPart();

            if (msg.IsBodyHtml)
            {
                body = new TextPart("html")
                {
                    Text = msg.Body
                };
            }
            else
            {
                body = new TextPart("plain")
                {
                    Text = msg.PlainTextBody
                };
            }

            //create the multipart/mixed container to hold the message text and the attachment
            var multipart = new Multipart("mixed");

            if (msg.Attachments != null || msg.Attachments.Count != 0)
            {
                //get all attachments from email message
                foreach (var msgAttachment in msg.Attachments)
                {
                    var attachment = new MimePart("image", "gif")
                    {
                        Content                 = new MimeContent(IOFile.OpenRead(msgAttachment.ContentStorageAddress), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = msgAttachment.Name
                    };

                    multipart.Add(attachment);
                }
            }

            multipart.Add(body);

            //set the multipart/mixed as the message body
            outMsg.Body = multipart;

            return(outMsg);
        }