LoginSignup
7
10

More than 5 years have passed since last update.

Gmail APIを使う時のBase64エンコード

Last updated at Posted at 2015-05-13

追記

パッケージ作って公開した

gmail_message_factory 0.0.1 | Pub Package Manager

こんなかんじで使える

import 'package:gmail_message_factory/gmail_message_factory.dart';

main() {
  var mf = new MessageFactory.UTF8("me", "to@example.com", "件名", "本文");
  var message = new Message();
  message.raw = mf.toRawMessage();
  api.users.messages.send(message, "me");
}

DartのWeb Appからgoogleapiを使ってGmail APIを叩いたけど日本語のメールを文字化けさせないようにするのに苦労した。

sendMail(GmailApi api) {
  var to = toInput.value;
  var subject = subjectInput.value;
  subject = CryptoUtils.bytesToBase64(UTF8.encode(subject));
  var text = textInput.value;

  var mail = "To: $to\n"
  "Subject: =?utf-8?B?$subject?=\n"
  "MIME-Version: 1.0\n"
  "Content-Type: text/plain; charset=${UTF8.name}\n"
  "Content-Transfer-Encoding: 7bit\n"
  "\n"
  "$text";
  mail = CryptoUtils.bytesToBase64(UTF8.encode(mail), urlSafe:true);
  var message = new Message();
  message.raw = mail;
  return api.users.messages.send(message, "me");
}

ポイントはヘッダ部分にはContent-Typeのエンコードは無効であるということ。

=?文字コード?符号方式?符号化された文字列?=という形式にすることでヘッダ部分にもUTF-8などのエンコードの文字列を使うことができる

Gmail APIのメール作成でAPIに渡すメールオブジェクトはUrl-SafeなBase64エンコードされた文字列である必要があるので、

CryptoUtils.bytesToBase64(UTF8.encode(subject));
CryptoUtils.bytesToBase64(UTF8.encode(mail), urlSafe:true);
でUTF8で書かれた文字列をBase64にする

7
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10