Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 266
  • Last Modified:

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

0
mctc
Asked:
mctc
  • 2
  • 2
  • 2
  • +1
1 Solution
 
É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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 2
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now