【发布时间】: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