EWS发送邮件在c#中失败,但在VB.Net中没有


public ExchangeService CreateConnection(string url)
{
ServicePointManager.ServerCertificateValidationCallback = (object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true;
ExchangeService service = new ExchangeService();
service.Url = new Uri(url);
service.UseDefaultCredentials = true;        // Uses users windows login credentials
return service;
}
public void SendEmail(string sEmailTo, string slocation, DateTime dtdate, string slogyard, string sScaling, string sLogMfct, string sOther, string sScaler, int icheckbox)
{
string scheckbox;
string sDomain = Globals.gDefaultEmailSuffix;
string sUserName = SystemInformation.UserName;
ExchangeService service = CreateConnection("https://myexchangeserver.com/EWS/Exchange.asmx");
string sHTMLpre = $"{EmailBody(Globals.gHTML)}";
EmailMessage mailMessage = new EmailMessage(service);                 // Use with exchange service

ReplaceWithBR(slogyard);
ReplaceWithBR(sScaling);
ReplaceWithBR(sLogMfct);
ReplaceWithBR(sOther);
if (icheckbox > 0)
scheckbox = "Yes";
else
scheckbox = "No";
sHTMLpre = sHTMLpre.Replace("[@Location]", slocation);
sHTMLpre = sHTMLpre.Replace("[@Date]", dtdate.ToString());
sHTMLpre = sHTMLpre.Replace("[@LogYard]", slogyard);
sHTMLpre = sHTMLpre.Replace("[@Scaling]", sScaling);
sHTMLpre = sHTMLpre.Replace("[@LogManufacturing]", sLogMfct);
sHTMLpre = sHTMLpre.Replace("[@Scaler]", sScaler);
sHTMLpre = sHTMLpre.Replace("[@Other]", sOther);
sHTMLpre = sHTMLpre.Replace("[@RemotesExist]", scheckbox);
mailMessage.ToRecipients.Add(new EmailAddress($"{sEmailTo}@{sDomain}"));     // Use with Exchange service
mailMessage.From = new EmailAddress($"{sUserName}@{sDomain}");               // Use with Exchange service
mailMessage.Subject = $"Scaling Yard Report for {slocation} on {dtdate}";    // Use with Exchange
mailMessage.Body = sHTMLpre;                                                 // Use with Exchange

try
{  
mailMessage.SendAndSaveCopy());                    //Use with Exchange Service
if (Globals.bLastEmail == true)
{
MessageBox.Show("Email Sent Successfully!");
Globals.MonthlyLog("Email Sent", $"Recipients:{Globals.gEmailList}");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Globals.MonthlyLog("Email Fail", $"{ex.Message}");
return;
}
}

下面是VB。运行良好的Net代码:

Public Function CreateConnection(ByVal url As String) As ExchangeService
ServicePointManager.ServerCertificateValidationCallback = Function(ByVal obj As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal errors As SslPolicyErrors) True
Dim service As New ExchangeService()
service.Url = New Uri(url)
service.UseDefaultCredentials = True        ' Uses users windows login credentials
Return service
End Function
Public Sub SendEmail(sEmailTo As String, slocation As String, dtdate As String, slogyard As String, sScaling As String, sLogMfct As String, sOther As String, sScaler As String, scheckbox As String)
Dim sDomain As String = gDefaultEmailSuffix
Dim sUserName As String = SystemInformation.UserName
Dim service As ExchangeService = CreateConnection("https://myexchangeserver.com/EWS/Exchange.asmx")
Dim sHTMLpre As String = $"{EmailBody(gHTML)}"
Dim mailMessage = New EmailMessage(service)                 ' Use with exchange service
'Dim mailMessage As New MailMessage()                       ' Use with SMTP client service
slogyard = slogyard.Replace(ControlChars.Lf, "<br>")
sScaling = sScaling.Replace(ControlChars.Lf, "<br>")
sLogMfct = sLogMfct.Replace(ControlChars.Lf, "<br>")
sOther = sOther.Replace(ControlChars.Lf, "<br>")
If scheckbox = True Then
scheckbox = "Yes"
Else
scheckbox = "No"
End If
sHTMLpre = sHTMLpre.Replace("[@Location]", slocation)
sHTMLpre = sHTMLpre.Replace("[@Date]", dtdate)
sHTMLpre = sHTMLpre.Replace("[@LogYard]", slogyard)
sHTMLpre = sHTMLpre.Replace("[@Scaling]", sScaling)
sHTMLpre = sHTMLpre.Replace("[@LogManufacturing]", sLogMfct)
sHTMLpre = sHTMLpre.Replace("[@Scaler]", sScaler)
sHTMLpre = sHTMLpre.Replace("[@Other]", sOther)
sHTMLpre = sHTMLpre.Replace("[@RemotesExist]", scheckbox)
mailMessage.ToRecipients.Add(New EmailAddress($"{sEmailTo}@{sDomain}"))     ' Use with Exchange service
mailMessage.From = New EmailAddress($"{sUserName}@{sDomain}")               ' Use with Exchange service
mailMessage.Subject = $"Scaling Yard Report for {slocation} on {dtdate}"    ' Use with Exchange
mailMessage.Body = sHTMLpre                                                 ' Use with Exchange
'mailMessage.IsBodyHtml = True                                              ' Use with SMTP CLient
'mailMessage.To.Add($"{sEmailTo}@{sDomain}")                                ' Use with SMTP CLient
'mailMessage.From = New MailAddress($"{sUserName}@{sDomain}")               ' Use with SMTP  
'mailMessage.Subject = $"Scaling Yard Report for {slocation} on {dtdate}"   ' Use with SMTP
'mailMessage.Body = sHTMLpre                                                ' Use with SMTP

'Dim SmtpCli As New SmtpClient()                                            ' Leaving this just in case the EWS breaks
'With SmtpCli                                                               ' SMTP Client Code
'    .UseDefaultCredentials = False
'    .Port = 25
'    .DeliveryMethod = SmtpDeliveryMethod.Network
'    .Host = gSMTPServer
'    .Credentials = New NetworkCredential(gSMTPUsername, gSMTPPassword)
'End With
Try
'SmtpCli.Send(mailMessage)                                              ' Use with SMPT client
mailMessage.SendAndSaveCopy()                                           ' Use with Exchange Service
If bLastEmail = True Then
MsgBox("Email Sent Successfully!")
Call MonthlyLog("Email Sent", $"Recipients:{gEmailList}")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Call MonthlyLog("Email Fail", $"{ex.Message}")
Exit Sub
End Try
End Sub

它在:mailMessage.SendAndSaveCopy()行失败——在c#中,但在VB中没有。净

获取错误:"请求失败。底层连接已关闭:在发送">

时发生意外错误正如我所说的,它在vb.net代码中工作得很好,所以它不是像节流这样的交换服务器设置。什么好主意吗?

需要将目标。net Framework更新到至少4.6或更高版本。我用的是4.5。我应该知道,因为我遇到了vb.net程序无法在未更新的32位Windows 10 PC上发送电子邮件的问题,这些PC没有4.6。

我正在使用。net 4.5.2并收到相同的错误。较低版本的。net没有强制它使用TLS版本>1.1要么使用更高版本的。net框架。或者你可以强制它使用TLS 1.2

'通过强制使用TLS 1.2来解决底层连接被关闭的意外错误

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

最新更新