Search code examples
c#.netgoogle-apigoogle-oauthgmail-api

can I make google API that send email just from my email


Hi I am trying to make c# application that send email from my email to verity of users I want the program to send email just from my account do I have to make the full process of makeing the api that send email from a deferent users or there is a way to make a connection with just my email


Solution

  • First off if you have a google workspace account. Then you could use a service account with domain wide deligation and delgate to a user on your domain. Then when you run your app it will be like that user is sending the emails. For example create a noreply user on the domain and jsut send emails from them.

    string ApplicationName = "Gmail API .NET Quickstart";
                const string serviceAccount = "clawskeyboard-smtp@clawskeyboard-api.iam.gserviceaccount.com";
    
                var certificate = new X509Certificate2(@"D:\Creds.p12", "notasecret", X509KeyStorageFlags.Exportable);
    
                var gsuiteUser = "noreply@yourdomain.com";
    
                var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
                {
                    User = gsuiteUser,
                    Scopes = new[] { GmailService.Scope.Gmail }
    
                }.FromCertificate(certificate);
    

    If this is a standard gmail account as i suspect then things will be much harder. First off you will need to set up oauth2 and authorize your app as yourself. This can be done easy enough.

     UserCredential credential;
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/Creds.json");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.FromStream(stream).Secrets, Scopes, "user", CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            }
            return credential;
    

    Just remember to watch it though if the refresh token ever expires you will need to authorize it again.