我们有一个在Windows Server 2008计算机上运行的应用程序。它使用office365 smtp中继帐户发送电子邮件。但是,所有电子邮件都未成功发送。我们在smtp.Send调用发送的电子邮件中随机获得这两个例外:
到目前为止,我们还未能弄清楚为什么会这样。任何想法都表示赞赏。
电子邮件代码使用System.Net.Mail命名空间 - .Net framework 4.0。 我们传递了NetworkCredential的用户名和密码。
public void Send(string from, string[] to, string[] cc, string[] bcc, string subject, string body, string[] attachmentArr, Boolean isBodyHtml, string smtpServerName, int port = 25, bool enableSsl = true, string userName = null, string password = null, string domain = null, int timeoutMilliSec = 100000)
{
MailMessage objEmail = new MailMessage();
try
{
foreach (string toItem in to)
{
objEmail.To.Add(toItem);
}
if (cc != null)
{
foreach (string toItem in cc)
{
objEmail.CC.Add(toItem);
}
}
if (bcc != null)
{
foreach (string toItem in bcc)
{
objEmail.Bcc.Add(toItem);
}
}
objEmail.From = new MailAddress(from);
objEmail.Subject = subject;
objEmail.Body = body;
objEmail.IsBodyHtml = isBodyHtml;
objEmail.Priority = MailPriority.High;
if (attachmentArr != null)
{
foreach (String s1 in attachmentArr)
{
objEmail.Attachments.Add(new Attachment(s1));
}
}
using (SmtpClient smtp = new SmtpClient(smtpServerName))
{
if (string.IsNullOrEmpty(userName) == false && string.IsNullOrEmpty(password) == false)
{
NetworkCredential credential = (string.IsNullOrEmpty(domain)) ? new NetworkCredential(userName, password) : new NetworkCredential(userName, password, domain);
smtp.Credentials = credential;
}
smtp.Timeout = timeoutMilliSec;
smtp.Port = port;
smtp.EnableSsl = enableSsl;
smtp.Send(objEmail);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (attachmentArr != null && objEmail.Attachments != null)
{
foreach (Attachment a1 in objEmail.Attachments)
{
a1.Dispose();
}
}
}
}