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: