[英]How to resolve Unable to read data from the transport connection: net_io_connectionclosed error while sending email using SMTPClient
We have an email accounts as emailName@companyDomain.in and this is configured in Office365 .我们有一个 email 帐户作为emailName@companyDomain.in并在Office365中配置。 We want to send an email using emailName@companyDomain.in from C#.我们想使用来自 C# 的emailName@companyDomain.in发送 email。 Below code sometimes work and sometimes not (most of the times not working).下面的代码有时有效,有时无效(大部分时间无效)。 Giving Error as "Unable to read data from the transport connection: net_io_connectionclosed" .给出错误为“无法从传输连接读取数据:net_io_connectionclosed” 。 Code is代码是
public static void SendEmail(string toEmailId, string subject, string mailMessage)
{
string fromEmail = "emailName@companyDomain.in";
MailMessage msg = new MailMessage();
msg.To.Add(toEmailId);
msg.From = new MailAddress(fromEmail, "Sender Name");
msg.Subject = subject;
msg.Body = mailMessage;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false; // Tried by commenting this too
client.Credentials = new System.Net.NetworkCredential(fromEmail, "password");
client.Port = 587; // Tried port number 25
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.TargetName = "STARTTLS/smtp.office365.com";
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception ex)
{
}
}
Can you please give any hint about what could be wrong?您能否就可能出现的问题提供任何提示?
Adding this code before creating the smtp client worked for me.在创建 smtp 客户端之前添加此代码对我有用。
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
}
First Use Port = 587首次使用端口 = 587
Generally STARTTLS is required to send mail, Adding the Security Protocol Tls12 will help to resolve this issue.发送邮件一般需要 STARTTLS,添加安全协议 Tls12 将有助于解决此问题。
Secondly test the stmp connection using powershell其次使用 powershell 测试 stmp 连接
$userName = 'username_here'
$password = 'xxxxxxxxx'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pwdSecureString
$sendMailParams = @{
From = 'abc.com'
To = 'xyz@gmail.com'
Subject = 'Test SMTP'
Body = 'Test SMTP'
SMTPServer = 'smtp.server.com'
Port = 587
UseSsl = $true
Credential = $credential
}
Send-MailMessage @sendMailParams
Thirdly If this send out the email, Add below code inside SmtpClient function:第三,如果发送 email,在 SmtpClient function 中添加以下代码:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.