yano3nora
7/2/2017 - 8:09 AM

[php: PHPMailer sample] php library "PHPMailer" sample. #php

[php: PHPMailer sample] php library "PHPMailer" sample. #php

<?php

/**
 * PHPMailer
 * @see [PHPで日本語メールを送信する](https://qiita.com/kidatti/items/16b9fa22399d6db7bcff)
 * @see [AuthType with PHPMailer #1224](https://github.com/PHPMailer/PHPMailer/issues/1224)
 */

// Set php language & encoding.
mb_language('japanese');
mb_internal_encoding('UTF-8');

// Load PHPMailer.
require 'PHPMailer/PHPMailerAutoload.php';

// New PHPMailer.
$mail = new PHPMailer();

if (MAIL_SMTP) {
  $mail->isSMTP();
  $mail->SMTPDebug  = 2;
  $mail->Host       = 'smtp.gmail.com';
  $mail->SMTPAuth   = true;
  // $mail->AuthType   = 'LOGIN';  // Using simple authentication via port 25.
  $mail->Port       = 465;
  $mail->Username   = 'your-gmail-address@gmail.com';
  $mail->Password   = 'your-password';
  $mail->SMTPSecure = 'ssl';
}


// Set Encoding.
if (MAIL_ENCODING != 'UTF-8') {
  // ISO-2022-JP
  $mail->CharSet  = 'iso-2022-jp';
  $mail->Encoding = '7bit';
}

// Set From.
$mail->From     = 'no-reply@example.com';
$mail->FromName = mb_encode_mimeheader(mb_convert_encoding($mailFromName, 'JIS', 'UTF-8'));

// Set To.
foreach ($mailAddresses as $mailTo) $mail->AddAddress($mailTo);

// Set Reply-to.
$mail->addReplyTo($mailReplyTo, 'Reply');

// Set CC & BCC.
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

// Set Subject.
$mail->Subject = mb_encode_mimeheader(mb_convert_encoding($mailSubject, 'JIS', 'UTF-8'));

// Set Attachments.
foreach ($mailAttachments as $attachmentPath) $mail->addAttachment($attachmentPath);

// Set Body.
if (MAIL_IS_HTML) {
  $mail->isHTML(true);
  $mail->Body    = mb_convert_encoding($mailHtmlAsBody, 'JIS', 'UTF-8');
  $mail->AltBody = mb_convert_encoding($mailBody, 'JIS', 'UTF-8');
} else {
  $mail->isHTML(false);
  $mail->Body = mb_convert_encoding($mailBody, 'JIS', 'UTF-8');
}

// Send mail.
if (!$mail->Send()) {
  throw new \Exception($mail->ErrorInfo);
}