Search code examples
c#gmail

How to send gmail from windows forms


What I want is to create a software using C# winforms that can automate sending emails to various list of people.

What I'd tried was this implementation:

try
{
    SmtpClient client = new SmtpClient("smtp.gmail.com");
    client.Port = 587;
    client.EnableSsl = true;
    client.Timeout = 100000;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential(
        "[email protected]", "yourgmailpassword");
    MailMessage msg = new MailMessage();
    msg.To.Add(textBox_To.Text);
    msg.From = new MailAddress("[email protected]");
    msg.Subject = textBox_Subject.Text;
    msg.Body = textBox_Message.Text;
    Attachment data = new Attachment(textBox_Attachment.Text);
    msg.Attachments.Add(data);
    client.Send(msg);
    MessageBox.Show("Successfully Sent Message.");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

But the problem is that, Google is not allowing this approach.
When I'm opening my gmail account, I get a ‘Suspicious sign in prevented’ email.

Any other approach?


Solution

  • That's google's security feature. To workaround it, google gives you two options

    Change account access for less secure apps

    To help keep Google Apps users' accounts secure, we may block less secure apps from accessing Google Apps accounts. As a Google Apps user, you will see a "Password incorrect" error when trying to sign in. If this is the case, you have two options:

    • Option 1: Upgrade to a more secure app that uses the most up to date security measures. All Google products, like Gmail, use the latest security measures.
    • Option 2: Change your settings to allow less secure apps to access your account. We don't recommend this option because it might make it easier for someone to break into your account. If you want to allow access anyway, follow these steps:
      1. Go to the "Less secure apps" section in My Account.
      2. Next to "Access for less secureapps," select Turn on. (Note to Google Apps users: This setting is hidden if your administrator has locked less secure app account access.)

    Link: https://support.google.com/accounts/answer/6010255?hl=en