GMAIL API sending email with attachment in c#

2020-06-26 04:29发布

问题:

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.

回答1:

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#?



回答2:

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

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

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


回答3:

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.



标签: gmail-api