Search code examples
smtpgmailgoogle-workspace

SMTP is not sending emails in gmail business account


This code is working well in gmail personal account, but when I try to use gmail business account, it is not working and keeps giving an error. 5.5.1 Authentication Required.

void SendEmail()
{
    DataTable data = GetData();
    DataTable email_data = GetEmailData();
    data.TableName = "Employee_Data";

    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(data);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            String from = "[email protected]";

            for (int i = 0; i < email_data.Rows.Count; i++)
            {
                String to = email_data.Rows[i][0].ToString();

                using (MailMessage mm = new MailMessage(from, to))
                {
                    mm.Subject = "Employees Attachment";
                    mm.Body = "Employees Exported Attachment";

                    mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Employees.xlsx"));
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                    credentials.UserName = "[email protected]";
                    credentials.Password = "1234";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }
}

Solution

  • I solved this problem. The account should not use 2nd verification in gmail if you want to use SMTP.

    https://support.google.com/accounts/answer/1064203?hl=en&ref_topic=7189195

    I can't control those things, I ask the administrator allow not to use 2nd verification. So I can work with that account using SMTP.