user1002973 user1002973 - 1 month ago 63
C# Question

How to create a Gmail API Message

I'd like to send a Message using Google's Gmail API. I've authenticated successfully, and am trying to use GmailService to send a message.

I'd like to use this:

myService.Users.Messages.Send(myMessage, "me").Execute();


where myService is a
Google.Apis.Gmail.v1.GmailService
and myMessage is a
Google.Apis.Gmail.v1.Data.Message
.

myService
is fine, I've done the OAuth dance. I can get messages from my Inbox and all that. But I don't know how to construct
myMessage
. I have a standard .NET
MailMessage
, with human-readable Subject, Body, To, From etc.

But the Google
Message
class takes fields
Payload
or
Raw
. What's the easiest way to convert a full
MailMessage
to a string which I can set to the
Payload
or
Raw
properties? Or is this not what I should be doing at all?

The documentation for the Message class.

Answer

I found a solution. Strangely, .NET doesn't seem to support this natively/easily. There's a nice nuget package though, called AE.Net.Mail, which can write an easy-to-create message object to a stream.

Here's the sample code that pointed me in that direction.

Copy-and-pasted code as site seems to be down, and Google's cache might not last forever:

using System.IO;
using System.Net.Mail;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

public class TestEmail {

  public void SendIt() {
    var msg = new AE.Net.Mail.MailMessage {
      Subject = "Your Subject",
      Body = "Hello, World, from Gmail API!",
      From = new MailAddress("[you]@gmail.com")
    };
    msg.To.Add(new MailAddress("yourbuddy@gmail.com"));
    msg.ReplyTo.Add(msg.From); // Bounces without this!!
    var msgStr = new StringWriter();
    msg.Save(msgStr);

    var gmail = new GmailService(Context.GoogleOAuthInitializer);
    var result = gmail.Users.Messages.Send(new Message {
      Raw = Base64UrlEncode(msgStr.ToString())
    }, "me").Execute();
    Console.WriteLine("Message ID {0} sent.", result.Id);
  }

  private static string Base64UrlEncode(string input) {
    var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
    // Special "url-safe" base64 encode.
    return Convert.ToBase64String(inputBytes)
      .Replace('+', '-')
      .Replace('/', '_')
      .Replace("=", "");
  }
}
Comments