SMTP Email Sending - c#

No connection could be made because the target machine actively refused it 127.0.0.1:25
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Net.Sockets.SocketException: No
connection could be made because the
target machine actively refused it
127.0.0.1:25
Source Error:
An unhandled exception was
generated during the execution of the
current web request. Information
regarding the origin and location of
the exception can be identified using
the exception stack trace below.
Stack Trace:
[SocketException (0x274d): No
connection could be made because the
target machine actively refused it
127.0.0.1:25] System.Net.Sockets.Socket.DoConnect(EndPoint
endPointSnapshot, SocketAddress
socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint
remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean
connectFailure, Socket s4, Socket s6,
Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult
asyncResult, Int32 timeout, Exception&
exception) +224
[WebException: Unable to connect to
the remote server]
System.Net.ServicePoint.GetConnection(PooledStream
PooledStream, Object owner, Boolean
async, IPAddress& address, Socket&
abortSocket, Socket& abortSocket6,
Int32 timeout) +5483819
System.Net.PooledStream.Activate(Object
owningObject, Boolean async, Int32
timeout, GeneralAsyncDelegate
asyncCallback) +202
System.Net.PooledStream.Activate(Object
owningObject, GeneralAsyncDelegate
asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object
owningObject, GeneralAsyncDelegate
asyncCallback, Int32 creationTimeout)
+332 System.Net.Mail.SmtpConnection.GetConnection(String
host, Int32 port) +160
System.Net.Mail.SmtpTransport.GetConnection(String
host, Int32 port) +159
System.Net.Mail.SmtpClient.GetConnection()
+35 System.Net.Mail.SmtpClient.Send(MailMessage
message) +1213
[SmtpException: Failure sending mail.]
System.Net.Mail.SmtpClient.Send(MailMessage
message) +1531
Checkout.btnSend_Click(Object sender,
EventArgs e) +2675
System.Web.UI.WebControls.Button.OnClick(EventArgs
e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +110
I can't send email in live connection but in my local its working.
please help me guys.
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument)
+13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection
postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +1565
Version Information: Microsoft .NET Framework Version:2.0.50727.3615; ASP.NET Version:2.0.50727.3618
here's my C# code..
SmtpClient SmtpMail = new SmtpClient();
SmtpMail.Host = "localhost";
//delete session cookie
Response.Cookies["session"].Expires = DateTime.Now.AddYears(-30);
SmtpMail.Send(objEmail);

You forgot to start your SMTP server on that machine
Please don't tell you don't have a SMTP server on that machine. But, if you have to tell that, refer to this page and this page also
Even if you configure the local SMTP server, your emails are most likely to end up in spam folder. Better use the SMTP server of your email provider. If you are using Gmail, have a look at here

I got the error with smtp services installed but not started. To start services on the local machine with smtp already installed, here's the steps I took:
Open Server Manager
Select Local Server
Type "smtp" in the filter box under SERVICES (see image)
Right click on Simple Mail Transfer Protocol Service (SMTP) and
select Start Services

Related

ASP.NET MVC on Windows IoT raspberry pi unable to connect to SQL database

I'm trying to start MusicStore application at Raspberry Pi 3 using Windows IoT system with .NET Core 2.0.4.
I managed to run it on Raspberry using ubuntu, but in Windows, I get an error from screenshot (sorry for not copying it but I didn't get error in putty so I need to use Windows IoT command line and I'm not able to copy this text anywhere).
Both systems were connecting to the database on my PC and linux was able to run application, while Windows is failing, so this is not fault of connection string.
I previously had problem with missing sni.dll but as suggested in this thread I repaired it by copying unix.
Any ideas what's wrong?
EDIT:
Today i tested it on my old PC (win10-x64) i got same error as on Windows-IoT so i can copy it here.
Unhandled Exception: System.AggregateException: One or more errors occurred. (A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 44 - Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage)) ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 44 - Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage) ---> System.Net.Sockets.SocketException: Nieznany host
at System.Net.Dns.InternalGetHostByAddress(IPAddress address)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at System.Data.SqlClient.SNI.SNIProxy.GetSqlServerSPN(String hostNameOrAddress, String portOrInstanceName)
at System.Data.SqlClient.SNI.SNIProxy.GetSqlServerSPN(DataSource dataSource)
at System.Data.SqlClient.SNI.SNIProxy.CreateConnectionHandle(Object callbackObject, String fullServerName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[]& spnBuffer, Boolean flushCache, Boolean async, Boolean parallel, Boolean isIntegratedSecurity)
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreatedAsync(CancellationToken cancellationToken)
at MusicStore.Models.SampleData.InitializeMusicStoreDatabaseAsync(IServiceProvider serviceProvider, Boolean createUsers) in C:\Users\lukas\Documents\projekty\magister\MusicStore\Models\SampleData.cs:line 27
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at MusicStore.Startup.Configure(IApplicationBuilder app) in C:\Users\lukas\Documents\projekty\magister\MusicStore\Startup.cs:line 220
at MusicStore.Startup.ConfigureProduction(IApplicationBuilder app) in C:\Users\lukas\Documents\projekty\magister\MusicStore\Startup.cs:line 171
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at MusicStore.Program.Main(String[] args) in C:\Users\lukas\Documents\projekty\magister\MusicStore\Program.cs:line 67
As far as i know, Windows IoT Core on arm has not ability to connect to MS SQL Server.You can trace the issue(#9064) on GitHub.
You can use additional web service or wcf and communicate over REST-API to work around.

Failure Sending Mail in C# SMTP server

I am writing web services for an application in which there is a registration function and upon registration i have to send an email through the server. i have already done this kind of work for another website with Parallel Plesk server. using the same code i'm trying to send email but getting this exception. I searched Google and some related answers here but all in vain. Help?
"System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'domainname.com'\r\n at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)\r\n at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)\r\n at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)\r\n at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)\r\n at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpClient.GetConnection()\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n --- End of inner exception stack trace ---\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n at ActivityTracker.Controllers.ValuesController.parentRegistration(parent p) in c:\Users\Harris\Documents\Visual Studio 2012\Projects\ActivityTracker\ActivityTracker\Controllers\ValuesController.cs:line 89"
From the machine running your code:
You CANNOT resolve domainname.com
You CAN resolve to the IP address of domainname.com
This indicates that you are missing an internal DNS entry.
As your machine can talk to the IP but not using the DNS name - you can work around the issue by creating a Hostname entry for the domain name in question.
Here's how to modify your Hostname file:
http://www.rackspace.com/knowledge_center/article/modify-your-hosts-file
Once this entry is in place, you should now be able to ping to domainname.com. When that works - rerun your code.
Some useful DNS reading:
http://www.techrepublic.com/article/understanding-how-dns-works-part-1/
http://social.dnsmadeeasy.com/blog/understanding-dns-forwarding/
NOTE: You've not confirmed if you can telnet to the port in question, so I am presuming this is ok - ruling out any firewall issues.
Try to use GMail SMTP if it works with GMail SMTP then the problem exist with the domain you specified.

Unable to access api via Azure website

I am using HttpClient to make the request.
Below is the original stack error:
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 209.99.17.14:443 at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) 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.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)Reqes
The same code works in local dev environment.

Webservice SocketException - Only Breaks On One Application

I have a few applications which use a single Web Service which resides on the same server as the applications.
Why would only one of the applications have a problem connecting to a web service? And is there a way I can better diagnose exactly what the problem is with the connection?
It won't even connect to a web service the application itself is hosting
I have tried running it from my local machine and it works fine (updated the web ref url and the connection string to point to the liver server), which should rule out that the code itself is the problem.
I have tried setting up a different virtual directory to point to the application; and later copying the entrie app to another location on the same server and setting it up there. No luck.
[SocketException (0x274c): 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 xx.xx.xx.xx:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream() +5321194
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +103
...
Found it... the proxy was the cause of the issue and it is the only application where I specify proxy different from the default:
Since I only need the proxy locally I disabled it on the live web.config with enabled="false"
<defaultProxy enabled="false">
<proxy
autoDetect="False"
bypassonlocal="True"
scriptLocation="http://www.proxy.something"
proxyaddress="http://proxy.com" />
</defaultProxy>

sending mail works on server but not on my local machine

i have the following code below (i have stuck in xxx to not publish the real name). this code works fine when i upload to the server and will send out emails perfectly.
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromEmailAddress_);
msg.To.Add(new MailAddress(toEmailAddress_));
msg.Subject = subject_;
msg.Body = body_;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("xxx#xxxx.org", "password");
try
{
SmtpClient c = new SmtpClient("mail.xxx.org");
c.UseDefaultCredentials = false;
c.Credentials = basicAuthenticationInfo;
c.Send(msg);
}
catch (Exception ex)
{
throw ex;
Console.Write(ex.Message.ToString());
}
but when i test locally on my machine in visual studio, i get an error:
[SocketException (0x274d): No connection could be made because the target machine actively refused it 66.226.21.251:25]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +5420699
System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +202
System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +332
System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +160
System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +159
any suggestions of why this wouldn't work
The first thing I'd do to run this down is to see whether the target machine is, as the error message says, actually refusing the connections. I can connect to port 25 on that IP address from here, so it's possible that your error message is misleading. These are all possible causes of a failure to connect:
there's some problem in your code
there's some problem in the library you're using
you have a local firewall preventing outbound mail from strange programs
your ISP does not permit outbound SMTP connections except to their own servers
some intermediate network is blocking things
the mail server's ISP is blocking SMTP connections from your network
the mail server really is rejecting you, perhaps because you're on a blocklist
To get more detail, download and install Wireshark. It's like a debugger for networks. Start a capture between your system and the target network and then run your code. Interpreting the captured packets takes some experience, so if you get stuck feel free to post more data here.
Relay restrictions are most likely preventing you from sending mail from outside an allowed set of IPs. If the SMTP Server is configured on a web/application server, it's probably set up to allow mail to be sent via the 127.0.0.1 only.
You can configure a local SMTP Server via the IIS Manager. If you go down this path, make sure port 25 is opened up on your local machine. Often times anti-virus type software block/monitor this port and it mucks with email delivery.
I think you are not using the port no in your code. Use these lines, Then mail should be gone on local also.
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Timeout = 60000;
smtp.Port = 25;
This is working on my system. I hope it will work also on your local system.
The provider has probably firewalled off their mail server so that it is only accepting mail from their hosting environment.
Change it to use your local mail server when you're testing it locally.
You asked for an XP Mail Server. Try hMailServer
Have a look to see if your antivirus is going crazy, i've have seen this problem a few times with people running mcafee.
Hope this helps.

Categories

Resources