having problems with this codes. When tested it keeps giving me the error message "Your message failed to send, please try again. "

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net.Mail;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            //Create the msg object to be sent
            MailMessage msg = new MailMessage();
            //Add your email address to the recipients
            msg.To.Add("reciever@domain.com");
            //Configure the address we are sending the mail from
            MailAddress address = new MailAddress("sender@gmail.com");
            msg.From = address;
            //Append their name in the beginning of the subject
            msg.Subject = txtName.Text + " :  " + ddlSubject.Text;
            msg.Body = txtMessage.Text;

            //Configure an SmtpClient to send the mail.
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true; //only enable this if your provider requires it
            //Setup credentials to login to our sender email address ("UserName", "Password")
            NetworkCredential credentials = new NetworkCredential("sender@gmail.com", "XXXXXXX");
            client.Credentials = credentials;

            //Send the msg
            client.Send(msg);

            //Display some feedback to the user to let them know it was sent
            lblResult.Text = "Your message was sent!";

            //Clear the form
            txtName.Text = "";
            txtMessage.Text = "";
        }
        catch
        {
            //If the message failed at some point, let the user know
            lblResult.Text = "Your message failed to send, please try again.";
        }
    }
}

Dani AI

Generated

Good call by and : surface the real exception first. For SMTP, catch SmtpException and show StatusCode and InnerException so you know whether it is auth, TLS, or policy related.

If you are using Gmail in 2025, regular passwords are no longer accepted for Workspace when apps sign in with just a username/password. Switch to OAuth or use a 16‑char App Password with 2‑Step Verification. Also stick to STARTTLS on port 587; .NET’s SmtpClient speaks STARTTLS, not SSL‑on‑connect (465). (workspaceupdates.googleblog.com)

Here is a drop‑in Web Forms example that adds the missing bits and better error reporting. Use your Gmail address and an App Password for the credentials, and keep From aligned with the authenticated account (or set ReplyTo):

using System.Net;
using System.Net.Mail;

protected void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        // If targeting .NET <= 4.6, force TLS 1.2 (remove on 4.7+).
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

        var msg = new MailMessage
        {
            From = new MailAddress("sender@gmail.com", txtName.Text),
            Subject = $"{txtName.Text}: {ddlSubject.SelectedValue}",
            Body = txtMessage.Text,
            IsBodyHtml = false
        };
        msg.To.Add("receiver@domain.com");
        // If you want replies to go elsewhere:
        // msg.ReplyToList.Add(new MailAddress(txtEmail.Text));

        using (var smtp = new SmtpClient("smtp.gmail.com", 587))
        {
            smtp.EnableSsl = true;                      // STARTTLS
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential("sender@gmail.com", "your-app-password");
            smtp.Send(msg);
        }

        lblResult.Text = "Your message was sent!";
    }
    catch (SmtpException ex)
    {
        lblResult.Text = $"Send failed: {ex.StatusCode} - {ex.Message}";
        if (ex.InnerException != null) lblResult.Text += $" ({ex.InnerException.Message})";
    }
}

Store the SMTP settings in web.config instead of hardcoding credentials. For new projects, consider MailKit; Microsoft does not recommend SmtpClient for new development. (learn.microsoft.com)

Recommended Answers

All 5 Replies

if you get rid of the try..catch block, asp.net should provide you with the actual error. At the moment, you are seeing that message because an error is causing the catch block to execute.

To see the real error, you could use:

try
{
    ...
}
catch(Exception ex)
{
//If the message failed at some point, let the user know
lblResult.Text = "Your message failed to send, please try again. Details: " + ex.ToString();
}

I have some working gmail code as below.

See if this helps you fix your problem.

        using (var mailMessage = new MailMessage(ApplicationConfig.Instance.EmailSenderAddress, recipient, subject, body))
        {
            mailMessage.IsBodyHtml = true;

            var basicCredentials = new NetworkCredential("myusername@gmail.com", "XXXXXXXXXXXXXXXXXXX");

            var smtpClient = new SmtpClient("smtp.gmail.com")
            {
                UseDefaultCredentials = false,
                Credentials = basicCredentials,
                EnableSsl = true
            };

            smtpClient.Send(mailMessage);
        }

Please, can you provide the above code in c#

It is in C#

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.