$to = 'recipient@example.com'; $subject = 'Test email'; $message = 'This is a test email sent from PHP'; $headers = 'From: sender@example.com'; if(mail($to, $subject, $message, $headers)) { echo 'Email sent successfully!'; } else { echo 'An error occurred while sending email.'; }
$to = 'recipient@example.com'; $subject = 'Test email'; $message = "This is a test email sent from PHP with HTML content
"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: sender@example.com'; if(mail($to, $subject, $message, $headers)) { echo 'Email sent successfully!'; } else { echo 'An error occurred while sending email.'; }
$to = 'recipient@example.com'; $subject = 'Test email with attachment'; $message = 'This is a test email with attachment sent from PHP'; $headers = 'From: sender@example.com'; $file_path = '/path/to/attachment.pdf'; $file_attachment = chunk_split(base64_encode(file_get_contents($file_path))); $mail_body = "--Boundary_\r\n"; $mail_body .= "Content-Type: application/octet-stream; name=" . basename($file_path) . "\r\n"; $mail_body .= "Content-Disposition: attachment; filename=" . basename($file_path) . "\r\n"; $mail_body .= "Content-Transfer-Encoding: base64\r\n"; $mail_body .= "\r\n" . $file_attachment . "\r\n\r\n"; $mail_body .= "--Boundary_"; $headers .= "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"Boundary_\"\r\n"; $headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n" . $mail_body; if(mail($to, $subject, $message, $headers)) { echo 'Email sent successfully with attachment!'; } else { echo 'An error occurred while sending email.'; }This code sends an email with an attachment. The attachment is read and its base64 encoded content is included in the email body with relevant headers. The above examples are using PHP's native Mail function. There are also various third-party libraries available to send emails such as SwiftMailer, PHPMailer and Zend Mail.