[英]Saving email to the directory with specified file name is not working in .NET 5.0
我正在嘗試遵循 Allan Eagle 在代碼項目中的帖子中建議的方法。 在.NET Core 3.1
之前,這種方法都可以正常工作,但在.NET 5.0
之前就不行了。 這是我創建的保存方法,
private void Save(MailMessage message, string filePath)
{
var assembly = typeof(SmtpClient).Assembly;
var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
var mailWriterContructor = mailWriterType.GetConstructors(bindingFlags)[0];
var mailWriter = mailWriterContructor.Invoke(new object[] { fileStream });//<-- This line throws error saying parameter mismatch
var sendMethod = typeof(MailMessage).GetMethod("Send", bindingFlags);
sendMethod.Invoke(message, bindingFlags, null, new[] { mailWriter, true, true }, null);
var closeMethod = mailWriter.GetType().GetMethod("Close", bindingFlags);
closeMethod.Invoke(mailWriter, bindingFlags, null, new object[] { }, null);
}
}
我檢查了所有可用的底層調用方法並嘗試使用它們傳遞所需的參數,但它們都不適合我。
錯誤消息:“參數計數不匹配。”
內部異常:null
堆棧跟蹤:
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
at..//user written line info
任何解決此問題的幫助或使用System.Net.Mail
實現相同目標的新方法將不勝感激。
根據第一條評論明確地給你一個答案,
var encodeForTransport = false;
var mailWriter = mailWriterContructor.Invoke(new object[] { fileStream, encodeForTransport });
正如我在評論中提到的,這篇文章在 2020 年已經過時了。盡管有日期,但它實際上是在 2009 年編寫的,並在 2014 年停止工作,當時一些內部方法更改了簽名。 在任何情況下,都不應使用System.Net.Mail
命名空間,因為正如 Microsoft 強烈警告的那樣:
重要的
我們不建議您使用 SmtpClient class 進行新開發,因為 SmtpClient 不支持許多現代協議。 請改用MailKit或其他庫。 有關詳細信息,請參閱SmtpClient 不應在 GitHub 上使用。
MailKit(或者更確切地說是它所構建的 MimeKit 庫)已經支持保存和加載郵件消息。 來自問:我如何保存消息? 答案很簡單:
message.WriteTo("message.eml");
您可以使用 MailKit 的 POP3 或 IMAP4 客戶端來檢索郵件。 DownloadMessages示例展示了如何從 GMail 下載消息並保存它們:
using (var client = new Pop3Client (new ProtocolLogger ("pop3.log"))) {
client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username", "password");
for (int i = 0; i < client.Count; i++) {
var message = client.GetMessage (i);
// write the message to a file
message.WriteTo (string.Format ("{0}.msg", i));
// mark the message for deletion
client.DeleteMessage (i);
}
client.Disconnect (true);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.