0

Here is my code

$to = $to;
$from = $from;
$subject = $subject; 
$file = "example_file.pdf"; 
$htmlContent = "message goes here"; 
$headers = "From: "." <".$from.">"; 

//boundary 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

//headers for attachment 
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

//multipart boundary 
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n"; 

//preparing attachment
if(!empty($file) > 0){
    if(is_file($file)){
        $message .= "--{$mime_boundary}\n";
        $fp =    @fopen($file,"rb");
        $data =  @fread($fp,filesize($file));

        @fclose($fp);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" . 
        "Content-Description: ".basename($file)."\n" .
        "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" . 
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    }
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $from;

//send email
$mail = @mail($to, $subject, $message, $headers, $returnpath); 

//email sending status
return $mail ? true : false;

I am using the above code for my project.

It works fine when sending email without attachment, but with attachment all emails goes to junk and spam

Help me to solve the problem.

  • I have no issues on sending mail without attachment. I have issues only when sending email with attachment. If you can help me out @mario –  Aug 21 '19 at 05:04
  • There is no "help me" or resolution without showcasing some research. Read the linked reference, use one of the checking services; and only *then* fix your manual MIME construction copypasta (or use a proper library). – mario Aug 21 '19 at 05:08

1 Answers1

-1

It would be a good practice to add headers with information. Try adding more info.

$headers .= "Reply-To: The Sender <sender@sender.com>\r\n"; 
$headers .= "Return-Path: The Sender <sender@sender.com>\r\n";
$headers .= "From: The Sender <senter@sender.com>\r\n"; 
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n";

```

This may solve your problem. Give it a try.
nXn
  • 904
  • 6
  • 13