如何使用 MailKit 发送具有失败状态的邮件传递状态



我们有一个鸽子/后缀邮件服务器,我们通过IMAP和SMTP协议将其用于自动化目的。

在某些情况下,系统处理电子邮件,但邮件有问题,系统将从管道中排除邮件。

由于电子邮件来自不同的来源,系统需要通知发件人失败,并且出于自动化目的,另一方希望收到状态为失败的邮件传递状态消息。

我们使用 MailKit 来处理消息,我一直试图弄清楚如何使用 C# 中的 MailKit 发送这样的消息,但我没有成功。

我拥有的代码的简化版本如下:

// Prepares smtpClient
MultipartReport multipartReport = new MultipartReport("delivery-status")
{
new TextPart {Content = new MimeContent(new MemoryStream(Encoding.ASCII.GetBytes("The message contains malformed data")))},

new MessageDeliveryStatus {StatusGroups = {new HeaderList {new Header("Action", "failed")}}}
};
MimeMessage  message = new MimeMessage
{
Body = multipartReport,

From = { new MailboxAddress("Webmaster", "webmaster@our.domain")},

To = { new MailboxAddress("User", "user@origin.domain")},

Subject = "Delivery Status Notification (Failure)",

InReplyTo = "message id of the received message"
};
smtpClient.Send(mimeMessage);

更新:通过建议的修改@jstedfast现在代码会生成以下消息:

From: Webmaster <webmaster@ourdomain.com>
Date: Sat, 06 Feb 2021 23:50:56 +0100
Subject: Delivery Status Notification (Failure)
Message-Id: <GII2AYZOWCU4.AXDWNKVKJ4XD3@ourdomain.com>
To: First Last <someone@gmail.com>
Return-Path: <>
MIME-Version: 1.0
Content-Type: multipart/report; boundary="=-HnKieASbitf0LQ3XjF16Mw==";
report-type=delivery-status
--=-HnKieASbitf0LQ3XjF16Mw==
Content-Type: text/plain
Attachment not allowed
--=-HnKieASbitf0LQ3XjF16Mw==
Content-Type: message/delivery-status
Reporting-MTA: dns;mail.ourdomain.com
Final-Recipient: rfc822;user@ourdomain.com
Action: failed
Status: 550 5.7.1

--=-HnKieASbitf0LQ3XjF16Mw==--

发送邮件后发生的情况是,它被接收并显示为原始发件人邮箱中的常规电子邮件。

更新 2:

如果有帮助,我使用Postfix作为 SMTP 服务器,在我看来,修改 MIME 消息并将其转换为常规文本 MIME 消息可能是Postfix

不知道什么不起作用,就很难知道该建议什么。

也就是说,快速浏览一下规范会发现"Action"标头是per-recipient-fields的一部分,该是可选的第二组状态标头。

标头字段的第一组是per-message-fields,其中应包含以下字段:

per-message-fields =
[ original-envelope-id-field CRLF ]
reporting-mta-field CRLF
[ dsn-gateway-field CRLF ]
[ received-from-mta-field CRLF ]
[ arrival-date-field CRLF ]
*( extension-field CRLF )

per-recipient-fields定义为:

per-recipient-fields =
[ original-recipient-field CRLF ]
final-recipient-field CRLF
action-field CRLF
status-field CRLF
[ remote-mta-field CRLF ]
[ diagnostic-code-field CRLF ]
[ last-attempt-date-field CRLF ]
[ final-log-id-field CRLF ]
[ will-retry-until-field CRLF ]
*( extension-field CRLF )

这意味着,您至少需要将构造MessageDeliveryStatus零件的方式更改为如下所示:

new MessageDeliveryStatus {
StatusGroups = {
new HeaderList {
new Header("Reporting-MTA", "dns;<dns name of the MTA>")
},
new HeaderList {
new Header("Final-Recipient", "rfc822;<address of recipient>",
new Header("Action", "failed"),
new Header("Status", "5.something")
}
}
}

您需要从 https://www.rfc-editor.org/rfc/rfc3463 中选择状态代码

最新更新