LoginSignup
2
3

More than 5 years have passed since last update.

PHPMailerで,ファイルを手元に保存せずに文字列だけからファイル添付する

Last updated at Posted at 2017-07-16

PHPMailer

PHPMailer/PHPMailer: The classic email sending library for PHP

基本的な使い方はこちらをどうぞ。

注意

2016年12月に発覚したPHPMailerの脆弱性について↓
最新版を使うなど対策はご自身でm(_ _)m

addStringAttachment

できること・使い方

文字列を指定の形式のファイルとしてメールに添付する。

mail.php
<?php
require("PHPMailer/class.phpmailer.php");

$mailer = new PHPMailer();

// 前処理いろいろ。c.f. 上記参考リンク

$str  = '日付,メニュー,内容' . "\n";
$str .= '170716,日替わり定食A,焼き鮭' . "\n";
$str .= '170716,日替わり定食B,肉野菜炒め' . "\n";

$filename = '170716食堂通信.csv';

$mailer->addStringAttachment($str, $filename);

$mailer->send();

これでこういう感じのCSVファイル( 170716食堂通信.csv )が添付されます↓
サーバー側にファイルは残りません。

日付 メニュー 内容
170716 日替わり定食A 焼き魚
170716 日替わり定食B 肉野菜炒め

ファイルの形式は自分で別途指定もできますが,ファイル名の拡張子から勝手に判断してもらえるようです。
(ソースコード参照↓)

ソースコード

一部抜粋で

PHPMailer/class.phpmailer.php at master · PHPMailer/PHPMailer

PHPMailer/class.phpmailer.php
    /**
     * Add a string or binary attachment (non-filesystem).
     * This method can be used to attach ascii or binary data,
     * such as a BLOB record from a database.
     * @param string $string String attachment data.
     * @param string $filename Name of the attachment.
     * @param string $encoding File encoding (see $Encoding).
     * @param string $type File extension (MIME) type.
     * @param string $disposition Disposition to use
     * @return void
     */
    public function addStringAttachment(
        $string,
        $filename,
        $encoding = 'base64',
        $type = '',
        $disposition = 'attachment'
    ) {
        // If a MIME type is not specified, try to work it out from the file name
        if ($type == '') {
            $type = self::filenameToType($filename);
        }
        // Append to $attachment array
        $this->attachment[] = array(
            0 => $string,
            1 => $filename,
            2 => basename($filename),
            3 => $encoding,
            4 => $type,
            5 => true, // isStringAttachment
            6 => $disposition,
            7 => 0
        );
    }

シチュエーション

私がこれを使ったのは

  • DBから取得した情報をCSVファイルとして他部署の人にメールで送りたい
  • メール送信後,CSVファイルは別に使わない

↑という状況でした。
最初はこういう流れを考えていましたが↓

  1. DBから取得
  2. CSVファイルに取得結果を書き込み
  3. CSVファイル保存
  4. addAttachment($filepath)で添付・送信
  5. CSVファイル削除

わざわざこちらでCSVファイルを作ったり消したりしなくてもよかった,というお話でした。

「そもそもメールの添付ファイルってメーラーによって文字列に変換されて送信されるんだから,
ファイル作って添付ってステップ踏むと
文字列 → ファイル → メーラーがファイルを文字列に → 受取側が文字列をファイルに
ってしてるわけで最初のほう二度手間じゃん」と
先輩から指摘を受けてこちらを使ったという次第でした。たしかになー。

2
3
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
2
3