-1

I use the following code for sending emails to gmail by using Google API:

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", "[email protected]"));
            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("=", "");
        }      
    }

I get the following error:

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:
Nagababu
  • 1
  • 4

2 Answers2

2

I think you got the error because the gmail message that you create in your code have invalid format.

In your code, you try to convert System.Net.Mail.MailMessage to raw text. But when you call ToString on MailMessage object, it just returns a string that represents the object instance, not its content.

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

To convert System.Net.Mail.MailMessage to raw text, you could reference this link Convert MailMessage to Raw.

I've not tried to convert System.Net.Mail.MailMessage to Gmail. But I've experienced converting MimeKit.MimeMessage to Gmail.

First, you create the MimeMessage

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "[email protected]"));
message.To.Add (new MailboxAddress ("Alice", "[email protected]"));
message.Subject = "How you doin?";
message.Body = new TextPart ("plain") {
    Text = @"Hey Alice"
};

Then convert it to Gmail using the following codes

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

Hope it could help.

Community
  • 1
  • 1
Trung Duong
  • 3,475
  • 2
  • 8
  • 9
0

I resolved the issue regenerating the token, var "NewTOKEN_NAME" in the following example:

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