Creating a Message for Gmail API in C#

前端 未结 3 1629
离开以前
离开以前 2020-12-16 16:31

I\'m looking at using the Gmail API in an application I\'m working on. However, I\'m not sure how to change their Java or Python examples over to C#. How exactly does the ex

3条回答
  •  -上瘾入骨i
    2020-12-16 16:57

    This was a tricky problem to solve, but I did end up getting it. I used the NuGet package AE.Net.Mail to get the RFC 2822 bit.

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

    Same code with a little further analysis and reasons are posted here: http://jason.pettys.name/2014/10/27/sending-email-with-the-gmail-api-in-net-c/

提交回复
热议问题