Google関連

Gmail APIを使ってメール送信するC#コード

「たまには.NET用のライブラリを使ってGoogle APIでも触ってみるか!」と、ふと思い立ったので、Gmail APIを使ってメールを送信を行うコードを書いてみました。

クライアントIDとクライアントシークレット

Gmail APIを利用する際、クライアントIDとクライアントシークレットが必要になるため、下記記事を参考にして事前に準備しておきます。

Google.Apis.Gmail.v1 Client Library

Googleの開発者向けサイトを見ればわかる通り、.NET用のClient Libraryが用意されています。

Gmail APIの場合は上記ライブラリですね。
これを使えば承認からAPIの実行まで、短いコードで簡単に書くことができます。

Gmail APIを使ってメール送信するC#コード

ではいよいよコードです。
といっても、認証部分やAPIの実行に関しては、以前書いた下記記事とほぼ同じです。

問題なのはメール送信を行うsendメソッドの部分。

The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied.

https://developers.google.com/gmail/api/v1/reference/users/messages/send より

RFC 2822形式でメール本体を用意しなくてはならず、面倒くさそうだと思ったのですが、Stack Overflowに丁度良いサンプルがありました。

var msg = new AE.Net.Mail.MailMessage {
  Subject = "Your Subject",
  Body = "Hello, World, from Gmail API!",
  From = new MailAddress("[you]@gmail.com")
};

https://stackoverflow.com/questions/32787230/how-to-create-a-gmail-api-message より

なるほど。
AE.Net.Mailあたりを使えば簡単にメール作成できそうですね。

ただ、AE.Net.Mailは更新も止まっているので、今回はMimeKitを使うことにします。

というわけで、以下コード。

/*
 * Gmail APIを使ってメール送信するC#コード
 * @kinuasa
 * 
 * 要参照
 *  Google.Apis, Google.Apis.Auth, Google.Apis.Auth.PlatformServices,
 *  Google.Apis.Core, Google.Apis.Gmail.v1, Google.Apis.PlatformServices,
 *  MimeKit, Newtonsoft.Json(v10.0.3)
 * 
 * 参考URL
 *  https://developers.google.com/gmail/api/quickstart/dotnet
 *  https://developers.google.com/gmail/api/v1/reference/users/messages/send
 *  https://developers.google.com/api-client-library/dotnet/get_started
 *  https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth
 *  https://stackoverflow.com/questions/32787230/how-to-create-a-gmail-api-message
 *  https://qiita.com/masaha03/items/930f071518160cded818
 *  https://www.ka-net.org/blog/?p=7007
 */
using System;
using System.IO;
using System.Text;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using MimeKit;

namespace GmailApiv1Sample
{
  class Program
  {
    public static void Main(string[] args)
    {
      //認証情報
      string client_id = "(クライアントID)";
      string client_secret = "(クライアントシークレット)";
      string[] scopes = {GmailService.Scope.GmailSend};
      string app_name = "Google.Apis.Gmail.v1 Sample";
      
      //メール情報
      string mail_from_name = "差出人";
      string mail_from_address = "(差出人アドレス)";
      string mail_to_name = "宛先";
      string mail_to_address = "(宛先アドレス)";
      string mail_subject = "テストメール";
      string mail_body = @"テストメールを送信します。
受信確認できましたら、返信をお願いします。

テスト太郎";
      
      //認証
      UserCredential credential;
      string token_folder_path = Path.Combine(Path.GetTempPath(), "Google.Apis.Gmail.Token");
      credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
          ClientId = client_id,
          ClientSecret = client_secret
        },
        scopes,
        "user",
        CancellationToken.None,
        new FileDataStore(token_folder_path)
      ).Result;
      
      var service = new GmailService(new BaseClientService.Initializer()
      {
        ApplicationName = app_name,
        HttpClientInitializer = credential
      });
      
      //メール作成
      var mime_message = new MimeMessage();
      mime_message.From.Add(new MailboxAddress(mail_from_name, mail_from_address));
      mime_message.To.Add(new MailboxAddress(mail_to_name, mail_to_address));
      mime_message.Subject = mail_subject;
      var text_part = new TextPart(MimeKit.Text.TextFormat.Plain);
      text_part.SetText(Encoding.GetEncoding("iso-2022-jp"), mail_body);
      mime_message.Body = text_part;
      
      byte[] bytes = Encoding.UTF8.GetBytes(mime_message.ToString());
      string raw_message = Convert.ToBase64String(bytes)
        .Replace('+', '-')
        .Replace('/', '_')
        .Replace("=", "");
      
      //メール送信
      var result = service.Users.Messages.Send(
        new Message()
        {
          Raw = raw_message
        },
        "me"
      ).Execute();
      
      Console.WriteLine("Message ID: {0}", result.Id);
      Console.ReadKey(true);
    }
  }
}

必要最小限のコードしか書いていませんが、無事にメール送信確認できました。

やはり、専用のライブラリが用意されていると処理が楽になりますね!

2019年5月の人気記事前のページ

【アイカツフレンズ!】アイドルカード一覧次のページ

関連記事

  1. Office関連

    CDOを使ってGmail送信を行うVBAマクロ(UTF-8対応版)

    2年ほど前にCDOを使ってGmail送信を行うVBAマクロについて記事…

  2. Google関連

    [Google Apps Script]スプレッドシートで不要な空白文字を削除する

    スプレッドシートでは、「データ」メニューにある「空白文字を削除」を実行…

  3. Google関連

    Google Docs API v1を試してみました。

    下記TechCrunchの記事によると、Google ドキュメントの新…

  4. AppSheet

    AppSheetとGoogle Apps Scriptとの連携機能を試してみました。

    当ブログでも2年ほど前に取り上げたことがある(下記記事ご参照)「App…

  5. Google関連

    Google Apps ScriptでVoiceText Web APIを呼び出す。

    ・モヤさまのショウ君にいろいろ喋らせるVBAマクロ(1)//www…

  6. Google関連

    [Google Apps Script]OAuth認証(2.0)が必要なWeb APIを利用する。

    前回の記事ではGoogle Apps Scriptを使ってWebアプリ…

コメント

  • コメント (0)

  • トラックバックは利用できません。

  1. この記事へのコメントはありません。

Time limit is exhausted. Please reload CAPTCHA.

※本ページはプロモーションが含まれています。

Translate

最近の記事

アーカイブ

PAGE TOP