使用Google API发送Gmail时出错

时间:2017-02-22 15:57:13

标签: c# google-api gmail-api

我使用以下代码通过 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 occurred
HResult=-2146233088
Message=An Error occurred, but the error response could not be deserialized
Source=Google.Apis
ServiceName=gmail
StackTrace:
at Google.Apis.Services.BaseClientService.<DeserializeError>d__34.MoveNext()
InnerException: Newtonsoft.Json.JsonReaderException
HResult=-2146233088
Message=Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonTextReader.ReadInternal()
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReaderreader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReaderreader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader,Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(Stringvalue, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value,JsonSerializerSettings settings)
at Google.Apis.Json.NewtonsoftJsonSerializer.Deserialize[T](String input)
at Google.Apis.Services.BaseClientService.<DeserializeError>d__34.MoveNext()
InnerException:

2 个答案:

答案 0 :(得分: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 };

希望它可以提供帮助。

答案 1 :(得分:0)

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

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