Solved

Send email in using smtp in C#

Posted on 2014-09-27
7
235 Views
Last Modified: 2014-10-02
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
Comment
Question by:mctc
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 40347623
0
 
LVL 13

Expert Comment

by:frankhelk
ID: 40348795
What exception is thrown ?

That might give much help ....
0
 

Author Comment

by:mctc
ID: 40349140
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 Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 12

Expert Comment

by:Ramkisan Jagtap
ID: 40349287
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
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 40349578
0
 
LVL 13

Expert Comment

by:frankhelk
ID: 40349753
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
 

Author Closing Comment

by:mctc
ID: 40357773
Thanks for the information and samples, problem resolved.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now