Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Message for Gmail API in C#

Tags:

c#

gmail-api

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.

like image 962
muttley91 Avatar asked Jul 14 '14 02:07

muttley91


1 Answers

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

like image 107
Xtros Avatar answered Sep 20 '22 15:09

Xtros