Solved

Send email in using smtp in C#

Posted on 2014-09-27
7
244 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 70

Expert Comment

by:Éric Moreau
ID: 40347623
0
 
LVL 14

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
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 
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 70

Accepted Solution

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

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

808 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