Smtpclient send error

here is my code for(int i = 0; i < number ; i++) { MailAddress to = new MailAddress(iMail.to); MailAddress from = new MailAddress(iMail.from, iMail.displayName); string body = iMail....

here is my code

for(int i = 0; i < number ; i++)
{
    MailAddress to = new MailAddress(iMail.to);
    MailAddress from = new MailAddress(iMail.from, iMail.displayName);
    string body = iMail.body;
    string subject = iMail.sub;
    oMail = new MailMessage(from, to);
    oMail.Subject = subject;
    oMail.Body = body;
    oMail.IsBodyHtml = true;
    oMail.Priority = MailPriority.Normal;
    oMail.Sender = from;
    s = new SmtpClient(smtpServer);
    if (s != null)
    {
        s.Send(oMail);
    }
    oMail.Dispose();
    s = null;
}

this loops sends over 60,000 email. but my problem i am getting » failure sending mail» in some of the email some times 5000 and some time less then that rest of them gets delivered. and i have check all those error out email has valid email address. dont know what is the problem. i really need help in this.

Edit: This is my exception Trace

Error — Failure sending mail.; Inner
Ex — System.IO.IOException: Unable to
read data from the transport
connection: net_io_connectionclosed.
at
System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[]
buffer, Int32 offset, Int32 read,
Boolean readLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
caller, Boolean oneLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader
caller) at
System.Net.Mail.CheckCommand.Send(SmtpConnection
conn, String& response) at
System.Net.Mail.MailCommand.Send(SmtpConnection
conn, Byte[] command, String from) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress
sender, MailAddressCollection
recipients, String deliveryNotify,
SmtpFailedRecipientException&
exception)

Some guy's user avatar

Some guy

4097 silver badges10 bronze badges

asked Feb 5, 2010 at 19:03

Nnp's user avatar

2

Well, the «failure sending e-mail» should hopefully have a bit more detail. But there are a few things that could cause this.

  1. Restrictions on the «From» address. If you are using different from addresses, some could be blocked by your SMTP service from being able to send.
  2. Flood prevention on your SMTP service could be stopping the e-mails from going out.

Regardless if it is one of these or another error, you will want to look at the exception and inner exception to get a bit more detail.

mattruma's user avatar

mattruma

16.5k31 gold badges103 silver badges169 bronze badges

answered Feb 5, 2010 at 19:09

Mitchel Sellers's user avatar

Mitchel SellersMitchel Sellers

61.6k14 gold badges110 silver badges172 bronze badges

7

apparently this problem got solved just by increasing queue size on my 3rd party smtp server.
but the answer by Nip sounds like it is fairly usefull too

answered Mar 9, 2010 at 23:12

Nnp's user avatar

NnpNnp

1,7736 gold badges35 silver badges62 bronze badges

I experienced the same issue when sending high volume email. Setting the deliveryMethod property to PickupDirectoryFromIis fixed it for me.
Also don’t create a new SmtpClient everytime.

answered Feb 9, 2010 at 2:49

Romhein's user avatar

RomheinRomhein

2,0562 gold badges17 silver badges17 bronze badges

2

what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information

MSDN

Edit for the new information

Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.

answered Feb 5, 2010 at 19:07

Pharabus's user avatar

PharabusPharabus

6,0611 gold badge26 silver badges39 bronze badges

6

For us, everything was fine, emails are very small and not a lot of them are sent and sudently it gave this error. It appeared that a technicien installed ASTARO which was preventing email to be sent. and we were getting this error so yes the error is a bit cryptic but I hope this could help others.

answered May 25, 2012 at 12:27

Marc Roussel's user avatar

Seeing your loop for sending emails and the error which you provided there is only solution.
Declare the mail object out of the loop and assign fromaddress out of the loop which you are using for sending mails. The fromaddress field is getting assigned again and again in the loop that is your problem.

Widor's user avatar

Widor

12.8k6 gold badges40 silver badges63 bronze badges

answered Jun 8, 2012 at 15:15

OM Krishna's user avatar

Five years later (I hope this developer isn’t still waiting for a fix to this..)

I had the same issue, caused by the same error: I was declaring the SmtpClient inside the loop.

The fix is simple — declare it once, outside the loop…

MailAddress mail = null;
SmtpClient client = new SmtpClient();
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Host = smtpAddress;       //  Enter your company's email server here!

for(int i = 0; i < number ; i++)
{
    mail = new MailMessage(iMail.from, iMail.to);
    mail.Subject = iMail.sub;
    mail.Body = iMail.body;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.Normal;
    mail.Sender = from;
    client.Send(mail);
}
mail.Dispose();
client.Dispose();

answered Oct 6, 2015 at 14:59

Mike Gledhill's user avatar

Mike GledhillMike Gledhill

27.2k7 gold badges147 silver badges155 bronze badges

This error can appear when the web server can’t access the mail server. Make sure the web server can reach the mail server, for instance pinging it.

answered Feb 18, 2014 at 13:49

Daniel Hedenström's user avatar

here is my code

for(int i = 0; i < number ; i++)
{
    MailAddress to = new MailAddress(iMail.to);
    MailAddress from = new MailAddress(iMail.from, iMail.displayName);
    string body = iMail.body;
    string subject = iMail.sub;
    oMail = new MailMessage(from, to);
    oMail.Subject = subject;
    oMail.Body = body;
    oMail.IsBodyHtml = true;
    oMail.Priority = MailPriority.Normal;
    oMail.Sender = from;
    s = new SmtpClient(smtpServer);
    if (s != null)
    {
        s.Send(oMail);
    }
    oMail.Dispose();
    s = null;
}

this loops sends over 60,000 email. but my problem i am getting » failure sending mail» in some of the email some times 5000 and some time less then that rest of them gets delivered. and i have check all those error out email has valid email address. dont know what is the problem. i really need help in this.

Edit: This is my exception Trace

Error — Failure sending mail.; Inner
Ex — System.IO.IOException: Unable to
read data from the transport
connection: net_io_connectionclosed.
at
System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[]
buffer, Int32 offset, Int32 read,
Boolean readLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
caller, Boolean oneLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader
caller) at
System.Net.Mail.CheckCommand.Send(SmtpConnection
conn, String& response) at
System.Net.Mail.MailCommand.Send(SmtpConnection
conn, Byte[] command, String from) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress
sender, MailAddressCollection
recipients, String deliveryNotify,
SmtpFailedRecipientException&
exception)

Some guy's user avatar

Some guy

4097 silver badges10 bronze badges

asked Feb 5, 2010 at 19:03

Nnp's user avatar

2

Well, the «failure sending e-mail» should hopefully have a bit more detail. But there are a few things that could cause this.

  1. Restrictions on the «From» address. If you are using different from addresses, some could be blocked by your SMTP service from being able to send.
  2. Flood prevention on your SMTP service could be stopping the e-mails from going out.

Regardless if it is one of these or another error, you will want to look at the exception and inner exception to get a bit more detail.

mattruma's user avatar

mattruma

16.5k31 gold badges103 silver badges169 bronze badges

answered Feb 5, 2010 at 19:09

Mitchel Sellers's user avatar

Mitchel SellersMitchel Sellers

61.6k14 gold badges110 silver badges172 bronze badges

7

apparently this problem got solved just by increasing queue size on my 3rd party smtp server.
but the answer by Nip sounds like it is fairly usefull too

answered Mar 9, 2010 at 23:12

Nnp's user avatar

NnpNnp

1,7736 gold badges35 silver badges62 bronze badges

I experienced the same issue when sending high volume email. Setting the deliveryMethod property to PickupDirectoryFromIis fixed it for me.
Also don’t create a new SmtpClient everytime.

answered Feb 9, 2010 at 2:49

Romhein's user avatar

RomheinRomhein

2,0562 gold badges17 silver badges17 bronze badges

2

what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information

MSDN

Edit for the new information

Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.

answered Feb 5, 2010 at 19:07

Pharabus's user avatar

PharabusPharabus

6,0611 gold badge26 silver badges39 bronze badges

6

For us, everything was fine, emails are very small and not a lot of them are sent and sudently it gave this error. It appeared that a technicien installed ASTARO which was preventing email to be sent. and we were getting this error so yes the error is a bit cryptic but I hope this could help others.

answered May 25, 2012 at 12:27

Marc Roussel's user avatar

Seeing your loop for sending emails and the error which you provided there is only solution.
Declare the mail object out of the loop and assign fromaddress out of the loop which you are using for sending mails. The fromaddress field is getting assigned again and again in the loop that is your problem.

Widor's user avatar

Widor

12.8k6 gold badges40 silver badges63 bronze badges

answered Jun 8, 2012 at 15:15

OM Krishna's user avatar

Five years later (I hope this developer isn’t still waiting for a fix to this..)

I had the same issue, caused by the same error: I was declaring the SmtpClient inside the loop.

The fix is simple — declare it once, outside the loop…

MailAddress mail = null;
SmtpClient client = new SmtpClient();
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Host = smtpAddress;       //  Enter your company's email server here!

for(int i = 0; i < number ; i++)
{
    mail = new MailMessage(iMail.from, iMail.to);
    mail.Subject = iMail.sub;
    mail.Body = iMail.body;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.Normal;
    mail.Sender = from;
    client.Send(mail);
}
mail.Dispose();
client.Dispose();

answered Oct 6, 2015 at 14:59

Mike Gledhill's user avatar

Mike GledhillMike Gledhill

27.2k7 gold badges147 silver badges155 bronze badges

This error can appear when the web server can’t access the mail server. Make sure the web server can reach the mail server, for instance pinging it.

answered Feb 18, 2014 at 13:49

Daniel Hedenström's user avatar

C# service fails to send email with multiple attachments. The failure occurs when sending >3 attachments. This failure occurs even if the total attachment size under 100KB.

Troubleshooting notes:
— Targets Framework is 4.0.
— The other threads for «existing connection was forcibly closed» are not relevant to this issue because I’m using System.Net.Mail class to send emails.
— Sending email to local SMTP service. And local SMTP service is able to relay emails without issues
— Captured System.Net class trace. Can provide entire log, if required.

App log shows following error:
System.Net.Mail.SmtpException: Failure sending mail. —> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. —> System.Net.Sockets.SocketException: An existing connection
was forcibly closed by the remote host
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   — End of inner exception stack trace —
   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Mime.MimePart.Send(BaseWriter writer)
   at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   — End of inner exception stack trace —
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Corp.Framework.EmailManager.SendMail(StringCollection toAddresses, Attachment[] attachments)ection toAddresses, Attachment[] attachments)

System.Net* Trace captures following errors:

System.Net Verbose: 0 : [4580] Exiting ConnectStream#2629989::Read()     -> 1453#1453
System.Net Verbose: 0 : [4580] ConnectStream#2629989::Read()
System.Net.Sockets Verbose: 0 : [4580] Socket#57782509::Receive()
System.Net.Sockets Error: 0 : [4580] Exception in the Socket#57782509::Receive — An existing connection was forcibly closed by the remote host
System.Net.Sockets Verbose: 0 : [4580] Exiting Socket#57782509::Receive()     -> 0#0
System.Net.Sockets Verbose: 0 : [4580] Socket#57782509::Dispose()
System.Net Error: 0 : [4580] Exception in the HttpWebRequest#9035793:: — The underlying connection was closed: An unexpected error occurred on a receive.
System.Net Error: 0 : [4580] Exception in the SmtpClient#12046712::Send — Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
System.Net Error: 0 : [4580]    at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Mime.MimePart.Send(BaseWriter writer)
   at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
System.Net.Sockets Verbose: 0 : [4580] Socket#42706818::Dispose()
System.Net Verbose: 0 : [4580] SmtpPooledStream::Dispose #54415608
System.Net Verbose: 0 : [4580] Exiting SmtpPooledStream::Dispose #54415608
System.Net Verbose: 0 : [4580] Exiting SmtpClient#12046712::Send()

Sample code:

MailMessage mail = new MailMessage();
mail.Subject = _MessageSubject;
mail.Body = _MessageBody;
mail.IsBodyHtml = false;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.Priority = _Priority;

foreach (Object a in _Attachments)
{
    mail.Attachments.Add((Attachment)a);
}

foreach(string to in toAddresses)
{
        mail.To.Add(to);
}

mail.From = new MailAddress(_FromAddress);
SmtpClient smtpClient = new SmtpClient(_SMTPServer);

smtpClient.Host = _SMTPServer;
smtpClient.EnableSsl = _IsSSLEnabled;
smtpClient.Port = _SMTPPort;

try
{
       smtpClient.Send(mail);
}

Ever since I posted a quick guide to sending email via Mailkit in .NET Core 2, I have been inundated with comments and emails asking about specific exception messages that either Mailkit or the underlying .NET Core. Rather than replying to each individual email, I would try and collate all the errors with sending emails here. It won’t be pretty to read, but hopefully if you’ve landed here from a search engine, this post will be able to resolve your issue.

I should also note that the solution to our “errors” is usually going to be a change in the way we use the library MailKit. If you are using your own mail library (Or worse, trying to open the TCP ports yourself and manage the connections), you will need to sort of “translate” the fix to be applicable within your code.

Let’s go!

Default Ports

Before we go any further, it’s worth noting the “default” ports that SMTP is likely to use, and the settings that go along with them.

Port 25
25 is typically used a clear text SMTP port. Usually when you have SMTP running on port 25, there is no SSL and no TLS. So set your email client accordingly.

Port 465
465 is usually used for SMTP over SSL, so you will need to have settings that reflect that. However it does not use TLS.

Port 587
587 is usually used for SMTP when using TLS. TLS is not the same as SSL. Typically anything where you need to set SSL to be on or off should be set to off. This includes any setting that goes along the lines of “SSLOnConnect”. It doesn’t mean TLS is less secure, it’s just a different way of creating the connection. Instead of SSL being used straight away, the secure connection is “negotiated” after connection.

Settings that are relevant to port 587 usually go along the lines of “StartTLS” or simply “TLS”. Something like Mailkit usually handles TLS for you so you shouldn’t need to do anything extra.

Incorrect SMTP Host

System.Net.Sockets.SocketException: No such host is known

This one is an easy fix. It means that you have used an incorrect SMTP hostname (Usually just a typo). So for example using smp.gmail.com instead of smtp.gmail.com. It should be noted that it isn’t indicative that the port is wrong, only the host. See the next error for port issues!

Incorrect SMTP Port

System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: A socket operation was attempted to an unreachable network [IpAddress]:[Port]

Another rather simple one to fix. This message almost always indicates you are connecting to a port that isn’t open. It’s important to distinguish that it’s not that you are connecting with SSL to a non SSL port or anything along those lines, it’s just an out and out completely wrong port.

It’s important that when you log the exception message of this error, you check what port it actually says in the log. I can’t tell you how many times I “thought” I was using a particular port, but as it turned out, somewhere in the code it was hardcoded to use a different port.

Another thing to note is that this error will manifest itsef as a “timeout”. So if you try and send an email with an incorrect port, it might take about 30 seconds for the exception to actually surface. This is important to note if your system slows to a crawl as it gives you a hint of what the issue could be even before checking logs.

Forcing Non-SSL On An SSL Port

MailKit.Net.Smtp.SmtpProtocolException: The SMTP server has unexpectedly disconnected.

I want to point out this is a MailKit exception, not one from .NET. In my experience this exception usually pops up when you set Mailkit to not use SSL, but the port itself requires SSL.

As an example, when connecting to Gmail, the port 465 is used for SSL connections. If I try and connect to Gmail with the following Mailkit code :

var emailClient = new SmtpClient();
emailClient.Connect("smtp.gmail.com", 465, false);

That last parameter that’s set to false is telling Mailkit to not use SSL. And what do you know, we get the above exception. The easy fix is obviously to change this to “true”.

Alternatively, you might be getting confused about TLS vs SSL. If the port says to connect using SSL, then you should not “force” any TLS connection.

Connecting Using SSL On A TLS Port (Sometimes)

MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.

Another Mailkit specific exception. This one can be a bit confusing, especially because the full error log from MailKit talks about certificate issues (Which it totally could be!), but typically when I see people getting this one, it’s because they are trying to use SSL when the port they are connecting to is for TLS. SSL != TLS.

So instead of trying to connect using MailKit by forcing SSL, just connect without passing in an SSL parameter.

emailClient.Connect("smtp.gmail.com", 465);

I should note that you will also get this exception in Mailkit if you try and force the SSLOnConnect option on a TLS Port. So for example, the following will not work :

emailClient.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.SslOnConnect);

Again, sometimes this is because the SSL connection truly is bogus (Either because the certificate is bad, expired etc), or because you are connecting to a port with no security whatsoever. But because of the rise of TLS, I’m going to say the most likely scenario is that you are trying to force SSL on a TLS port.

Another error that you can sometimes get with a similar setup is :

Handshake failed due to an unexpected packet format

This is an exception that has a whole range of causes, but the most common is forcing an SSL connection on a TLS port. If your SMTP port supports “TLS”, then do not set SSL to true.

Forcing No TLS On A TLS Port

System.NotSupportedException: The SMTP server does not support authentication.

This one is a little weird because you basically have to go right out of your way to get this exception. The only way I have seen this exception come up when you are telling Mailkit to go out of it’s way to not respect any TLS messages it gets and try and ram authentication straight away.

So for example, the following code would cause an issue :

emailClient.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.None);

Incorrect Username And/Or Password

MailKit.Security.AuthenticationException: AuthenticationInvalidCredentials: 5.7.8 Username and Password not accepted.

Goes without saying, you have the wrong username and password. This is not going to be any connection issues. You definitely have the right host and port, and the right SSL/TLS settings, but your username/password combination is wrong.

Other Errors?

Have something else going haywire? Drop a comment below!

When i try to send email from my local hosting it works fin but when i try to send email from godaddy plesk hosting account it shows me error «failure sending mail»

«System.Net.Mail.SmtpException: Failure sending mail. —> System.Net.WebException: Unable to connect to the remote server —> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.25.108:25 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) — End of inner exception stack trace — at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) — End of inner exception stack trace — at System.Net.Mail.SmtpClient.Send(MailMessage message) at WebApplication1._Default.Place_Click(Object sender, EventArgs e)»

try
            {
                
                MailMessage msg = new MailMessage();
                
                msg.To.Add(someone@gmail.com);
                
                MailAddress address = new MailAddress("username@gmail.com");
                msg.From = address;
                msg.Subject = "gmail";
                msg.Body = "gmail";

                
                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = true;
                client.Host = "smtp.gmail.com";
                client.Port = 25;

                
                NetworkCredential credentials = new NetworkCredential("username@gmail.com", "password");
                client.UseDefaultCredentials = true;
                client.Credentials = credentials;

                
                client.Send(msg);

                
                Label1.Text = "Your message was sent!";
            }
            catch (Exception ex)
            {
                
                Label1.Text = ex.ToString();
                
            }


Now i have found the solution. The code below is work for me just changing the smtp server thanks every one.

try
           {
               
               MailMessage msg = new MailMessage();
               
               msg.To.Add(someone@any.com);
               
               MailAddress address = new MailAddress("user@mydomain.com");
               msg.From = address;
               msg.Subject = "anything";
               msg.Body = "anything";

               
               SmtpClient client = new SmtpClient();
               client.DeliveryMethod = SmtpDeliveryMethod.Network;
               client.EnableSsl = false;
               client.Host = "relay-hosting.secureserver.net";
               client.Port = 25;

               
               NetworkCredential credentials = new NetworkCredential("user@mydomain.com", "Password");
               client.UseDefaultCredentials = true;
               client.Credentials = credentials;

               
               client.Send(msg);

               
               Label1.Text = "Your message was sent!";
           }
           catch (Exception ex)
           {
               
               Label1.Text = ex.ToString();
               
           }

You need to verify the GoDaddy SMTP settings first. Majority of the times, you will get error due to setting up an incorrect settings.

Also try to debug the code with try..catch block and track the inner exception.

Hi

Before coding

Check if you are able to send email using the SMTP server , check the ports , in this case port 587.
Usually it’s 25(SMTP) , 465(SMTP with SSL).

You can telnet

telnet <serve> <port>

You can also try to send email using telnet.
http://www.port25.com/how-to-check-an-smtp-connection-with-a-manual-telnet-session-2

That is because of the port you’re using and the server isn’t responding to the request of yours at that port. Change the port to 25 and then retry. I have always used 25, and it always worked.

I am receiving this error

"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.28.108:587"

Hi,

I was also receiving error

«A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.28.108:587»

Thank you again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  • Remove From My Forums

 none

не могу отправить письмо из скрипта

  • Вопрос

  • собственно проблема. при запуске этого на powershell`e:

    Send-SmtpMail.ps1

    либо этого

    $mail = New-Object System.Net.Mail.MailMessage
    $mail.From = «from@mail.ru»;
    $mail.To.Add(«to@mail.ru»);
    $mail.Subject = «Test AUTH»;
    $mail.Body = «Test»;
    # Подключаемся к серверу
    $smtp = New-Object System.Net.Mail.SmtpClient(«smtp.mail.ru»);
    $smtp.Credentials = New-Object System.Net.NetworkCredential(«login», «pass»);
    # Отправляем
    $smtp.Send($mail);

    вылетает ошибка:

    Исключение при вызове «Send» с «1» аргументами: «Сбой при отправке сообщения электронной почты.»
    В :строке:12 позиция:10
    + $smtp.Send <<<< ($mail);

    пытался гуглить, безуспешно. с учетом того что недавно возникла такая необходимость, разобраться в самом powershell`e времени особо не было
    стоит win7 с powershell`ом, который стоял. че думать??

Ответы

  • Скрипт, котрый вы привели, вполне рабочий. (проверил, подставив свои реквизиты для mail.ru)

    Видимо, происходит какая-то ошибка во время соединения/передачи c вашей раб. станции, на которой вы запускаете скрипт, на smtp-сервер. Например,
    — у вас не доступа к smtp.mail.ru (перекрыто firewall’ом),
    — вас забанили на mail.ru,
    — у вас плохой канал и связь рвется во воремя передачи сообщения.
    и т.д. и т.п.

    Попробуйте, для начала, отправить то же самое письмо с проблемной рабочей станции не скриптом, но «руками» (при помощи telnet) или почтовым клиентом.

    • Предложено в качестве ответа

      16 ноября 2009 г. 16:29

    • Отменено предложение в качестве ответа
      XomYa4ina
      16 ноября 2009 г. 18:37
    • Помечено в качестве ответа
      XomYa4ina
      16 ноября 2009 г. 18:47

Здравствуйте.
Возникла ошибка. Какой бы код не был, всегда выбивает тоже самое.
Вот недавний:

SmtpClient smtp = new SmtpClient("smtp.mail.ru", 25);
            smtp.Credentials = new System.Net.NetworkCredential("***@mail.ru", "****");

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("***@mail.ru");
            mail.To.Add(new MailAddress("***l@yandex.ru"));
            mail.Subject = "Subject";
            mail.Body = "Body";

            string file = @"C:Users***Desktop12.txt";
            Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet);
            mail.Attachments.Add(attach);

            smtp.Send(mail);

Выбивает такое:
Окошко с надписью:

Необрабатываемое исключение в приложении. При нажатии кнопки "Продолжить" приложение проигнорирует ошибку и попытается продолжить работу. При нажатии кнопки "Выход" приложение немедленно завершит работу.

Сбой при отправке сообщения электронной почты.

Подробности:

************** Текст исключения **************
System.Net.Mail.SmtpException: Сбой при отправке сообщения электронной почты. ---> System.Net.WebException: Невозможно соединиться с удаленным сервером ---> System.Net.Sockets.SocketException: Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера 217.69.139.161:25
   в System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   в System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- Конец трассировки внутреннего стека исключений ---
   в System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
   в System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
   в System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
   в System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
   в System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
   в System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
   в System.Net.Mail.SmtpClient.GetConnection()
   в System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- Конец трассировки внутреннего стека исключений ---
   в System.Net.Mail.SmtpClient.Send(MailMessage message)
   в hz.Form1.Button1_Click(Object sender, EventArgs e) в C:UsersAsussourcereposhzhzForm1.cs:строка 38
   в System.Windows.Forms.Control.OnClick(EventArgs e)
   в System.Windows.Forms.Button.OnClick(EventArgs e)
   в System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   в System.Windows.Forms.Control.WndProc(Message& m)
   в System.Windows.Forms.ButtonBase.WndProc(Message& m)
   в System.Windows.Forms.Button.WndProc(Message& m)
   в System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   в System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Там дальше еще куча подробностей. Напишите если нужно. При нажатии «Продолжить» логично что смс так и не приходит….

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Smtp ошибка 550 невозможно установить отправителя domain is not allowed to send mail
  • Smtp ошибка 550 невозможно установить отправителя beget
  • Smtp ошибка 550 невозможно добавить получателя sweb
  • Smtp ошибка 535 ошибка авторизации как исправить
  • Smtp ошибка 454

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии