0

When I take the Raw produced from encode(below) and put it in https://developers.google.com/apis-explorer/?hl=en_GB#p/gmail/v1/gmail.users.messages.send it works fine with main email but not with delegate.

is there a way to map delegate user/service account to a gmail for sending emails?

    public static bool SendEmail(string to, string subject, string body)
    {
        var mailService = AuthenticateServiceAccount(serviceAccountEmail, path, Scopes);

        var mailMessage = new System.Net.Mail.MailMessage();
        mailMessage.From = new System.Net.Mail.MailAddress(cID);
        mailMessage.To.Add(to);
        mailMessage.ReplyToList.Add(cID);
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.IsBodyHtml = true;

        var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

        var gmailMessage = new Message
        {
            Raw = Encode(mimeMessage.ToString())
        };


        Send(mailService, cID, gmailMessage);


        return true;
    }
    public static string Encode(string text)
    {
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);

        return System.Convert.ToBase64String(bytes)
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
    }

    public static Message Send(GmailService service, string userId, Message body)
    {
        try
        {
            // Initial validation.
            if (service == null)
                throw new ArgumentNullException("service");
            if (body == null)
                throw new ArgumentNullException("body");
            if (userId == null)
                throw new ArgumentNullException(userId);

            // Make the request.
            return service.Users.Messages.Send(body, userId).Execute();
        }
        catch (Exception ex)
        {
            throw new Exception("Request Send failed.", ex);
        }
    }
Mark
  • 1
  • 1
  • You have only one useful line of code in Send method `service.Users.Messages.Send(body, userId).Execute();` what if you put this code `SendMail` – Chetan Oct 31 '17 at 23:13
  • You may want to check this [related SO post](https://stackoverflow.com/a/39276047/5995040), you can follow this [document](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority) that the developer ID is whitelisted in the domain CPanel. Then read the line "Then, an administrator of the G Suite domain must complete the following steps:" to enable your service account. Hope this helps. – Mr.Rebot Nov 01 '17 at 16:54

0 Answers0