-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", "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("=", "");
        }      
    }

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

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
  • it is not working ..i got same error..please suggest me – Nagababu Feb 23 '17 at 07:07
  • Which method are you using, MimeMessage or still System.Net.Mail.MailMessage? – Trung Duong Feb 23 '17 at 07:14
  • what over method you suggest me MimeMessage(). – Nagababu Feb 23 '17 at 07:56
  • 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 http://stackoverflow.com/questions/41160536/how-to-send-html-message-via-mimekit-mailkit – Trung Duong Feb 23 '17 at 08:10
  • what over your mention i copy paste and execute( i send plain text ) ,but not working... – Nagababu Feb 23 '17 at 09:02
  • I have some doubts...shall i ask you..? – Nagababu Feb 23 '17 at 09:21
  • It's ok. You could ask me – Trung Duong Feb 23 '17 at 09:23
  • from mail address you pass two parameter first one is password and second one is mail id ..i am right? Ex: message.From.Add (new MailboxAddress ("Joey", "joey@friends.com")); – Nagababu Feb 23 '17 at 09:28
  • No, the first parameter is not password, it just a display name. I think if you could share your entire source code, I will try to figure out the problem. – Trung Duong Feb 23 '17 at 09:44
  • i was updated my code in above section..please suggest me – Nagababu Feb 23 '17 at 10:31
  • My Modified code is shared top of above section ..please help me – Nagababu Feb 23 '17 at 11:08
  • I've created a test program, copy your code and replace your credential information with mine and it working normallly. I think the problem may be in your gmail account setting. Did you follow the instructions at https://developers.google.com/gmail/api/quickstart/dotnet? – Trung Duong Feb 23 '17 at 11:26
  • i followed the same steps..please share your Client_screect file. – Nagababu Feb 23 '17 at 13:19
  • I've sent my credentials to email tomailid@gmail.com. But I think it could not help you much. If you use my credentials in your program, when you run the program, it will open a consent screen and you will be prompted to log in with my google account. Have you registered your application for Gmail API in Google API Console? – Trung Duong Feb 23 '17 at 14:41
  • yes..i registered ..my id: snagababusaikam@gmail.com...please share your credentials please.. – Nagababu Feb 23 '17 at 14:53
  • I've shared my credential https://drive.google.com/file/d/0B9kc0wx0qrxKNUltOEtuTVBuaDQ/view?usp=sharing Please check. – Trung Duong Feb 23 '17 at 14:56
  • its asking request access please share to my mail id: snagababusaikam@gmail.com – Nagababu Feb 23 '17 at 15:01
  • i check your credentials My credential also same data in Client_screect file..my code got error..but my code execute in your side perfectly...please suggest me.. – Nagababu Feb 23 '17 at 16:16
  • Could you send me your account information to email trungduong201608@gmail.com. I think I could help you check the setting of your account. – Trung Duong Feb 23 '17 at 16:30
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