Can't send email using Google SMTP server using my custom email address

192 Views Asked by At

I have a google account using my own custom email address ([email protected]) and turned on 2-step verification and created an app password. When I try to use that email address and app password to send an email in c# using MailKit, I get "535: 5.7.8 Username and Password not accepted."

So I created another google account ([email protected]) and created an app password and using the same code, the email sends successufully.

However, the "from" email is [email protected] and I want to send from [email protected]. How could I get my email to send successfully from my custom email google account, or send it from the other account, but from my custom email address?

            var email = new MimeMessage();
            email.From.Add(new MailboxAddress(_mailSettings.DisplayName, _mailSettings.Email));
            email.To.Add(MailboxAddress.Parse(toEmail));
            email.Subject = subject;
            var builder = new BodyBuilder();
            builder.HtmlBody = body;
            email.Body = builder.ToMessageBody();
            using var smtp = new SmtpClient();
            smtp.Connect("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
            smtp.Authenticate("[email protected]", "xxxx xxxx xxxx xxxx");
            await smtp.SendAsync(email);
            smtp.Disconnect(true);
            return "Email has been sent successfully.";
2

There are 2 best solutions below

0
Ansh Agarwal On

As far as I'm aware, you would have to sign in using your [email protected] account. Perhaps by disabling 2fa? I did find this link about google disabling less secure access, which used to be mandatory to use a custom smtp script. https://support.google.com/accounts/answer/6010255?hl=en

0
Primico On

So, I believe in the [email protected] account you need to go to "Accounts and Import" and add a reply email and enter the SMTP credentials of you custom domain. Since my [email protected] email was hosted at AWS, I ended up using AWS SES to send the emails. Although I believe by just adding that reply email, it would have worked fine with Google also. The only issue I had in AWS SES is the emails would always go to spam, even though the email was verified. It turns out I had to set up DomainKeys Identified Mail (DKIM) for the domain and then all emails ended up in the inbox successfully.