回复Mailkit中的邮件

kar*_*iam 10 c# mailkit mimekit

我正在为我的项目使用Mailkit库(Imap).

我可以通过SmtpClient轻松发送新消息.

目前我正在挖掘如何回复特定邮件.是否可以为该回复邮件添加更多收件人?

@jstedfast感谢精彩的:)

jst*_*ast 12

回复邮件非常简单.在大多数情况下,您只需创建回复消息,就像创建任何其他消息一样.只有一些细微的差别:

  1. 在回复消息,你会想前缀Subject与头"Re: "如果前缀尚不你回复的(换句话说,如果你回复邮件与消息中存在Subject"Re: party tomorrow night!",你就没有前缀它与另一个"Re: ").
  2. 您需要将回复消息的In-Reply-To标题设置Message-Id为原始消息中标题的值.
  3. 您需要将原始邮件的References标题复制到回复邮件的References标题中,然后附加原始邮件的Message-Id标题.
  4. 您可能希望在回复中"引用"原始邮件的文本.

如果这个逻辑用代码表示,它可能看起来像这样:

public static MimeMessage Reply (MimeMessage message, bool replyToAll)
{
    var reply = new MimeMessage ();

    // reply to the sender of the message
    if (message.ReplyTo.Count > 0) {
        reply.To.AddRange (message.ReplyTo);
    } else if (message.From.Count > 0) {
        reply.To.AddRange (message.From);
    } else if (message.Sender != null) {
        reply.To.Add (message.Sender);
    }

    if (replyToAll) {
        // include all of the other original recipients - TODO: remove ourselves from these lists
        reply.To.AddRange (message.To);
        reply.Cc.AddRange (message.Cc);
    }

    // set the reply subject
    if (!message.Subject.StartsWith ("Re:", StringComparison.OrdinalIgnoreCase))
        reply.Subject = "Re:" + message.Subject;
    else
        reply.Subject = message.Subject;

    // construct the In-Reply-To and References headers
    if (!string.IsNullOrEmpty (message.MessageId)) {
        reply.InReplyTo = message.MessageId;
        foreach (var id in message.References)
            reply.References.Add (id);
        reply.References.Add (message.MessageId);
    }

    // quote the original message text
    using (var quoted = new StringWriter ()) {
        var sender = message.Sender ?? message.From.Mailboxes.FirstOrDefault ();

        quoted.WriteLine ("On {0}, {1} wrote:", message.Date.ToString ("f"), !string.IsNullOrEmpty (sender.Name) ? sender.Name : sender.Address);
        using (var reader = new StringReader (message.TextBody)) {
            string line;

            while ((line = reader.ReadLine ()) != null) {
                quoted.Write ("> ");
                quoted.WriteLine (line);
            }
        }

        reply.Body = new TextPart ("plain") {
            Text = quoted.ToString ()
        };
    }

    return reply;
}
Run Code Online (Sandbox Code Playgroud)

注意:此代码假定message.TextBody不为null.虽然不太可能,但这可能会发生(意味着消息不包含text/plain正文).