如何用phpmailer在yii framweek中发送附件?

gpnt7bae  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(118)

我正在使用Yii framwework和phpmailer发送邮件给特定的用户。我的邮件功能工作正常,但我卡在附件部分,因为我是从一个功能生成pdf。
生成pdf数据的功能在此处是动态的:

public function generatePdf()
{
   $html = '';
   $html .= '<div></div>'; //and same like this all html part.
   echo $html;
  //mpdf stuff will come here.
      $mpdf->WriteHTML($stylesheet,1);  //             
      $mpdf->WriteHTML($html,2); 
      $mpdf->Output($path.$file_name, "F");
}

这个功能可以正常的生成PDF文件。但是现在我想用这个功能来发送邮件附件。我不知道如何实现这个功能。请帮助我。
我正在使用另一个功能发送邮件:

public function sentMail(){
   $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
    $mail->SMTPAutoTLS = false;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;

    $mail->Username = GUSER;  
    $mail->Password = GPWD;           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress($to);
    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }  // demo code
}

如何在我的sentMail()中使用generatePdf函数作为附件。

dgjrabp2

dgjrabp21#

public function generatePdf()
{
   $html = '';
   $html .= '<div></div>'; //and same like this all html part.
   echo $html;
  //mpdf stuff will come here.
      $mpdf->WriteHTML($stylesheet,1);  //             
      $mpdf->WriteHTML($html,2); 
      $mpdf->Output($path.$file_name, "F");
      return $path.$file_name;
}

public function sentMail(){
    $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
    $mail->SMTPAutoTLS = false;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;    
    $mail->Username = GUSER;  
    $mail->Password = GPWD;           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress($to);
    //If you know path then use this
    #$mail->addAttachment("uploads/".$file_name); //Here add the proper path

    //If you want to attach the use below, 
    //If you write this in single class then call with $this->generatePdf()
    $mail->addAttachment(generatePdf());

    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }  // demo code
}

相关问题