0

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");
                }
            }
        }

    }
Bogdan Zubar
  • 73
  • 12

3 Answers3

1

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.

saAction
  • 2,035
  • 1
  • 13
  • 18
0

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;
    }
Noob Coder
  • 11
  • 5
  • something you are doing on the send operation is causing it to fail. – Noob Coder Aug 14 '18 at 06:43
  • I just updated it. I had the old version instead of the new which the new has no "attachment" – Noob Coder Aug 14 '18 at 06:44
  • Thank you, but it didn't help me :( – Bogdan Zubar Aug 14 '18 at 06:45
  • You're welcome. lets make it work. are you creating a DLL and using it as a reference ? – Noob Coder Aug 14 '18 at 06:46
  • I use System.Net.Mail as a reference – Bogdan Zubar Aug 14 '18 at 06:51
  • that reference is within the DLL in your actual form you should be calling to the DLL as a reference. like "using SendGmail;" or what ever you have named the DLL to. – Noob Coder Aug 14 '18 at 06:52
  • within my form that I allow the email to be written and sent from I have "using SendEmail;" as a reference that calls to the DLL created to handle gmail which is what I provided above.. – Noob Coder Aug 14 '18 at 06:55
  • I also have tested once again just to be 100% percent and the code provided is working perfectly. – Noob Coder Aug 14 '18 at 06:56
  • Could you say what did you enable in your Google account, maybe problem somewhere there? – Bogdan Zubar Aug 14 '18 at 06:59
  • I have all the same settings in my gmail that you do. You are not referencing to the Gmail.DLL correctly or formatting the form correctly to send the email. if you have "Allow less secure apps" turned on as you say you do then you are good. the problem is within your form. – Noob Coder Aug 14 '18 at 07:01
  • I changed some code and now i have this problem "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 108.177.15.108:587 " – Bogdan Zubar Aug 15 '18 at 06:54
0

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.

Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36