muttley91
muttley91

Reputation: 12674

Creating a Message for Gmail API in C#

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 existing sample change over?

Sample found here.

Upvotes: 13

Views: 23141

Answers (3)

Xtros
Xtros

Reputation: 467

Here is what I was able to get working, using MimeKit.

public void SendEmail(MyInternalSystemEmailMessage email)
{
    var mailMessage = new System.Net.Mail.MailMessage();
    mailMessage.From = new System.Net.Mail.MailAddress(email.FromAddress);
    mailMessage.To.Add(email.ToRecipients);
    mailMessage.ReplyToList.Add(email.FromAddress);
    mailMessage.Subject = email.Subject;
    mailMessage.Body = email.Body;
    mailMessage.IsBodyHtml = email.IsHtml;

    foreach (System.Net.Mail.Attachment attachment in email.Attachments)
    {
        mailMessage.Attachments.Add(attachment);
    }

    var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

    var gmailMessage = new Google.Apis.Gmail.v1.Data.Message {
        Raw = Encode(mimeMessage)
    };

    Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, ServiceEmail);

    request.Execute();
}

public static string Encode(MimeMessage mimeMessage)
{
    using (MemoryStream ms = new MemoryStream())
    {
        mimeMessage.WriteTo(ms);
        return Convert.ToBase64String(ms.GetBuffer())
            .TrimEnd('=')
            .Replace('+', '-')
            .Replace('/', '_');
    }
}

}

Note: If you are getting an email bounce issue, it is likely due to not setting the ReplyToList field. See: GMail API Emails Bouncing

Upvotes: 22

pettys
pettys

Reputation: 2468

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("[email protected]"));
    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/

Upvotes: 7

Eric D
Eric D

Reputation: 7159

Seems like this isn't really an issue with the Gmail API. What you should be looking for is "c# create email" (potentially adding "RFC 2822" as that's the RFC that defines the format for these emails). Once you have such a valid "email message" (the real, entire email content you can use with SMTP or IMAP, etc) then using it with the Gmail API should be pretty trivial.

Upvotes: -1

Related Questions