-1

im newbie using PHPmailer, I'm trying to send an email and everything is work fine if all input in form is filled.

but I can't send an email if attachment is empty. please help me how can I send an email without attachment or make the attachment is optional. here is my code : php

and this is my form form

thank u.

budi
  • 9
  • 1
  • 5

3 Answers3

1

Just do not write

$mail->addAttachment(...

if there is no file.

For example

if ($_FILES['attachemnt']['error'] == UPLOAD_ERR_OK) {
    $mail->addAttachment(...
}
Ivan Bolnikh
  • 742
  • 9
  • 19
1

Base on your question, more specifically

everything is work fine if all input in form is filled

You just need to remove check on attachment input field inside your JavaScript

If that is already handled, than I'll suggest to put a check if attachment file is present or not, inside sendemail function of your php file; if no, than do not add $mail->addAttachment like Ivan Bolnikh has suggested or use

if(isset($attachment))
    $mail->addAttachment($attachment);

Hope it helps!!!

Firoz Memon
  • 4,282
  • 3
  • 22
  • 32
0

If you do not pass any file and you call the function move_uploaded_file it returns false. So sendmail will not be called. You made the file upload addictive to the sendmail

EDIT

Try something like that:

if(!move_uploaded_file($_FILES['attachment']['name'], $file)) { 
$file = false; 
 } 
sendmail($to, $subjects, $body, $file);

Then you can say:

if($attachment) { 
$mail->addAttachment($attachment); 
} 

Sorry for bad code formatting, wrote it on my mobile phone

Community
  • 1
  • 1
csskevin
  • 383
  • 2
  • 14
  • this is work !! thank u very much sir. – budi Aug 27 '17 at 10:38
  • No problem. Please mark this post as answere if it helped you – csskevin Aug 27 '17 at 10:48
  • You didn't show how `$attachment` is defined. – Synchro Aug 27 '17 at 16:04
  • `$attachment` is a required parameter in the function `sendmail()` If you look above we pass `$file` as fourth parameter to the function `sendmail` and if you watch the code posted by budi as image it says: `function sendmail($to, $subject, $body, $attachment) { ... }` – csskevin Aug 28 '17 at 16:35