0
votes

before writing a comment that I am duplicating questions, I want to say that i've read and tried everything that could be possible.

I am trying to send an email by gmail smtp. I use ASP.NET WebForm, also tried to deploy website on the server with .net 4.0.

My Gmail Account has been configured by enabling: POP, IMAP protocols. Also less secure app was Turned ON and two factor authentication is disabled.

Here is my code for sending emails:

try
{
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 465);
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("email", "password");
    MailMessage masage = new MailMessage();
    masage.To.Add("email");
    masage.From = new MailAddress("email");
    masage.Subject = "subject";
    masage.Body = "Hello";
    smtp.Send(masage);
}
catch (Exception eX)
{
    throw new Exception("cDocument: Error occurred trying to Create an Email" + Environment.NewLine + eX.Message);
} 

So problem is, when I am trying to send an email, I have an error

Failure sending mail.

Please, help me to figure out, what may be the issue.

Update: I tried to use all ports 465 and 587. Massage appears only after pressing button for sending. I use System.Net.Mail;

Why this question is unique: Because I tried to use all ports and I have all permissions for sending, but still have an error.

Here is a code for Sending button:

public void btn_submit_Click(object sender, EventArgs e)
    {
        //comment
        string comment = id_comment.Text.Replace("'", "\"");

        //comment end
        bool check = id_check_terms.Checked;
        string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
        string Username_new = Username.Replace("APAC\\", "");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        con.Open();
        //username
        var Fullname = "Select FirstName From UserData where (Employee='"+Username_new+"')";
        SqlCommand Fullname_command = new SqlCommand(Fullname, con);
        object Fullname_object = Fullname_command.ExecuteScalar();
        string Fullname_converted = Convert.ToString(Fullname_object);
        //usernitemame
        var items = "Select item From Basket where (Username='" + Username_new + "')";
        SqlCommand items_command = new SqlCommand(items, con);
        object items_object = items_command.ExecuteScalar();
        string items_converted = Convert.ToString(items_object);
        List<String> columnData = new List<String>();
        List<String> emaildata = new List<String>();
        List<String> emaildatacc = new List<String>();

        using (con)
        {
            //email primary
            string email = "Select Email From MBAccessoriesEmail where TOorCC='1'";
            using (SqlCommand command = new SqlCommand(email, con))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        emaildata.Add(reader.GetString(0));
                    }
                }
            }
            string email_primary = string.Join(", ", emaildata);
            //endemail
            //email cc
            string emailcc = "Select Email From MBAccessoriesEmail where TOorCC='2'";
            using (SqlCommand command = new SqlCommand(emailcc, con))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        emaildatacc.Add(reader.GetString(0));
                    }
                }
            }
            string email_cc = string.Join("; ", emaildatacc);
            //endemail


            this.GridView1.Columns[6].Visible = false;
            if (check == true)
            {
                if (GridView1.Rows.Count == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "<script>alert('You dont have anything in your basket.');</script>", false);
                }else
                {

                    try {
                        MailMessage mail = new MailMessage();
                        mail.To.Add("email");
                        mail.From = new MailAddress("email");
                        mail.Subject = "subject";
                        mail.Body = "Hello";
                        mail.IsBodyHtml = true;
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = "smtp.gmail.com";
                        smtp.Port = 587;
                        smtp.Credentials = new System.Net.NetworkCredential("email", "password");
                        smtp.EnableSsl = true;
                        smtp.Send(mail);
                        }
                    catch (Exception eX)
                    {
                        throw new Exception("cDocument: Error occurred trying to Create an Email" + Environment.NewLine + eX.Message);
                    }

                    cmd.CommandText = "Delete Basket where Username='" + Username_new + "'";
                    cmd.ExecuteNonQuery();

                    con.Close();

                    Response.Redirect("ShoppingCart.aspx");
                }
            }
        }

    }
3
Is that message appear before or after executing SmtpClient.Send() method? Can you provide stack trace if exists? Check here for possible SMTP ports.Tetsuya Yamamoto
smtp.gmail.com uses port 587.Alex Kudryashev
@TetsuyaYamamoto Massage appears exactly when I call method for sending.Bogdan Zubar
@AlexKudryashev I already tried and still nothing.Bogdan Zubar
Possible duplicate of Sending email in .NET through GmailVDWWD

3 Answers

1
votes

Google provides high security validations, to avoid send email from other device your need to give permission to that google account.

Go to https://g.co/allowaccess from a different device you have previously used to access your Google account and follow the instructions.

0
votes

Try this. I have updated mine and seems to work fine. Also make sure that your "strings" are in the same order as declared in send.

public string send(string gmailid, string password, string toemail, string subject, string body)
    {
        string msg = null;
        MailMessage mail = new MailMessage();
        mail.To.Add(toemail);
        mail.From = new MailAddress(gmailid);
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential
                    (gmailid, password);
        smtp.EnableSsl = true;
        try
        {
            smtp.Send(mail);
            msg = "Your Message has been sent!";
        }
        catch (Exception)
        {
            msg = "Your Message could NOT be sent.";
        }
        return msg;
    }
0
votes

I wanted to put it in comments but it is a little longer. I use smpt.gmail.com for years and didn't have such problem. The only difference is that I use to place mail settings to web.config or app.config

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network defaultCredentials="false" host="smtp.gmail.com" password="MYPASSWORD" port="587" userName="MYACCOUNTEMAIL"/>
      </smtp>
    </mailSettings>
</system.net>

and send email like this

var cli = new System.Net.Mail.SmtpClient();
cli.EnableSsl = true; //for some reason .config settings don't work here
//no more cli settings
var msg = new System.Net.Mail.MailMessage();
// do all other things
//finally
cli.Send(msg);

It works for me.