c# - 发送到 System.Net.Mail.SmtpClient 等文件夹
问题描述
我正在使用 MailKit.Net.Smtp.SmtpClient 并试图弄清楚是否有一种方法可以配置此客户端,以便它将电子邮件拖放到文件夹中,就像PickupDirectoryLocation属性影响 System.Net 的方式一样。 Mail.SmtpClient dotNet 实例。这里需要进行开发和调试,以便我们可以安全地捕获可能会发出的消息。
我愿意接受另一种调试 MailKit 生成的电子邮件的技术,只要它不涉及任何外部服务,如 SMTP 服务器。
解决方案
The way to do this is to do the following:
public static void SaveToPickupDirectory (MimeMessage message, string pickupDirectory)
{
do {
// Generate a random file name to save the message to.
var path = Path.Combine (pickupDirectory, Guid.NewGuid ().ToString () + ".eml");
Stream stream;
try {
// Attempt to create the new file.
stream = File.Open (path, FileMode.CreateNew);
} catch (IOException) {
// If the file already exists, try again with a new Guid.
if (File.Exists (path))
continue;
// Otherwise, fail immediately since it probably means that there is
// no graceful way to recover from this error.
throw;
}
try {
using (stream) {
// IIS pickup directories expect the message to be "byte-stuffed"
// which means that lines beginning with "." need to be escaped
// by adding an extra "." to the beginning of the line.
//
// Use an SmtpDataFilter "byte-stuff" the message as it is written
// to the file stream. This is the same process that an SmtpClient
// would use when sending the message in a `DATA` command.
using (var filtered = new FilteredStream (stream)) {
filtered.Add (new SmtpDataFilter ());
// Make sure to write the message in DOS (<CR><LF>) format.
var options = FormatOptions.Default.Clone ();
options.NewLineFormat = NewLineFormat.Dos;
message.WriteTo (options, filtered);
filtered.Flush ();
return;
}
}
} catch {
// An exception here probably means that the disk is full.
//
// Delete the file that was created above so that incomplete files are not
// left behind for IIS to send accidentally.
File.Delete (path);
throw;
}
} while (true);
}
推荐阅读
- javascript - Angular JS 的 IOS pin 用户界面
- python - SqlLite 与 SqlAlchemy CreateTable 导致数据库被锁定
- angular - 用''按日期排序表
- android - ImageDecoder 与 BitmapFactory
- reactjs - 如何在草稿js中转换字符串
- php - PHP 致命错误:在中找不到类“IntlDateFormatter”
- c# - 将数字数据类型的输入传递给 WebAPI 的标准方法?
- mysql - SQL - 如何在文本字段中搜索特定数据?例如,我需要包含 C1 + 任何字符的行,例如 C1$,而不是另一个数字,例如 C19
- java - 将jdbc与休眠混合?
- java - Java:在 JFrame 中使用 add(ClassName) 时如何访问类变量