Creating a Message for Gmail API in C#

muttley91 picture muttley91 · Jul 14, 2014 · Viewed 16.6k times · Source

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.

Answer

Xtros picture Xtros · Oct 3, 2016

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.ToString())
    };

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

    request.Execute();
}

public static string Encode(string text)
{
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);

    return System.Convert.ToBase64String(bytes)
        .Replace('+', '-')
        .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