LoginSignup
0
0

Google Apps Script の MailApp.sendEmail 関数で、Web上の複数の写真を添付送信する

Last updated at Posted at 2023-12-28

Google Apps Script の MailApp.sendEmail 関数で、Web上の複数の写真を添付送信します。

▼各々の引数を設定し、sendEmail関数を呼び出します。

function callSendFunction() {
  var recipient = 'test@example.com', cc = '', bcc = '';
  var subject = '写真付きメール', msgBody = '写真付きメールです。';

  // 送信時のファイル名と画像URLを、2次元配列に設定する(ファイル名はnullか''で元のファイル名になる)
  var imageFiles = [
    [null, 'https://example/001.jpg'],
    ['002a', 'https://example/002.jpg'],
    ['', 'https://example/003.jpg'],
    ['004b', 'https://example/004.jpg'],
  ];
  //var imageFiles = null; // 添付写真がないとき
    
  sendEmail(recipient, cc, bcc, subject, msgBody, imageFiles);
}

sendEmail関数です。

function sendEmail(recipient, cc, bcc, subject, msgBody, imageFiles = []) {

  // 改行コードを変換する(テキスト形式修復)
  var subject = subject.replace(/<br>/g, ' ').replace(/\n/g, ' ');
  var body = msgBody.replace(/<br>/g, '\n');

  // 画像レスポンスを取得する
  var imageRes = [];
  for (var i=0; i < imageFiles.length; i++) {
    imageRes[i] = UrlFetchApp.fetch(imageFiles[i][1]);   
  }

  // imageFilesがあればファイルのデータ型を取得してファイル名を復元する
  var blobs = [], fileName = [], extension = [];
  for (var i=0; i < imageFiles.length; i++) {
    // ファイルのデータ型を取得する
    blobs[i] = imageRes[i].getBlob();
    
    // ファイル名を設定する
    fileName[i] = decodeURIComponent(blobs[i].getName()); // 元のファイル名(拡張子含む)
    if (imageFiles[i][0]!=null && imageFiles[i][0]!='') {
      extension[i] = fileName[i].match(/\.[^.]+$/)[0]; // 元の拡張子
      fileName[i] = imageFiles[i][0] + extension[i]; // 新しいファイル名(拡張子含む)
    }
    blobs[i] = blobs[i].setName(fileName[i]); // (拡張子含む)
  }

  // Email 送信する
  MailApp.sendEmail (
    recipient,
    subject,
    body, {
      cc: cc,
      bcc: bcc,
      attachments: blobs // データ型の配列を渡す
    }
  );
}
0
0
0

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
0
0