Send Email using SMTP in web api vs asmx service - asp.net

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);

Related

VB.net mail sending works in localhost but gives error in web server

I have simple email sending application that is working in localhost. But when I try to accress with my web server than it throws exception error below. Is this error with my code or with server? I am using GoDaddy Hosting. How do I fix it?
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions 68.178.213.37: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 mass_mail.confirmationMail() in G:\PleskVhosts\healthsaviour.com\httpdocs\mass-mail.aspx.vb:line 24
Imports System.Data
Imports System.IO
Imports System.Net.Mail
Imports MySql.Data.MySqlClient
Partial Class mass_mail
Inherits System.Web.UI.Page
Private Sub sendBulk_Click(sender As Object, e As EventArgs) Handles sendBulk.Click
confirmationMail()
End Sub
Private Sub confirmationMail()
Try
Dim mail As New MailMessage
Dim SmtpServer As New SmtpClient()
mail.From = New MailAddress("support#healthsaviour.com")
mail.To.Add(TextBox1.Text)
mail.Subject = "Order No"
mail.Body = "Hi"
mail.IsBodyHtml = True
SmtpServer.Port = 25
SmtpServer.Credentials = New System.Net.NetworkCredential("email", "password")
SmtpServer.Host = "smtp.secureserver.net"
SmtpServer.Send(mail)
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
End Class
I just changed my port from 25 to 80 & it started working

SendEmail in ASP.net shows me Syntax error, command unrecognized. The server response was: Dovecot ready

I want to send mail using ASP.NET with this code:
public void Semail(string subject, string messageBody, string toAddress)
{
MailMessage mail = new MailMessage();
mail.To.Add(toAddress);
//mail.To.Add("amit_jain_online#yahoo.com");
mail.From = new MailAddress("noreplykaramaoozi#eesharif.edu");
mail.Subject = subject;
string Body = messageBody;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "sina.sharif.ir"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("noreplykaramaoozi#eesharif.edu", "******");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
But after executing i got this error :
Syntax error, command unrecognized. The server response was: Dovecot ready.
This is the stacktrace
[SmtpException: Syntax error, command unrecognized. The server response was: Dovecot ready.]
System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +2176152
System.Net.Mail.SmtpClient.Send(MailMessage message) +2188821
Novitiate.fa.Register.btnLogin_Click(Object sender, EventArgs e) +2948
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
There might be issue with SMTP Server.
Try with GMAIL Settings, if mail is working with GMAIL server, then most probably there is issue with your Mailing Server.
It looks like you are using POP3 or IMAP server not SMTP Server, please check configuration of your Server
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
When using gmail smtp server and ssl be sure to use 587 port instead of 465, this solved the issue for me.

SmtpException while sending mails from a particular mailing server

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;
}
}

Facebook SDK 5+ authentication token error: A connection attempt failed because the connected party did not properly respond after a period of time

I have an issue I have been trying to fix since this morning (now over 8h). I got the facebook cookie contents, found the auth token which works fine on its own in the browser
https://graph.facebook.com/me?access_token=201856003211297|2.AQAHJg3GugHIHhec.3600.1314442800.1-100002411647354|RAylZSUax4pdKcIt--QruS-Qcgc
But
Whenever I try to get the user information, the web-page crashes down very nicely with the error below.
I have tried to read from the page using web request:
'Dim inputFile As String = "https://graph.facebook.com/me?access_token=" & access_token
'Dim sDiskFile As String = "auth.txt"
'Dim _wrequest As WebRequest = WebRequest.Create(inputFile)
'Dim _wresponse As WebResponse
'_wresponse = _wrequest.GetResponse()
'Dim _stream As Stream = _wresponse.GetResponseStream()
'Dim oReader As New StreamReader(_stream, Encoding.ASCII)
And it crashed with the same error. I decided to give the Facebook SDK 5 a go and the same error is happening:
Dim access_token As String = GetFacebookTokenFromCookie()
If access_token = "" Then
litUser.Text = "<fb:login-button perms='email'>Login with Facebook</fb:login-button>"
Else
Dim app As New DefaultFBApp
Dim _ctx As New FacebookWebContext(app)
Dim fb As New Facebook.FacebookClient(app)
fb.AccessToken = access_token
Dim parameters As New Dictionary(Of String, Object)()
parameters("fields") = "id,name"
Dim result As Object = fb.Get(parameters)
Dim id = result.id
Dim name = result.name
Dim firstName As String = result.first_name
Dim lastName = result.last_name
Dim link = result.link
Dim username = result.username
Dim gender = result.gender
Dim male = result.locale
litUser.Text = "Welcome " & firstName
End If
DefaultFBApp is:
Public Class DefaultFBApp
Implements Facebook.IFacebookApplication
With all the must-implement fields added in and the api key and secret filled in.
Same error:
Server Error in '/' Application.
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 69.171.224.21:443
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: 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 69.171.224.21:443
Source Error:
Line 25: parameters("fields") = "id,name"
Line 26:
Line 27: Dim result As Object = fb.Get(parameters)
Line 28:
Line 29: Dim id = result.id
Source File: masterpage.master Line: 27
Stack Trace:
[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 69.171.224.21:443]
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
[WebExceptionWrapper: Unable to connect to the remote server]
FluentHttp.HttpHelper.OpenRead() +191
Facebook.FacebookClient.Api(String path, IDictionary`2 parameters, HttpMethod httpMethod, Type resultType) +253
Facebook.FacebookClient.Get(IDictionary`2 parameters) +44
ASP.masterpage_master.Page_Load(Object sender, EventArgs e) in E:\kunden\homepages\6\d364763622\www\wsb6301158401\masterpage.master:27
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Version Information: Microsoft .NET Framework Version:2.0.50727.5446; ASP.NET Version:2.0.50727.5420
Any help would be mostly appreciated

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