我有一个名为 SchedulerService 的类,其中有一个 SendMail 函数,当需要在某个时间发送电子邮件时调用该函数。当我调用 SendMail 函数时,我传入一个对象,该对象包含有关向谁发送电子邮件以及电子邮件来自谁的信息。现在,我添加了一个 SendCompleted 处理程序,以便我可以重新发送电子邮件,以防万一发生导致它无法发送的情况。我有这个发送邮件的代码:
var recipients = EmailTo.Split(',').ToList();
if (String.IsNullOrEmpty(EmailFrom))
EmailFrom = recipients[0];
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress(EmailFrom);
recipients.ForEach(a => message.To.Add(new MailAddress(a)));
message.Attachments.Add(new Attachment(LocationOfResults));
message.Subject = String.Format("{0:MM-dd-yyyy} Results for task: {1}.", DateTime.Now, Description);
message.Body = "Attached is the results file specified for the task: " + Description;
smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtpClient.UseDefaultCredentials = true;
smtpClient.SendAsync(message, null);
}
这是事件处理程序
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
MailMessage mail = (MailMessage)e.UserState;
using (mail)
{
smtpClient.Send(mail);
}
}
if (e.Error != null)
{
Log(e.Error.ToString() + " in SendCompletedHandlerEvent", EventLogEntryType.Error);
}
}
问题是,我发现这样做不起作用,因为 To 和 From 字段是空的,这会在发送电子邮件时导致错误。我应该如何从未能发送的电子邮件中回收收件人/发件人字段?