Error while trying to send an email in asp.net - c#

I was trying to impliment an email option in my program..
The follwing exception was thrown
+$exception {"The server rejected one or more recipient addresses. The server response
was: 550 5.7.1 <"mail-id">... Relaying denied. IP name lookup failed [172.25.9.23]\r\n"}
System.Exception {System.Web.HttpException}
This is what i have done......
MailMessage objEmail = new MailMessage();
objEmail.To = txtTo.Text;
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCC.Text;
objEmail.Subject = txtSubject.Text;
objEmail.Body = txtBody.Text; ;
objEmail.Priority = MailPriority.High;
WebMsgBox.Show("test");
SmtpMail.SmtpServer = "someserver.com";
MailAttachment attach = new MailAttachment(#"D:\email.txt");
objEmail.Attachments.Add(attach);
try
{
SmtpMail.Send(objEmail);
WebMsgBox.Show("Your Email has been sent sucessfully - Thank you");
}
catch (Exception exc)
{
WebMsgBox.Show("Send failure: " + exc.ToString());
}

Perhaps check that the server you are using to send with (smtp) has the sender machine IP whitelisted. I don't actually know how this is done but your infrastructure folks could help. Seems as though the smtp server has been secured somewhat.

When we try to send mail, there are lots of configuration settings have to be ok including some background things. (mailserver, antivirus, firewalls,routers, anti spyware etc…). Have you checked your SMTP server (services) is enabled or not ?
I am not sure 100% that below steps solve your problem, but you can check your SMTP server configurations by it :
In the Control Panel >> Administrative Tools >> Internet Information Services.
Open the node for your computer, right-click the Default SMTP Virtual Server node and choose Properties.
In the Access tab, click Connection.
Select Only the list below, click Add and add the IP 127.0.0.1. This restricts connections to just the local computer, i.e., localhost. Close the Connection dialog box.
Click Relay and repeat Step 4 to allow only localhost to relay through this server.
For IIS7, you can do it by :
Open IIS and select the node for your computer, double click on "SMTP Email" option at right side panel.
You can set SMTP server and port details there.
In your firewall or router (or both), close incoming port 25. This is an important security measure that will prevent spammers from finding your SMTP server and using it to relay spam.
Hope this will solve your problem.

Related

Getting the SMTP server and host from the system configuration in Windows

In Windows you can configure the mail settings from the control panel. What I want to know is where is that information stored? I need to write an app that can send email and by default I want to use those settings. I assumed that if I used the parameterless constructor of SmtpClient it would read them, however when I run the following code:
var smtp = new SmtpClient();
var host = smtp.Host;
var port = smtp.Port;
Console.WriteLine("{0}:{1}", host,port);
I get the host as null (though the port is 25.) If I send a message through it, it throws an exception saying "Host not specified".
Where can I get this pre-configured data?
You need to set the property first before checking for its value otherwise it will be null. However, by default, the port is 25. That's why you see 25 for port even though none was specified. Here's the definition of Host property of SmtpClient object.
public string Host { set; get; }
Member of System.Net.Mail.SmtpClient
Summary:
Gets or sets the name or IP address of the host used for SMTP transactions.
Returns:
A System.Strin
g that contains the name or IP address of the computer to use for SMTP transactions.
Try this...
var smtp = new SmtpClient();
smtp.Host = "localhost"; //your mail server host name or ip address
var host = smtp.Host;
var port = smtp.Port;
Console.WriteLine("{0}:{1}", host,port);
Usually you would need the SMTP server name before hand and use this info as part of your configuration in your program. You can have the user obtains this information from outlook settings. I assuming you already know this. For whatever reasons you want to get the SMTP server name dynamically, this activity may be viewed as hacking and can pose a security issue to the user. Can you image if some programs automatically use your mail server pre-configured in outlook to send our some emails?
With that said, one way to achieve this is to have a 3rd party port scanner as part of your process to get a list of potential SMTP server names and use the helo command to verify SMTP existence. This should help determine which ip is the SMTP server.

Using SmtpClient, and getting "the target machine actively refused it"

I am trying to use System.Net.Mail for an application to send an email, but get this exception:
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: No connection could be made
because the target machine actively refused it 198.238.39.170:25
The code I am using is:
string mailserver = "Scanmail.ofm.wa.lcl";
MailMessage msg = new MailMessage("albert#einstein.net", "snark#snarky.com", "Very subjective", "A message body!");
SmtpClient client = new SmtpClient(mailserver);
client.Send(msg);
Obviously the email addresses above are fictional, but in the actual code it uses real email addresses in the system. The mail server address is accurate.
I am tempted to think that I need to put some kind of security credentials in there, but not sure where - although #Andre_Calil's advice suggests this is not the problem, and that possibly the mail server is configured to prevent my development machine from connecting. So how is this to be overcome?
So, as we were talking, your server is probably configured to deny relay from every machine, which is a recommended security setting.
From your development machine, open a prompt (command) and type telnet SMTP_SERVER_IP_ADDRESS 25. This command will try to stablish a basic socket connection on port 25, which is the default SMTP port. If it's successful, you'll still have to discover whether the server requires authentication.
However, if it's unsuccesful, you'll have to put your code on hold until you can get the help of a sysadmin.
One other thing to try is to repeat this same test from a app server, because the SMTP server may be configured to allow app_server and deny everybody_else.
Regards

Unable to send mail from ASP.NET web page

I have a Contact Us page in my website from which I am trying to send mail.Here is my code
MailMessage feedBack = new MailMessage();
feedBack.To.Add("some#some.com");
feedBack.From = new MailAddress("MyClient#some.com");
feedBack.Subject = "Mail from My Client's Website.";
feedBack.Body = "Sender Name: " + Name.Text + "<br/><br/>Sender Last Name:"+LastName.Text+"<br/><br/>Sender Company:"+Company.Text+"<br/><br/>Sender Designation:"+Designation.Text+"<br/><br/>Sender Email:"+Email.Text+"<br/><br/>Sender Phone No:"+ PhoneNo.Text+"<br/><br/>Sender Enquiry:"+Enquiry.Text;
feedBack.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.MyClient.com"; //Or Your SMTP Server Address
//smtp.Port = 25;
//smtp.EnableSsl =false;
smtp.Credentials = new System.Net.NetworkCredential("MyClient#some.com","XXXX");
//Or your Smtp Email ID and Password
smtp.Send(feedBack);
All the time I keep getting 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 64.37.118.141:25
I have verified with my client and all the details are correct(smtp server name,credentials).
I also tried setting port to 587 and 465 but it did not work.
Can someone help me out with this?
What can be the cause?
I am not able to find it.
Any suggestions are welcome.
I tested the ip above with port 25 through telnet and got the following response:
Command:
telnet 64.37.118.141 25
Response:
Could not open connection to the host, on port 25: Connect failed
Most likely port 25 is being blocked. You will need to find what port is used with your pop/smtp servers.
MEDIUM TRUST
If you are on a shared hosting service, chances are that ASP.Net is set to run in medium-trust (as it should). This restricts SMTP to port 25 only, you cannot use any other port.
SMTP problems when ASP.NET is not running in full-trust
SO similar post
Have you checked that the server that the web application resides on is set up to be allowed to send mail through the SMTP server? Trust connections sometimes have to be setup to allow relaying off one server throught another.

Sending email from a .net application via a mail server with a self-signed SSL certificate

I installed hmailserver 5.3.2 and configured it. It receives and sends
emails normally, but I wanted to use it to send emails from a .net/C#
application located in another server, and for that I wanted to use
SSL communication. Before, the application was configured to send
emails via gmail, on port 587 and it worked ok, but now we want to use
our own mail server. We first configured the application to connect on
smtp.domain.com on port 25 and that works, it sends the email.
Then we
created a self signed certificate to test the if we could send the
message through a secure channel.I created the certificate with
openSSL setting common name as: mail.domain.com, smtp.domain.com,
*.domain.com, domain.com. I opened port 587 on the firewall and
configured hmailserver to use a certificate for inbound connections on
that port.
None of the certificates I created worked (I tried one and then
created another one and so on), generating the following (generic) exception in the
application:
System.Exception: _COMPlusExceptionCode = -532459699
Of course I also tried to connect via telnet: telnet smtp.domain.com
587, and I just got a blank screen. It is not a firewall issue since
when I disable the ssl on port 587 I can connect normally.
Looking at the log doesn't even show an attempt to connect when using
587 with SSL.
I already checked these questions: Getting SmtpClient to work with a self signed SSL certificate and Using a self-signed certificate with .NET’s HttpWebRequest/Response, but it didn't solve my problem. The approach with ServerCertificateValidationCallback didn't have any influence.
I tried with ports 25 (which is also proposed in one of the questions above), 465, 587, and with all 3 it happens the same: The initial handshake (SYN / SYN-ACK / ACK) and after about 80s the connection is closed (FIN), nothing in between.
Do I have to install that certificate somewhere so the .net application sees it as trusted? I mean, I already installed it as a Trusted Root Certification Authority and could check by running mmc, so I have no idea where to go now...
Thanks for the help!
PS: Not sure if this belongs to ServerFault since it concerns a C# application but also a mail server...
EDIT: Code sample:
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
SmtpClient mailClient = new SmtpClient("smtp.domain.com");
mailClient.Credentials = new NetworkCredential("username#domain.com", "pwd");
mailClient.Port = 587;
mailClient.EnableSsl = true;
MailMessage mailMessage = new MailMessage("mailAddressFrom", "mailAddressTo", "subject", "body");
mailMessage.IsBodyHtml = true;
mailClient.Send(mailMessage);
EDIT 2: Log (Based on Ramunas' suggestion):
"TCPIP" 3588 "2010-06-23 10:02:49.685" "TCPConnection - Posting AcceptEx on 0.0.0.0:465"
"DEBUG" 3588 "2010-06-23 10:02:49.809" "Creating session 24039"
"TCPIP" 772 "2010-06-23 10:04:29.639" "TCPConnection - SSL handshake with client failed. Error code: 2, Message: End of file, Remote IP: X"
"DEBUG" 772 "2010-06-23 10:04:29.639" "Ending session 24039"
currently, you can not send mail using c# 4/.NET 4 to a hMailServer regardless whether the certificate used by hMailServer is purchased or self-signed.
the problem is two part AFAIK ... c# 4/.NET 4 will only send using TLS and port 587; hMailServer does not currently support STARTTLS. c# 4/.NET 4 does not support the alternative of 465/SSL.
see this thread "configuring SSL confusion ..." at hMailServer's forum.
"SmtpClient.EnableSsl Property ":
"An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported." -- MSDN
As gerryLowry said:
c# 4/.NET 4 will only send using TLS and port 587;
hMailServer does not currently support STARTTLS
You can update your hMailServer to hMailServer 5.5.1 (BETA) here
It now supports STARTTLS and with port 587 all is working correctly.
This is a sophisticated mechanism but in simple words client (computer you're making connection from) should know about WHO is certificate issuer (in your case your server is certificate issuer). If it does not find it in it's Trusted Root Certificate Authorities list then it considers this connection to be unsafe. (I bet you've seen browser warning you about unsafe request to some https://.... site).
Open Certificates snap-in in your Microsoft management console on a client computer and try to add the same self signed certificate to a Trusted Root Certificate Authorities list.
I installed hMailServer, created self signed certificate, added it to hMailServer and was not able to send mail via it, too. Though I was successful while sending emails without certificate.
I enabled logging on hMailServer (for everything) and tried again with no luck. But I saw an error in a log file stating
"Severity: 2 (High), Code: HM5113,
Source: TCPServer::Run(), Description:
Failed to load certificate file. Path:
<...>test.cer,
Address: 0.0.0.0, Port: 25, Error: An
invalid argument was supplied"
Maybe this is a case on your hMailServer also?
I have port 25 as normal SMTP open on my hMailServer as well as port 465 for SSL, so I had to change my code to point to the normal SMTP configuration. It should work after that. As for SSL, sorry, it won't work on hMailServer...
MailMessage message = new MailMessage();
message.From = new MailAddress("me#myself.home", "Me");
message.Body = "hello, World!";
message.To.Add(new MailAddress("you#myself.home", "You"));
SmtpClient client = new SmtpClient("secure.myself.home", 25);
client.EnableSsl = false;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("me#myself.home", "pwd");
client.Send(message);

C# SmtpClient error: not local host?

I'm sending a simple mail with attachment using SmtpClient but I get this error:
Mailbox unavailable. The server response was: not local host
example.com, not a gateway
System.Net.Mail.SmtpFailedRecipientException:
Mailbox unavailable.
The server response was: not local host example.com, not a gateway at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message)
And the code:
public static void CreateMessageWithAttachment(byte[] compressed)
{
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"noreply#example.com",
"recepient#example.com",
"Hello.",
"How are you?");
// Create the file attachment for this e-mail message.
Stream attachStream = new MemoryStream(compressed);
Attachment attachment = new Attachment(attachStream, MediaTypeNames.Application.Octet);
message.Attachments.Add(attachment);
//Send the message.
SmtpClient client = new SmtpClient("123.12.12.123");
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Send(message);
attachment.Dispose();
}
Of course the domain and IP is valid in the original code. I have tried using both "localhost" and IP but getting same error. Googling returned 3 results of which the helpful one seems to be in chinese and firewall preventing me from translating it.
Thanks in advance.
I've searched for: C# smtpclient error The server response was: not local host example.com, not a gateway and got 27K+ results.
If you are using localhost have a look at this page it says:
This is a relay error. Make sure you can relay through the SmtpMail.SmtpServer
either by your IP address, by your MailMessage.From address, or if you need to
authenticate, check out 3.8 How do I authenticate to send an email?
If SmtpMail.SmtpServer is set to "127.0.0.1" or "localhost", and you are using
the built in IIS SMTP Service, you can allow relaying for 127.0.0.1 by
1) Opening the IIS Admin MMC
2) Right-Clicking on the SMTP Virtual Server and selecting Properties
3) On the Access tab, click the Relay button
4) Grant 127.0.0.1 (or the IP address used by System.Web.Mail) to the
Computers list.
5) Close all dialogs
6) Restarting the SMTP Service

Categories