如何在C#中使用Mailkit在草稿中添加byte []附件

时间:2018-07-10 08:44:01

标签: c# wpf mailkit

public byte[] Attachment { get; set; }是我要添加的附件  草稿保存。有人知道如何在草稿附件中保存byte[]吗?

public void DraftMessage(string strto, string strcc, string strBcc,
     string strSubject, string strBody, List<UserAttachment> listAttachments)
{
    try
    {
        MimeMessage email = new MimeMessage();
        email.MessageId = MimeUtils.GenerateMessageId();
        var list = new InternetAddressList();

        if (strto != "")
        {
            string[] strArrayto = strto.Split(';');

            if (strArrayto != null)
            {
                list = new InternetAddressList();

                foreach (string _strTo in strArrayto)
                    list.Add(new MailboxAddress(_strTo));

                email.To.AddRange(list);
            }
        }

        if (strcc != "")
        {
            string[] strArraycc = strcc.Split(';');

            if (strArraycc != null)
            {
                list = new InternetAddressList();

                foreach (string _strcc in strArraycc)
                    list.Add(new MailboxAddress(_strcc));

                email.Cc.AddRange(list);
            }
        }

        if (strBcc != "")
        {
            string[] strArrayBcc = strBcc.Split(';');

            if (strArrayBcc != null)
            {
                list = new InternetAddressList();

                foreach (string _strBcc in strArrayBcc)
                    list.Add(new MailboxAddress(_strBcc));

                email.Bcc.AddRange(list);
            }
        }

        email.Subject = strSubject;
        email.Body = new TextPart(TextFormat.Html)
        {
            Text = strBody
        };

        SaveMessgeSummary(email, strDraftfolder, listAttachments);

        var draftFolder = MailManager.Instance.ImapClient.GetFolder(strDraftfolder);

        if (draftFolder != null)
        {
            draftFolder.Open(FolderAccess.ReadWrite);

            draftFolder.Append(email, MessageFlags.Draft);
            draftFolder.Expunge();
        }

        DAL.MessageSummary.UpdateExecutStatus(email.MessageId);
    }
    catch (Exception ex)
    {
    }
}

上面的代码中,我正在传递参数List<UserAttachment> listAttachments,该参数正在使用以下类:

public class UserAttachment
{
    public byte[] Attachment { get; set; }
    public string strFileName { get; set; }
}

1 个答案:

答案 0 :(得分:4)

FAQ说明了如何创建附件:

var attachment = new MimePart ("image", "gif") {
    Content = new MimeContent (File.OpenRead (path), ContentEncoding.Default),
    ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
    ContentTransferEncoding = ContentEncoding.Base64,
    FileName = Path.GetFileName (path)
};

MimeContent类型接受Stream,您可以通过创建byte[]Stream转换为MemoryStream

Content = new MimeContent (new MemoryStream(byteArray), ContentEncoding.Default),