Send email in using smtp in C#

Hi,
I am trying to send email using the smtp method. When I run the page, it goes through the code with it's proper values but doesn't send the email. Instead the browser appears with an error saying "Internet Explorer cannot display the webpage". When debugging it goes to the catch statement instead of finishing the remainder of the code block.
The code stops on this line: smtp.Send(fromAddress, toAddress, subject, body);

There is no smtp code in web.config. Using Framework 3.5

Your help is greatly appreciated.

Here is the code:
-------------------------------
MarkUp Code
-------------------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmailTest.aspx.cs" Inherits="EmailTest" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head id="Head1" runat="server">
<title>Email Test Page</title>
</head>

<body>    
<form id="form1" runat="server">

<asp:Panel ID="Panel1" runat="server" DefaultButton="idbtnSubmit">
     <p>
         Send Mail.</p>
     <p>
         Your name:
         <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ErrorMessage="*"
             ControlToValidate="idYourName" ValidationGroup="save" /><br />
         <asp:TextBox ID="idYourName" runat="server" Width="250px" /><br />
         Your email address:
         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
             ControlToValidate="idYourEmail" ValidationGroup="save" /><br />
         <asp:TextBox ID="idYourEmail" runat="server" Width="250px" />
         <asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator23"
             SetFocusOnError="true" Text="Example: username@gmail.com" ControlToValidate="idYourEmail"
             ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
             ValidationGroup="save" /><br />
         Subject:
         <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
             ControlToValidate="idYourSubject" ValidationGroup="save" /><br />
         <asp:TextBox ID="idYourSubject" runat="server" Width="400px" /><br />
         Your Question:
         <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
             ControlToValidate="idComments" ValidationGroup="save" /><br />
         <asp:TextBox ID="idComments" runat="server"
                 TextMode="MultiLine" Rows="10" Width="400px" />
     </p>
     <p>
         <asp:Button ID="idbtnSubmit" runat="server" Text="Send"
                     OnClick="Button1_Click" ValidationGroup="save" />
     </p>
 </asp:Panel>
 <p>
     <asp:Label ID="idDisplayMessage" runat="server" Visible="false" />
 </p>  


</form>

</body>
</html>

Open in new window




-------------------------------
Code Behind
-------------------------------
using System;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Web;


public partial class EmailTest : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void SendMail()
    {
        // Gmail Address from where you send the mail
        var fromAddress = "xxxxxx@gmail.com"; //your email id from which you want to send e-mail

        // any address where the email will be sending
        var toAddress = idYourEmail.Text.ToString();  //email id to whom you you are sending e-mail

        //Password of your gmail address
        const string fromPassword = "xxxxxx"; //your email password

        // Passing the values and make a email formate to display
        string subject = idYourSubject.Text.ToString();
        string body = "From: " + idYourName.Text + "\n";
        body += "Email: " + idYourEmail.Text + "\n";
        body += "Subject: " + idYourSubject.Text + "\n";
        body += "Question: \n" + idComments.Text + "\n";

        // smtp settings
        var smtp = new System.Net.Mail.SmtpClient();
        {
            smtp.Host = "smtp.gmail.com"; //host name
            smtp.Port = 587; 		  //port number
            smtp.EnableSsl = true; 	  //whether your smtp server requires SSL
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
            smtp.Timeout = 20000;
        }
        // Passing values to smtp object
        smtp.Send(fromAddress, toAddress, subject, body);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //here on button click what will be done
            SendMail();
            idDisplayMessage.Text = "Your email message has been successfully sent.";
            idDisplayMessage.Visible = true;
            idYourSubject.Text = "";
            idYourEmail.Text = "";
            idYourName.Text = "";
            idComments.Text = "";
        }
        catch (Exception ex) { throw ex; }
    }

}

Open in new window

mctcAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
0
frankhelkCommented:
What exception is thrown ?

That might give much help ....
0
mctcAuthor Commented:
Here is the exception: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Ramkisan JagtapLead DeveloperCommented:
You dont have access to the SMTP server or you have given wrong authentication details in the settings.
Please and try again!

Also check with setting
 smtp.UseDefaultCredentials = false;
0
Éric MoreauSenior .Net ConsultantCommented:
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
frankhelkCommented:
Hmm - I suspect that it is exact what the server told you (wrong credentials). But I see the following alternative causes:

1. The server doesn't accept regular (clear text) connections - it requires the connection to be encrypted by SSL. Try using appropriate settings in your code or involve some SSL wrapper program like stunnel. My regular email provider switched to allowing SSL only for email access (SMTP & POP3) last year, and I used it to conserve my beloved old mail software for another couple of years ;-)

2. I've tried to google the error code (551) for more details and found the following:
551 - The recipient is not local to the server. The server then gives a forward address to try.
That might describe another aspect of "wrong credentials" - se server is responsible for the domain, but it doesn't know that user. It possibly tells you what server to contact for delivery of that mail.

Since the SMTP protocol is a clear text protocol (which is only encapsulated in encryption if SSL'ed), an inspection of the conversation with Wireshark might reveal at what point of the conversation the problem arises. It seems to arise only from the RCPT and VRFY commands which are far beond initial authentication. Therefore I suspect some deeper cause, i.e. "not my job" in the meaning of "that user is no longer mine, please try again at server xxx". See RFC2821 for more details.
0
mctcAuthor Commented:
Thanks for the information and samples, problem resolved.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming Languages-Other

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.