Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Send email in using smtp in C#

Posted on 2014-09-27
7
Medium Priority
?
259 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

Use Filtering Commands to Process Files in Linux

Learn how to manipulate data with the help of various filtering commands such as `cat`, `fmt`, `pr`, and others in Linux.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
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…

688 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