Search code examples
c#.net-coregoogle-apigmail-api

Gmail api with .net core - How to draft an email


I'm trying to integrate Google's Gmail API into my .Net Core (c#) console app. I have proof of concepts working using the Calendar, Docs, and Sheets API, but I'm stuck with how to draft an email with the Gmail API.

The only guide I could find uses Java (https://developers.google.com/gmail/api/guides/drafts), but I'm not sure how to translate the following section, specifically the Properties, Session, and MimeMessage types:

    // Encode as MIME message
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    email.setFrom(new InternetAddress(fromEmailAddress));
    email.addRecipient(javax.mail.Message.RecipientType.TO,
        new InternetAddress(toEmailAddress));
    email.setSubject(messageSubject);
    email.setText(bodyText);

I'm not wanting to send the email, I'm only wanting to create a draft that will appear in my Drafts folder. Here is what I have so far:

static void Main(string[] args){
    string[] gmailScopes = { GmailService.Scope.GmailCompose };
    var credential = GetCredentialsFromFile(gmailScopes);
    GmailService service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = APPLICATION_NAME
    });

    //*** create a MimeMessage??? ***
    string messageHtml = "This is a test<br/><h1>Hello, World</h1>";
    //string messageHtmlEncoded = Base64UrlEncoder.Encode(messageHtml);
    Draft draft = new Draft
    {
        Message = new Message
        {
            //Raw = messageHtmlEncoded
        }
    };
    
}
private GoogleCredential GetCredentialsFromFile(string[] scopes)
{
    GoogleCredential credential;
    using var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read);
    credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);
    return credential;
}

Any help in how to create a draft using the Google apis would greatly appreciated.

A side question, once I'm able to get this working, will the draft reside in the service account that is being used to authenticate or will it be in my drafts folder?

Thanks in advance.


Solution

  • It turns out that my problem was using a service account without a G Suite account. After I switched to OAUTH authentication, it worked great. I'll go ahead and show the main parts of my code in case it might help someone else.

    var secrets = GoogleClientSecrets.FromFile("client_secret_oath.json");
    var userCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
            secrets.Secrets,
            _Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore("token_send.json", true)
    )
    .Result;
    
    var gmailService = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = userCredentials,
        ApplicationName = APPLICATION_NAME
    });
    
    string messageHtml = $"To: <email>@gmail.com\r\nSubject: Test Subject\r\nContent-Type: text/html;charset=utf-8\r\n\r\ntest body";
    string messageHtmlEncoded = Base64UrlEncoder.Encode(messageHtml);
    
    Draft draft = new Draft
    {
        Message = new Message
        {
            Raw = messageHtmlEncoded
        }
    };
    
    var createRequest = gmailService.Users.Drafts.Create(draft, "me");
    var draftResponse = createRequest.Execute();