Cantinos
Cantinos

Reputation: 282

gmail-api .net How to MVC website send email without logging in

I try to use google gmail-api on a .NET MVC5 website on azure. I bought a gmail suite account and would like that my websites send email through gmail.

I followed more or less the tutorial and the code below is the result of my exploration. It's work but... a google authentification windows open each time. It's look like the ClientId and ClientSecret are not enough.

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = "xxxxxxxx.apps.googleusercontent.com",
                    ClientSecret = "xxxxxx"
                },
                new[] { GmailService.Scope.GmailModify },
                _defaultSender,
                CancellationToken.None);

            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "MyProjet"
            });

            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body = html,
                ContentType = "text/html",
                From = new MailAddress(_defaultSender)
            };

            foreach (var recipient in recipients)
            {
                msg.To.Add(new MailAddress(recipient));
            }
            var msgStr = new StringWriter();
            msg.Save(msgStr);

            await service.Users.Messages.Send(new Message()
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").ExecuteAsync();

The google tutorial wrote:

The sample will attempt to open a new window or tab in your default browser. If this fails, copy the URL from the console and manually open it in your browser.

There isn't any other way? A website service account can not send contact/loggin/etc emails via gmail? The other stacks show that it may seem that way: Sending email in .NET through Gmail or How to send an email in .Net according to new security policies?

Upvotes: 1

Views: 1547

Answers (1)

Cantinos
Cantinos

Reputation: 282

Brendan Green put me in the right direction. I confuse gmail impersonation account (where the tutorial leads) and using a service account for the send as a predefine email.

Here a code sample that works a MVC5 WebApp on Azure. Goodbye sendgrid! Hello GMAIL!

var serviceAccountEmail = "[email protected]";
            var certificate = new X509Certificate2(Resources.Gmail.Certificat,//the google .p12 file stored as resource
                "notasecret",
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

            var credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    User = "[email protected]",
                    Scopes = new[] { "https://mail.google.com/" }
                }.FromCertificate(certificate)
            );

            // Create the service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "ProjectName"
            });

            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body = html,
                ContentType = "text/html",
                From = new MailAddress(_defaultSender)
            };

            foreach (var recipient in recipients)
            {
                msg.To.Add(new MailAddress(recipient));
            }
            var msgStr = new StringWriter();
            msg.Save(msgStr);

            await service.Users.Messages.Send(new Message()
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").ExecuteAsync();

Upvotes: 2

Related Questions