PHPMailer 附件 寄多個MAIL 函式範例

最近專案常常用到,所以寫了個簡單的小函式 把寄檔案附件及 同時 CC 給多人的功能都寫進來。

if (!function_exists('class_sendMail')) {
  function class_sendMail($subject, $html, $user,$file='',$recipient=''){
    $recipient_ar = explode(',',$recipient);//以逗號分割
    $mail = new PHPMailer;
    $mail->isSMTP();// Set mailer to use SMTP
    $mail->Host = '';//您的 mail server 位置
    $mail->SMTPAuth = true;
    $mail->Username = '帳號';
    $mail->Password = '密碼';
    $mail->SMTPSecure = false;// Enable TLS encryption, `ssl` also accepted
    $mail->SMTPAutoTLS = false;
    $mail->CharSet = "UTF-8";
    $mail->Port = 25; // TCP port to connect to

    $mail->setFrom('寄件信箱', '寄件者');
    $mail->addAddress($user);// Add a recipient
    foreach($recipient_ar as $value){
      $mail->addAddress($value);// Add a recipient
    $mail->isHTML(true);// Set email format to HTML
      $mail->AddAttachment('檔案路徑'.$file); // 設定附件檔檔名 注意此範例 $file 只是檔名,若你檔案有分多層請連檔案路徑一同寫在 $file 並移除 '檔案路徑'. 字串

    $mail->Subject = $subject;
    $mail->Body    = $html;
    if(!$mail->send()) {return false;} else { return true;}


require_once "./plugins/PHPMailer/PHPMailerAutoload.php";
require_once "./plugins/PHPMailer/class.phpmailer.php";
require_once "./plugins/PHPMailer/class.smtp.php";

  $html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "">
	    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	    <title>信件標題 </title>
  $html .= '<p>信件內容</p>';
  $html .= '</body></html>';

  $user    ='收件者mail';
  $subject = '寄件標題';
  $from    = '寄件者mial';
  $headers = "Content-type: text/html; charset=utf-8\r\n" ."From: $from\r\n";
  $recipient=',,';//除了本來的收件者 還要寄給這些收件者時填,無請設為空字串

Leave a comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *