-3

I want to send an e-mail with an attachment. This is my code:

try{
    OpenFileDialog dlgs = new OpenFileDialog();
    if (dlgs.ShowDialog() == DialogResult.OK)
    {
        string path = dlgs.FileName.ToString();
        label10.Text = path;
    }
    MailMessage mail = new MailMessage("rajithaprasad3@gmail.com","rajithaprasad3@gmail.com","no","no");
    mail.Attachments.Add(new Attachment(label10.Text));
    SmtpClient client = new SmtpClient("smtp.gmail.com");
    client.Port=587;
    client.EnableSsl = true;
    client.Send(mail);   
    MessageBox.Show("Succcessfully Send Your Backup.Please check Mail Inbox", "done", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
catch (Exception ex){
    MessageBox.Show(ex.ToString());
    MessageBox.Show("This mail Cant Be Sent Make sure You are connected to the internet\n or check whether the particular file stil exite in the system.make sure provided informations are correct", "Eror", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

But when I run the application, it throws an exception message like this

How can I fix it?

vojta
  • 5,591
  • 2
  • 24
  • 64
  • 2
    Google may block sign in attempts from some apps or devices when you try to login from some app. Check this answer for more details: http://stackoverflow.com/a/32475872/2946329 – Salah Akbari Dec 03 '15 at 11:48
  • 1
    Possible duplicate of [Sending email through Gmail SMTP server with C#](http://stackoverflow.com/questions/704636/sending-email-through-gmail-smtp-server-with-c-sharp) – PaulG Dec 03 '15 at 11:49
  • look into this too.. http://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not – Awais Mahmood Dec 03 '15 at 11:49
  • and also.. http://stackoverflow.com/questions/18503333/the-smtp-server-requires-a-secure-connection-or-the-client-was-not-authenticated – Awais Mahmood Dec 03 '15 at 11:50
  • do you have enough privileges to send a mail? – Amit Kumar Ghosh Dec 03 '15 at 11:51

1 Answers1

0

I don't see where you've provided the login credentials for the gmail account. You need to set UseDefaultCredentials to false and then provide the login credentials. Example below:

client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("email@gmail.com", "password");

Also, with gmail there is no point setting the MailMessage from parameter, as gmail ignores that setting.

Also, make sure that you've configured the gmail account to allow less secure applications.

user1666620
  • 4,800
  • 18
  • 27