Sending attachment in laravel mail

2019-08-20 06:52发布

问题:

everyone. I am trying to send email with attachment on it. What I have done is :

   controller code snippet:

     try{
           Mail::send(['name' => 'By System'],array(), function($msg) use ($email,$name,$message,$attachment,$ext,$display) {
                        $msg->from('ricket999@gmail.com', 'Markle Admin');
                        $msg->to($email)->subject('Payment Done')
                            ->setBody('This is to notify you that the employee named '.$name.' has been paid for the monthly payment. Thank You.','text/html')
                            ->attach(public_path().'/'.$attachment, ['as' => $display.'.'.$ext, 'mime' => 'application/pdf']);  });
        }
    catch(Exception $e){
             // if any error mark the mail sent status 0
             $result = DB::table('message')->where('name',$name)->where('email',$email)->update(['sent'=>'0']); 
            }

But it is showing this error :

    Type error: Argument 1 passed to Swift_Mime_SimpleMessage::attach() must implement interface Swift_Mime_MimeEntity, string given, called in E:\xampp\htdocs\email-send\app\Http\Controllers\HomeController.php on line 133

What have I missed. I saw this and this but it is same as mine and they say its working but why am I getting this error. Any kind of help are appreciated. Thank you.

回答1:

You have 2 problems:

  1. You are trying to attach a zip archive while you have set the mime as application/pdf

  2. The path to your archive is wrong. Instead of E:\\xampp\\htdocs\\email-send\\public\\files\\1520764563.zip it is E:\\xampp\\htdocs\\email-send\\public/files/1520764563.zip

Regarding the Argument 1 passed to Swift_Mime_SimpleMessage::attach() must implement interface Swift_Mime_MimeEntity, string given error I suppose that this solves your problem:

    $swiftAttachment = Swift_Attachment::fromPath($correctPath); 
    $this->email->attach($swiftAttachment); // now attach the correct type