Google Gmail API错误C#.net“failedPrecondition”

时间:2017-10-31 23:06:06

标签: c# asp.net gmail-api

当我从编码生成Raw(下面)并将其放入https://developers.google.com/apis-explorer/?hl=en_GB#p/gmail/v1/gmail.users.messages.send时,它可以与主电子邮件一起使用,但不能与委托一起使用。

有没有办法将代理用户/服务帐户映射到gmail以发送电子邮件?

    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);
        }
    }

0 个答案:

没有答案