-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:
7
  • 2
    Error says the response can't be deserialised, you need to figure out what is being sent back, perhaps using something like Fiddler. Commented Feb 22, 2017 at 15:59
  • @DavidG please suggest me what i need to deserialised.(like :gmail service object )how to deserialised by using Fiddler Commented Feb 22, 2017 at 16:05
  • I don't know what the response you are getting says, that's up to you to figure out. I was suggesting using Fiddler as a proxy to see the HTTP requests going between you and Google. Commented Feb 22, 2017 at 16:07
  • @Nagababu Which line in your code raise that error? Commented Feb 22, 2017 at 16:09
  • @TrungDuong i got error at : request.Execute(); Commented Feb 22, 2017 at 16:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

19 Comments

it is not working ..i got same error..please suggest me
Which method are you using, MimeMessage or still System.Net.Mail.MailMessage?
what over method you suggest me MimeMessage().
You are using MimeMessage and still get error, isn't it? As I could see in your question, your message is a html content. So instead create plain text MimeMessage, you should create HTML MimeMessage. You could check this link for how to create a HTML stackoverflow.com/questions/41160536/…
what over your mention i copy paste and execute( i send plain text ) ,but not working...
|
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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.