I want to send an email with an attachment (pdf) that comes from a request. Without attachment. an email has sent perfectly but with attachment, it threw an error
Fatal error: Uncaught exception 'Swift_IoException' with message 'The path cannot be empty'
here is my mail class
class MyMail extends Mailable {
use Queueable, SerializesModels;
public $details;
public function __construct($details =[]) {
$this->details = $details;
}
public function build() {
if ($this->details['file']) {
return $this->subject('New applicant')
->from("my@email.com", "name")
->view('email.mail')
->attach($this->details['file']->getRealPath(),
[
'as' => $this->details['file']->getClientOriginalName(),
'mime' => $this->details['file']->getClientMimeType(),
]);
}
}
}
Here is my controller code
$file = $request->file('file ');
if ($file) {
$file_name = hexdec(uniqid());
$ext = strtolower($file->getClientOriginalExtension());
$file_full_name = $file_name . '.' . $ext;
$upload_path = 'files/';
$upload_path1 = 'backend/files/';
$file_url = $upload_path . $file_full_name;
$success = $file->move($upload_path1, $file_full_name);
}
$details = [
'applicant_name' => $request->name,
'applicant_contact' => $request->contact,
'applicant_email' => $request->email,
'file' => $file,
];
$base_email = 'example@email.com';
Mail::to($base_email)->send(new MyMail($details));
Can anyone help me with how can I send an email with an attachment?
You are attaching directly from request.But you should upload your iamge to storage or public folder.Then you can attach path of image
$details = [
'applicant_name' => $request->name,
'applicant_contact' => $request->contact,
'applicant_email' => $request->email,
'file' => $file,
'fileUrl' => $file_url,
];
$this->subject('New applicant')
->from("my@email.com", "name")
->view('email.mail')
->attach(asset( $this->details['fileUrl']),
[
'as' => $this->details['file']->getClientOriginalName(),
'mime' => $this->details['file']->getClientMimeType(),
]);
in my controller i uploaded the file and send it to mail class like this:
if ($request->has('resume')) {
$file = $request->file('resume');
$file_name = Str::random(7) . '.'.$file->getClientOriginalExtension();
$destinationPath = "/followUp";
$file->move(public_path($destinationPath), $file_name);
$file = 'followUp/'.$file_name;
}
$subject = 'پیگیری رزومه - ایندید';
Mail::to('visanewcom@gmail.com')->send(new sendMail($username,$mobile,$subject,$file));
and then in send mail class:
return $this->view('email.followUp')
->with('username',$this->username)
->with('mobile',$this->mobile)
->with('file',$this->file)
->subject($this->subject)
->attach(public_path($this->file), [
'as' => 'resume.pdf',
'mime' => 'application/pdf',
])
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.