SmtpException while sending mails from a particular mailing server - asp.net

My question may be duplicate one, but i didn't got a proper solution for my problem.That's why i am asking.
I have a asp website.I am using smtpclient to send messages.My code is working fine with gmail settings.But in the production server they are using Bellnetwork's(smtp10.on.aibn.com) mailing server.They are using port 25 and also not using SSL(email provider doesn't support SSL).But the same mail settings was running fine for the last 2-3 years,but now when we send some messages from our site(production) 1 or 2 fails to send out and others will send out successfully.The strange thing is there was no problem for the last 3years.I am getting the following errors for the failed mails.
Exceptions:
1.
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.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Handler.BLL.cSendMail.SendMail(String p_strFrom, String p_strDisplayName, String p_strTo, String p_strSubject, String p_strMessage, String strFileName)
2.
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
3.
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 67.69.240.69:25
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 67.69.240.69: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, Int32 timeout, 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, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, 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(String host, Int32 port)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Handler.BLL.cSendMail.SendMail(String p_strFrom, String p_strDisplayName, String p_strTo, String p_strSubject, String p_strMessage, String strFileName)
my code:
public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
{
try
{
p_strDisplayName = _DisplayName;
string smtpserver = _SmtpServer;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(_From,_DisplayName);
smtpClient.Host = _SmtpServer;
smtpClient.Port = Convert.ToInt32(_Port);
string strAuth_UserName = _UserName;
string strAuth_Password = _Password;
if (strAuth_UserName != null)
{
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
smtpClient.UseDefaultCredentials = false;
if (_SSL)
{
smtpClient.EnableSsl = true;
}
smtpClient.Credentials = SMTPUserInfo;
}
message.From = fromAddress;
message.Subject = p_strSubject;
message.IsBodyHtml = true;
message.Body = p_strMessage;
message.To.Add(p_strTo);
try
{
smtpClient.Send(message);
return true;
}
catch (SmtpException ee)
{
Log.WriteSpecialLog("smtpClient mail sending first try failed : " + ee.ToString(),"");
Log.WriteSpecialLog("status code : " + ee.StatusCode, "");
}
}

This code is working for me
public static string sendMail(string fromEmail, string toEmail, string subject, string body, string Name, string bcc="" , string replyTo="")
{
MailMessage mailer = new MailMessage
{
IsBodyHtml = true,
From = new MailAddress(fromEmail, "yoursite.com"),
Subject = subject,
Body = body,
BodyEncoding = Encoding.GetEncoding("utf-8")
};
mailer.To.Add(new MailAddress(toEmail, toEmail));
//
if (!string.IsNullOrEmpty(bcc))
{
mailer.Bcc.Add(bcc);
}
//
if (!string.IsNullOrEmpty(replyTo))
{
mailer.Headers.Add("Reply-To", replyTo);
}
//
AlternateView plainView = AlternateView.CreateAlternateViewFromString(Regex.Replace(body, "<(.|\\n)*?>", string.Empty), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
mailer.AlternateViews.Add(plainView);
mailer.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SMTPserver"]);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
NetworkCredential basicAuthenticationInfo = new NetworkCredential(ConfigurationManager.AppSettings["passMail"], ConfigurationManager.AppSettings["passKey"]);
smtp.UseDefaultCredentials = false;
smtp.Credentials = basicAuthenticationInfo;
smtp.EnableSsl = false;
smtp.Port = ConfigurationManager.AppSettings["Port"];
//
try
{
smtp.Send(mailer);
return "Email sent successfully !";
}
catch (Exception ex)
{
return "Failure in Email Message= !" + ex.message;
}
}

Related

aws simple email service not working with godaddy hosting asp.net

I was earlier using godaddy email services to send emails from my web application in asp.net. But now I moved to aws ses as it is fast.
The thing is in development environment(Local) aws email is working fine and emails are going but when I am deploying it in godaddy server then no email is going. Do I need to do any settings at godaddy server level or it is my code fault? My website is in shared hosting environment. Is it the reason.
Is this related to MX records?
Here is my code
string UserName = ConfigurationManager.AppSettings["UserName"];
string EmailFrom = ConfigurationManager.AppSettings["EmailFrom"];
string EmailFromDisplayName = ConfigurationManager.AppSettings["EmailFromDisplayName"];
string EmailFromPwd = ConfigurationManager.AppSettings["EmailFromPwd"];
string EmailBcc = ConfigurationManager.AppSettings["EmailBcc"];
bool EmailIsSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["EmailIsSSL"]);
int EmailPort = Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"]);
string EmailHost = ConfigurationManager.AppSettings["EmailHost"];
//Create the msg object to be sent
MailMessage mailMessage = new MailMessage();
//Default email message
mailMessage.Bcc.Add(EmailBcc);
//Configure the address we are sending the mail from
MailAddress address = new MailAddress(EmailFrom, EmailFromDisplayName);
mailMessage.From = address;
//Loop all to recepients
foreach(string emailTo in toAddress)
{
mailMessage.To.Add(emailTo);
}
//Loop to add all Bcc addresses...
foreach (string emailBcc in bccAddress)
{
mailMessage.Bcc.Add(emailBcc);
}
//Loop to add all CC addresses...
foreach (string emailCc in ccAddress)
{
mailMessage.CC.Add(emailCc);
}
//Add attachments...
foreach (string filePathWithName in relativeFilePathsToBeAttached)
{
if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(filePathWithName)))
{
Attachment data = new Attachment(
System.Web.HttpContext.Current.Server.MapPath(filePathWithName),
MediaTypeNames.Application.Octet);
// your path may look like Server.MapPath("~/file.ABC")
mailMessage.Attachments.Add(data);
}
}
mailMessage.Subject = mailSubject;
mailMessage.Body = mailBody;
mailMessage.IsBodyHtml = IsBodyHtml;
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = EmailIsSSL;
client.Host = EmailHost;
client.Port = EmailPort;
//Setup credentials to login to our sender email address ("UserName", "Password")
//NetworkCredential credentials = new NetworkCredential(EmailFrom, EmailFromPwd);
NetworkCredential credentials = new NetworkCredential(UserName, EmailFromPwd);
client.UseDefaultCredentials = true;
client.Credentials = credentials;
if (ConfigurationManager.AppSettings["IsMailEnabled"].ToString() == "true")
{
client.Send(mailMessage);
}
I am getting this error on server
Failure sending mail.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.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) at System.Net.Mail.SmtpClient.Send(MailMessage message) at TestCookie.ExecuteSendEmail(String mailBody, String mailSubject, List1 toAddress, List1 bccAddress, List1 ccAddress, List1 relativeFilePathsToBeAttached, Boolean IsBodyHtml)
The issue was with port number. I was using 587 and 25 and it is not working. But when I used 2587 and it worked for me. I don't know how. If someone can explain then that will help.

Strange .NET Mail behaviour with Disposables

Recently been going through a bunch of code tidying up and "improving" things, I noticed this bit of code used for sending emails:
Dim SmtpServer As New SmtpClient() With {
.Port = 25,
.Host = Email.Hostname,
.Credentials = New NetworkCredential() With {
.UserName = Email.UserName,
.Password = Email.Password
}
}
Dim mail As New MailMessage() With {
.From = Email.Sender,
.Subject = Email.Subject,
.IsBodyHtml = True,
.Body = Email.WrappedHtml
}
If Not Email.Attachments Is Nothing Then
For Each a In Email.Attachments
mail.Attachments.Add(a)
Next
End If
mail.To.Add(New MailAddress(Email.Recipient.Email, Email.Recipient.Name))
Call SmtpServer.Send(mail)
SmtpServer.Dispose()
mail.Dispose()
SmtpServer = Nothing
mail = Nothing
In that example the Email Object is a Class containing basic email information, recipients, sender, attachments etc.
The code above works perfectly....
But, I noticed that SmtpServer and MailMessage are both Disposable objects, and it would be better practice to wrap them in Using statements, thus:
Using SmtpServer As New SmtpClient() With {
.Port = 25,
.Host = Email.Hostname,
.Credentials = New NetworkCredential() With {
.UserName = Email.UserName,
.Password = Email.Password
}
}
Using mail As New MailMessage() With {
.From = Email.Sender,
.Subject = Email.Subject,
.IsBodyHtml = True,
.Body = Email.WrappedHtml
}
If Not Email.Attachments Is Nothing Then
For Each a In Email.Attachments
mail.Attachments.Add(a)
Next
End If
mail.To.Add(New MailAddress(Email.Recipient.Email, Email.Recipient.Name))
Call SmtpServer.Send(mail)
End Using
End Using
However... when I do that, and send more than a couple of emails in quick succession I get:
System.Net.Mail.SmtpException: Failure sending mail. ---> 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 read430) at System.Net.Mail.SmtpReplyReaderFactory.Read430s(SmtpReplyReader caller, Boolean one430) at System.Net.Mail.SmtpReplyReaderFactory.Read430(SmtpReplyReader caller) at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)
It appears that the Using Statements are causing the connection to close too early....
Anyone else had similar experience/tips on solution?
I've reverted to the old code, but it is better practice to wrap in using statements, right?

Send Email using SMTP in web api vs asmx service

I am trying to send notification email in ASP.NET Web API. Following is the code
[HttpPost]
[Route("api/UpdateUser")]
public Foo UpdateUser(Foo vm)
{
/* some data base operations here....
......
......
*/
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("<SMTP Server>", 587);
mail.From = new MailAddress("test#test.com");
mail.To.Add("toemail#test.com");
mail.Subject = "You are subject";
mail.IsBodyHtml = true;
mail.Body = "Hello My Dear User";
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Foo newVM = new Foo();
}
But it throws following error:
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 <server IP>:587
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.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)
Now, i created an entirely new asp.net web project and placed same code in an asmx service (SOAP), and call it using soap client tools, it works just fine..
i deployed both in two separate IIS applications on same (test environment)server, only difference is web.api is a part of a ASP.NET MVC Application where as asmx service part of asp.net web application.
Result:
asmx service works but WEB API errors out with above error message.
Question is why ? what am i missing ?
I searched around and found following configuration could help
<system.net>
<defaultProxy>
<proxy usesystemdefault="False"/>
</defaultProxy>
:( but unfortunately in my case it didn't help...
Any one faced such issue ?
try this
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress("yourmail");
mailMessage.To.Add("akash073#waltonbd.com");
mailMessage.CC.Add("akash073#gmail.com");
mailMessage.Subject = "Test";
mailMessage.Body = "Test";
var smtp = new SmtpClient();
smtp.Host = "your host";
smtp.Port = 25;//your port
smtp.Credentials = new System.Net.NetworkCredential("userName", "password");
smtp.Send(mailMessage);

Getting "Unable to connect to a remote server" error while calling a service using Web Application

I am getting "Unable to connect to a remote server" error while calling a service using Web Application. But the same code runs when I use it from a console application. Here is the stack trace:-
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
Exception& exception)
Here is the code which I am using:-
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
X509Certificate cert = X509Certificate.CreateFromCertFile(certificatePath);
req.ClientCertificates.Add(cert);
using (StreamReader sr = File.OpenText(inFilePath))
{
string xml = sr.ReadToEnd();
string postRaw = string.Format("request={0}", System.Web.HttpUtility.UrlEncode(xml));
byte[] buf = Encoding.UTF8.GetBytes(postRaw);
req.ContentLength = buf.Length;
try
{
Stream s = req.GetRequestStream(); //This is where I get the error.
s.Write(buf, 0, buf.Length);
s.Close();
}
catch (Exception ex)
{
}
}
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Console.WriteLine(string.Format("HTTP status code: {0}, content length: {1}, content encoding: {2}",
resp.StatusCode, resp.ContentLength, resp.ContentEncoding));
if (resp.StatusCode == HttpStatusCode.OK)
{
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line + "\r\n");
}
}
string resXml = sb.ToString();
}
Is there any setting in web.config which I need to mention for this to work in a web application?

Using gmail smtp server for emails in asp.net web site in IIS 6.0

I've uploaded my asp.net web site to IIS 6.0, and it's currently working, except for sending e-mails. In my asp.net test server, I was able to use gmail as an smtp server for outgoing e-mails from my gmail account.
In the IIS live server version, when I click the button control that is supposed to send the message, the loading bar of the browser only reaches 25% and then stops, no error or message.
The following is my code for the button click event that sends the e-mail.
private void sendUsername()
{
/**
* Sends user's username to
* their listed e-mail address.
*
*/
string username = Session["retrievedUsername"].ToString();
string usernameSent = "usernameSent";
string from = "mandizi84#gmail.com";
string to = enterEmailTextBoxTwo.Text;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "The All-Star R.E.C. Center", System.Text.Encoding.UTF8);
mail.Subject = "ASRC password retrieval.";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
string htmlBody = "Hi " + username + "," + "<br /><br />";
htmlBody += "Your username is " + "'" + username + "'" + "." + "<br /><br />";
htmlBody += "If you don't remember your password, return to the Credential Recovery section to get a new password." + "<br /><br />";
htmlBody += "Your membership is much appreciated." + "<br /><br />";
htmlBody += "Thank you," + "<br /><br/>";
htmlBody += "The All-Star R.E.C. Center";
mail.Body = htmlBody;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(from, "password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(mail);
Session["usernameSent"] = usernameSent;
Response.Redirect("~/Email Confirmation.aspx", false);
}
catch (Exception ex)
{
Exception ex2 = ex;
while (ex2 != null)
{
errorLabel.Text = "Mail could not be sent. ";
errorLabel.Text += ex2.ToString();
}
}
}
I did some research and read in a few places that configuring the mail server role is not necessary if I use gmail account, but in other places I did.
So my question is in IIS, do I need to configure the mail server role and then add the gmail smtp to use that smtp service in my live website on IIS 6.0?
Thanks
Update: I just removed the while loop from my catch block and received the following error:
Mail could not be sent. 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 74.125.95.109:587 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, Int32 timeout, 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, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, 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 Credential_Recovery.sendUsername() in e:\Senior Design\Second Version\ASRC\Credential Recovery.aspx.cs:line 619
line 619 in my code is "client.Send(mail)"
Dont you think the While loop in your Catch block is going into an infinite loop, thus not showing you the actual error?if therez an Exception, ex2 will never be null. its like a while(1) statement!!

Resources