3

I need help with sending email w/attachment using Gmail Api in c#.

I have read Google website on sending emails with attachment but the example is in java.

MongMong
  • 33
  • 1
  • 1
  • 6

4 Answers4

9

Its too late for the answer, but posting it in case anyone needs it:)

Need MimeKit library for this: can be installed from NuGet.

enter image description here

Code:

public void SendHTMLmessage()
{
    //Create Message
    MailMessage mail = new MailMessage();
    mail.Subject = "Subject!";
    mail.Body = "This is <b><i>body</i></b> of message";
    mail.From = new MailAddress("fromemailaddress@gmail.com");
    mail.IsBodyHtml = true;
    string attImg = "C:\\Documents\\Images\\Tulips.jpg OR Any Path to attachment";
    mail.Attachments.Add(new Attachment(attImg));
    mail.To.Add(new MailAddress("toemailaddress.com.au"));
    MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);

    Message message = new Message();
    message.Raw = Base64UrlEncode(mimeMessage.ToString());
    //Gmail API credentials
    UserCredential credential;
    using (var stream =
        new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);
        credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scope,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }

    // Create Gmail API service.
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });
    //Send Email
    var result = service.Users.Messages.Send(message, "me/OR UserId/EmailAddress").Execute();
}

Scope can be:

GmailSend or GmailModify

static string[] Scope = { GmailService.Scope.GmailSend };
static string[] Scope = { GmailService.Scope.GmailModify };

Base64UrlEncode function:

private string Base64UrlEncode(string input)
{
    var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
    return Convert.ToBase64String(inputBytes)
      .Replace('+', '-')
      .Replace('/', '_')
      .Replace("=", "");
}
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Preet
  • 984
  • 2
  • 14
  • 34
1

I have an example in VB.net. GMail API Emails Bouncing.

Google page provides examples in Java and Python only. The objects being used in the Java example are not available in .Net version of API. It is not possible to translate those examples.

Fortunately, it is quite easy to do the same in C#/VB. Just use plain old Net.Mail.MailMessage to create a message including attachments, then use MimeKit (NuGet it) to convert the message into string and pass the string (after encoding Base64) to "Raw" field of message.send of Gmail API.

Community
  • 1
  • 1
Allen King
  • 2,372
  • 4
  • 34
  • 52
0

There's nothing particular to sending an attachment with the Gmail API. Either way the Gmail API message.send() takes a full RFC822 email message in the message.raw field (urlsafe base64 encoded). The main trick is building up such an RFC822 email message string in your language. I imagine there are some MIME message librarys in C# and that's the main issue is finding those libraries. I don't do C# but javax.internet.mail.MimeMessage works well in java and the 'email' module is good for python.

This other post seems relevant: How to send multi-part MIME messages in c#?

Community
  • 1
  • 1
Eric D
  • 6,901
  • 1
  • 15
  • 26
0
    string[] Scopes = { GmailService.Scope.GmailSend };
    string ApplicationName = "Gmail API App";

    public GmailForm()
    {
        InitializeComponent();
    SendHTMLmessage();
    }

    string Base64UrlEncode(string input)
    {
        var data = Encoding.UTF8.GetBytes(input);
        return Convert.ToBase64String(data).Replace("+", "-").Replace("/", "_").Replace("=", "");
    }

    public void SendHTMLmessage()
    {
        //Create Message
        MailMessage mail = new MailMessage();
        mail.Subject = "Subject!";
        mail.Body = "This is <b><i>body</i></b> of message";
        mail.From = new MailAddress("youremail@gmail.com");
        mail.IsBodyHtml = true;
        string attImg = "C:\\attachment.pdf";
        mail.Attachments.Add(new Attachment(attImg));
        mail.To.Add(new MailAddress("receiver@mail.com"));
        MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);

        var msg = new Google.Apis.Gmail.v1.Data.Message();
        msg.Raw = Base64UrlEncode(mimeMessage.ToString());
        //Gmail API credentials
        UserCredential credential;

        using (var stream =new FileStream(Application.StartupPath + @"/credentials.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,Scopes,"user",CancellationToken.None,new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Gmail API service.
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        
        //Send Email
        var result = service.Users.Messages.Send(msg, "me").Execute();
        MessageBox.Show("Your email has been successfully sent !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Chris May 24 '22 at 17:28