I previously wrote an article on what code you can use to send email using ASP.NET C#. That article assumed that the local SMTP service was allowing anonymous relay for code on the local server (i.e. 127.0.0.1). Below is a slightly revised code sample allowing for authentication against an SMTP server in case your server has that feature enable to prevent (or at least track) spam sending from code on the local server.
sendmail.aspx
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"><title></title></head> <body> <form id="form1" runat="server"> <div> Message to: <asp:TextBoxID="txtTo" runat="server"></asp:TextBox><br/> Message from: <asp:TextBoxID="txtFrom" runat="server"></asp:TextBox><br/> Subject: <asp:TextBoxID="txtSubject" runat="server"></asp:TextBox><br/> Message Body: <br/> <asp:TextBoxID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px"> </asp:TextBox><br/> <asp:ButtonID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email"/> <br/> <asp:LabelID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
sendmail.aspx.cs
using System; using System.Web.UI.WebControls; using System.Net.Mail; publicpartialclass SendMail : System.Web.UI.Page { protectedvoid Btn_SendMail_Click(object sender, EventArgs e) { MailMessage mailObj = new MailMessage( txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text); string userName = "ftpUser"; string password = "ftpPassword"; SmtpClient SMTPServer = new SmtpClient("localhost"); SMTPServer.Credentials = new System.Net.NetworkCredential(userName, password); try { SMTPServer.Send(mailObj); Label1.Text = "Sent!"; } catch (Exception ex) { Label1.Text = ex.ToString(); } } }
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: SMTP authentication is required. at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at Default2.Btn_SendMail_Click(Object sender, EventArgs e) in c:\Users\Vinay\Documents\Visual Studio 2010\WebSites\WebSite1\Default2.aspx.cs:line 25
am getting this error please help
Asumming your username and password are correct for the SMTP Service, it sounds like you may have a service that requires SSL. If so, try adding the line below just before the Credentials statement.
SmtpClient.EnableSsl = True
SMTPServer.EnableSsl = true;
SMTPServer.EnableSsl = true;