0

I have a document in my websites directory that I want to be attached to an email when the submit button is click but having issues getting this to work I can't quite see how I would do this with out an error. This is what I have so far.

$message = "Body Test";
$attachment = $myFile=fopen("DATA/EmailDoc.txt","r") or exit("Can't open file!"); fclose($myFile);
    if (isset($_POST['submit'])){
        mail('sulmaxcp@gmail.com', 'Subject Test', $message);
    }
Matt Hutch
  • 453
  • 1
  • 6
  • 20
  • Possible duplicate of [Send attachments with PHP Mail()?](http://stackoverflow.com/questions/12301358/send-attachments-with-php-mail) – morxa Mar 14 '16 at 23:15

2 Answers2

0

Use class PHPMailer so you can attach the file you need to send and for other items you need.

Neobugu
  • 333
  • 6
  • 15
0

using php's native mail function, this is doable but very hard. You would need to implement mail's multipart protocol yourself (requires to specify additional headers and encoding your attachment in the body).

Here's an example of how a multipart mail looks (taken from the RFC)

 From: Nathaniel Borenstein <nsb@bellcore.com> 
 To:  Ned Freed <ned@innosoft.com> 
 Subject: Sample message 
 MIME-Version: 1.0 
 Content-type: multipart/mixed; boundary="simple 
 boundary" 

 This is the preamble.  It is to be ignored, though it 
 is a handy place for mail composers to include an 
 explanatory note to non-MIME compliant readers. 
 --simple boundary 

 This is implicitly typed plain ASCII text. 
 It does NOT end with a linebreak. 
 --simple boundary 
 Content-type: text/plain; charset=us-ascii 

 This is explicitly typed plain ASCII text. 
 It DOES end with a linebreak. 

 --simple boundary-- 
 This is the epilogue.  It is also to be ignored.

what this means, is that you would first need to pass a specific Content-Type header to the mail, where the boundary value specifies seperators between all parts in the mail (normally you would have two parts: your mail's actual content and the attachment).

Then in the mail body, you would need to have a string containing all these parts as shown in the example above. In case you wanted to attach binary files, things would be even more complicated, because then you would probably need to base64 encode these binary images and add the used encoding to the part's header that was encoded.

To sum up: if you want attachments, don't use the php mail function for that, but rather use tools like PHPMailer, which will be more high level and simpler to use.

Matthias
  • 2,622
  • 1
  • 18
  • 29