Thursday, April 6

PHP Send Email with Attachments

 Dear All,


Here's an example code for attaching a file to an email in PHP using the built-in mail() function:


Php code

// recipient email address

$to = "recipient@test.com";

// email subject

$subject = "Test email with attachment";

// email message

$message = "This is a test email with attachment.";

// attachment file path

$file_path = "/path/to/attachment.pdf";

// attachment file name

$file_name = "attachment.pdf";

// read attachment file contents

$file_content = file_get_contents($file_path);

// encode attachment file contents in base64

$file_content = base64_encode($file_content);


// email headers

$headers = "MIME-Version: 1.0" . "\r\n";

$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

$headers .= "From: sender@example.com" . "\r\n";

$headers .= "Cc: cc@example.com" . "\r\n";

// email boundary

$boundary = "boundary_" . md5(uniqid(time()));

// email body

$body = "--$boundary\r\n";

$body .= "Content-Type: text/html; charset=UTF-8\r\n";

$body .= "\r\n";

$body .= "$message\r\n";

$body .= "--$boundary\r\n";

$body .= "Content-Type: application/pdf; name=\"$file_name\"\r\n";

$body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";

$body .= "Content-Transfer-Encoding: base64\r\n";

$body .= "\r\n";

$body .= chunk_split($file_content) . "\r\n";

$body .= "--$boundary--";


// send email with attachment

if(mail($to, $subject, $body, $headers)) {

    echo "Email sent with attachment.";

} else {

    echo "Failed to send email with attachment.";

}

In the above code, I first specify the recipient email address, email subject, and email message. I also provide the file path and name of the file to be attached.

I then read the contents of the file and encode it in base64 format. I also specify the email headers, including the MIME version, content type, and sender and cc email addresses.

I specify the email boundary and create the email body, which includes the message and the attachment. The attachment is added as a separate section in the email body with the appropriate content type and encoding.

Finally, I use the mail() function to send the email with the attachment. If the email is sent successfully, I display a success message. Otherwise, we display an error message.


No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...