我试图通过应用程序系统使用 SMTP 服务器自动发送多封带有多个附件的电子邮件,但我遇到了这个问题 Inner exception = Unable to read data from the transport connection: An existing connection wasforced close by the remote host。
public static void sendEmailAttachement(string mailFrom, string mailTo, string subjectText, string bodyText, List<string> attachments)
{
try
{
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
MailMessage message = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp-mail.outlook.com");
message.From = new MailAddress(mailFrom);
message.To.Add(mailTo);
message.Subject = subjectText;
message.Body = bodyText;
SmtpServer.Port = 587;
List<Attachment> ListAttachment = new List<Attachment>();
if (attachments != null)
{
foreach (var path in attachments)
{
FileInfo fileInfo = new FileInfo(path);
string fileName = Path.GetFileName(fileInfo.FullName);
ListAttachment.Add(new Attachment(path));
}
}
SmtpServer.Credentials = new System.Net.NetworkCredential(mailFrom, "********");
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;
SmtpServer.Timeout = Int32.MaxValue;
using (AlternateView alternate = AlternateView.CreateAlternateViewFromString(bodyText, Encoding.UTF8, MediaTypeNames.Text.Html))
{
message.AlternateViews.Add(alternate);
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
if (ListAttachment.Count > 0)
{
foreach (var Attachment in ListAttachment)
{
message.Attachments.Add(Attachment);
}
}
SmtpServer.Send(message);
if (ListAttachment.Count > 0)
{
foreach (var Attachment in ListAttachment)
{
Attachment.Dispose() ;
}
}
}
}
catch (Exception e)
{
throw;
}
}