Search code examples
c#.netgoogle-apigmail-apigoogle-api-dotnet-client

How to send emails from a .net core console application via Gmail API?


I've created a console application to send confirmation messages from a gmail account as a cron job, initially it used mailkit but it's no longer working so I added an apikey to a new project on google developers console, then added Google.Apis.Gmail.v1 to my project and I'm trying to use it, this is I have so far.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;

namespace sender
{
    class Program
    {
        static void Main(string[] args) {
            var gs = new GmailService(new BaseClientService.Initializer {
                    ApplicationName = "mi-app-sending-emails",
                    ApiKey = "AIzxxxx_E_xxxxxx-Hxxxxx"
                });
                Message b = new Message();
                b.Id = "sender@gmail.com";
                //code here
    
                gs.Users.Messages.Send(b, "customer@gmail.com");
         }
    }
}

It does not send any message and the documentation does not provide much information, can you please provide me some information about how to achieve this code to work?


Solution

  • First off you forgot execute.

    var result = gs.Users.Messages.Send(b, "customer@gmail.com").Execute();
    

    second API key wont work with the gmail api. Your going to need to be authorized

    private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
            {
                try
                {
                    if (string.IsNullOrEmpty(userName))
                        throw new ArgumentNullException("userName");
                    if (string.IsNullOrEmpty(clientSecretJson))
                        throw new ArgumentNullException("clientSecretJson");
                    if (!File.Exists(clientSecretJson))
                        throw new Exception("clientSecretJson file does not exist.");
    
                    // These are the scopes of permissions you need. It is best to request only what you need and not all of them               
                    using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
                    {
                        string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                        credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
    
                        // Requesting Authentication or loading previously stored authentication for userName
                        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                                 scopes,
                                                                                 userName,
                                                                                 CancellationToken.None,
                                                                                 new FileDataStore(credPath, true)).Result;
    
                        credential.GetAccessTokenForRequestAsync();
                        return credential;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Get user credentials failed.", ex);
                }
            }
    
    /// <summary>
        /// This method get a valid service
        /// </summary>
        /// <param name="credential">Authecated user credentail</param>
        /// <returns>GmailService used to make requests against the Gmail API</returns>
        private static GmailService GetService(UserCredential credential)
        {
            try
            {
                if (credential == null)
                    throw new ArgumentNullException("credential");
    
                // Create Gmail API service.
                return new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Gmail Oauth2 Authentication Sample"
                });
            }
            catch (Exception ex)
            {
                throw new Exception("Get Gmail service failed.", ex);
            }
        }
    }
    

    If you check the documentation for message.send you will notice it states you need to be authorized to access this method. API Keys only work with public endpoints not private endpoints

    enter image description here