Send mail via Google Apps Gmail using service account domain wide delegation in nodejs

后端 未结 2 1033
名媛妹妹
名媛妹妹 2020-12-02 02:13

I\'ve been reading tutorials and seeing examples for 2 days already, with no success. I want to send an email using Google Apps Gmail account in NodeJS environment, however,

2条回答
  •  长情又很酷
    2020-12-02 02:58

    Thanks very much @agoldis. Both the summary steps and the code were very helpful.

    It helped me pick up on a few things I needed to fix on both the GoogleWorkspace and the ApplicationCode end of the communication path. Below is my c# implementation for anyone who needs it.

    private static void Try4()
    {
      try {
         //file included in project with properties:  CopyToOutputDirectory = CopyAlways
         var credential = GoogleCredential.FromFile("MyPrj-MyServiceAccount-Credentials.json")       
                          .CreateScoped(new[] { GmailService.Scope.GmailSend })
                          .CreateWithUser("WhoIAmImpersonating@bla.com")
                          .UnderlyingCredential as ServiceAccountCredential;
    
         var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential });
    
         var nl = Environment.NewLine;
         string plainText =         "From:         WhoIAmImpersonating@bla.com" 
                             + nl + "To:           myfriend@gmail.com,"
                             + nl + "Subject:      This is the Subject" 
                             + nl + "Content-Type: text/html; charset=us-ascii" 
                             + nl 
                             + nl + "This is the message text.";
         var newMsg = new Message() { Raw = Base64UrlEncode(plainText) };
    
         service.Users.Messages.Send(newMsg, "WhoIAmImpersonating@bla.com").Execute();
         Console.WriteLine("Message Sent OK");
      }
      catch (Exception ex) {
          Console.WriteLine("Message failed");
      }
    }
    
    
    
    private static string Base64UrlEncode(string input)
    {
      var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
      return Convert.ToBase64String(inputBytes)
                    .Replace('+', '-')
                    .Replace('/', '_')
                    .Replace("=", "" );
    }
    

提交回复
热议问题