【问题标题】:Error sending gmail using Google API使用 Google API 发送 gmail 时出错
【发布时间】:2023-03-14 19:39:02
【问题描述】:

我使用以下代码通过 Google API 向 gmail 发送电子邮件:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.Net.Mail;
using MimeKit;
using System.Configuration;


  class Program
    {
        static string credPath;
        static string credPath1;
        static string[] Scopes =
        {          
            GmailService.Scope.GmailModify,                      
            "https://www.googleapis.com/auth/gmail.compose",
            "https://www.googleapis.com/auth/gmail.send",
            "https://www.googleapis.com/auth/userinfo.email"             
        };      

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Please Enter Your Mail Id");
                string usr = Console.ReadLine();
                UserCredential credential;
                using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.ReadWrite))
                {
                    credPath =System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, "credentials/gmail-dotnet-quickstart.json");            
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync
                        (
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "me",
                        CancellationToken.None,
                        new FileDataStore((credPath), false)
                        ).Result;

                }
                var gmail = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential                    
                });


                var message = new MimeMessage();
            message.From.Add(new MailboxAddress("Saikam Nagababu", usr));
            message.To.Add(new MailboxAddress("Saikam Nagababu", "tomailid@gmail.com"));
            message.Subject = "How you doin?";
            message.Body = new TextPart("plain")
            {
                Text = @"Hey Alice"
            };


            var rawMessage = "";
            using (var stream = new MemoryStream())
            {

                message.WriteTo(stream);
                rawMessage = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length)
                    .Replace('+', '-')
                    .Replace('/', '_')
                    .Replace("=", "");
            }
            var gmailMessage = new Google.Apis.Gmail.v1.Data.Message { Raw = rawMessage };

            Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = gmail.Users.Messages.Send(gmailMessage, usr);
          request.Execute();
            }
            catch(Exception e)
            {

                throw e;

            }
        }

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

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

我收到以下错误:

发生 Google.GoogleApiException
H结果=-2146233088
Message=发生错误,但无法反序列化错误响应
来源=Google.Apis
服务名称=gmail
堆栈跟踪:
在 Google.Apis.Services.BaseClientService.d__34.MoveNext()
内部异常:Newtonsoft.Json.JsonReaderException
H结果=-2146233088
消息=解析值时遇到意外字符:d__34.MoveNext()
内部异常:

【问题讨论】:

  • 错误表示无法反序列化响应,您需要弄清楚返回的内容,可能使用 Fiddler 之类的东西。
  • @DavidG 请建议我需要反序列化的内容。(例如:gmail 服务对象)如何使用 Fiddler 进行反序列化
  • 我不知道您收到的回复是什么,这取决于您自己想办法。我建议使用 Fiddler 作为代理来查看您和 Google 之间的 HTTP 请求。
  • @Nagababu 代码中的哪一行引发了该错误?
  • @TrungDuong 我收到错误:request.Execute();

标签: c# google-api gmail-api


【解决方案1】:

我认为您收到错误消息是因为您在代码中创建的 gmail 邮件格式无效。

在您的代码中,您尝试将 System.Net.Mail.MailMessage 转换为原始文本。但是当您在 MailMessage 对象上调用 ToString 时,它只返回一个表示对象实例的字符串,而不是它的内容。

var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
                {  Raw = Encode(mailMessage.ToString())
                };

要将System.Net.Mail.MailMessage 转换为原始文本,您可以参考此链接Convert MailMessage to Raw

我没有尝试将 System.Net.Mail.MailMessage 转换为 Gmail。但我体验过将 MimeKit.MimeMessage 转换为 Gmail

首先,您创建MimeMessage

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice@wonderland.com"));
message.Subject = "How you doin?";
message.Body = new TextPart ("plain") {
    Text = @"Hey Alice"
};

然后使用以下代码将其转换为 Gmail

var rawMessage = "";
using (var stream = new MemoryStream ()) {

    message.WriteTo (stream);
    rawMessage = Convert.ToBase64String (stream.GetBuffer (), 0, (int) stream.Length)
        .Replace ('+', '-')
        .Replace ('/', '_')
        .Replace ("=", "");
}
var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
                {  Raw = rawMessage };

希望对您有所帮助。

【讨论】:

  • 它不工作..我得到同样的错误..请建议我
  • 你使用的是哪种方法,MimeMessage 还是 System.Net.Mail.MailMessage?
  • 你建议我使用什么方法 MimeMessage()。
  • 您正在使用 MimeMessage 并且仍然出现错误,不是吗?正如我在您的问题中看到的,您的消息是 html 内容。因此,您应该创建 HTML MimeMessage,而不是创建纯文本 MimeMessage。您可以查看此链接以了解如何创建 HTML stackoverflow.com/questions/41160536/…
  • 你提到的我复制粘贴并执行(我发送纯文本),但不工作......
【解决方案2】:

我解决了在以下示例中重新生成令牌 var "NewTOKEN_NAME" 的问题:

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(NewTOKEN_NAME, true)).Result;

【讨论】:

    猜你喜欢
    • 2014-09-24
    • 2021-02-24
    • 2018-04-11
    • 2017-04-14
    • 1970-01-01
    • 2015-03-08
    • 2011-06-20
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多