Send attachments with PHP Mail()?
I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail()
function. PHP's mail()
function really isn't very good.
To use PHPMailer:
- Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer
- Extract the archive and copy the script's folder to a convenient place in your project.
- Include the main script file --
require_once('path/to/file/class.phpmailer.php');
Now, sending emails with attachments goes from being insanely difficult to incredibly easy:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
It's just that one line $email->AddAttachment();
-- you couldn't ask for any easier.
If you do it with PHP's mail()
function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.
Send PHP HTML mail with attachments
To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.
Sending a simple attached file via PHP mail() function
It is possible to do with all 3 libraries you listed (PHPMAiler, PEAR and Swiftmailer).
For PHPMailer you can see a tutorial here:
require_once '../class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->AddAddress('whoto@otherdomain.com', 'John Doe');
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK<P></P>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
AddAttachment will take a file from your server.
How to upload a file form an HTML form can be found here. Once your email is sent you can delete (unlink) the file from the server.
The PHP manual can help you to better undersand file uploads.
All you want to do is easy to achieve, but it's longer to explain than do it :) But with all the links I gave you you have everything you need. If you have specific questions let me know.
Send email with attachment php not working
Are you looking for something like this:
This should work for you for this scenario:
<?php
function mail_attachment($filename, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$body = '';
$headers = '';
$file = $filename;
$separator = md5(time());
$attachment = chunk_split(base64_encode(file_get_contents($file)));
$headers = "From: ".$from_name."<".$from_mail.">" . PHP_EOL;
$headers .= "Reply-To: ".$replyto . PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . PHP_EOL . PHP_EOL;
$body .= "Content-Transfer-Encoding: 7bit" . PHP_EOL;
$body .= "This is a MIME encoded message." . PHP_EOL;
$body .= "--" . $separator . PHP_EOL;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"" . PHP_EOL;
$body .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$body .= $message . PHP_EOL;
$body .= "--" . $separator . PHP_EOL;
$body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . PHP_EOL;
$body .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$body .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL;
$body .= $attachment . PHP_EOL;
$body .= "--" . $separator . "--";
if (mail($mailto, $subject, $body, $headers)) {
echo "Message sent!";
} else {
echo "ERROR sending message.";
}
}
$my_file = "2.doc";
$my_name = "Your Name (or) Your Business";
$my_mail = "myemail@yahoo.com";
$my_replyto = "replyemail@gmail.com";
$to_email = "replyemail@gmail.com";
$my_subject = "Your file has arrived!";
$requester = $_POST['Field101'];
$message = "Hey $requester, Your custom email message goes here";
mail_attachment($my_file, $to_email, $my_mail, $my_name, $my_replyto, $my_subject, $message);
?>
Related Topics
Group Array Data on One Column and Sum Data from Another Column
Laravel App Storage Images Failed to Load and Redirect to 404
Unset Post Variables After Form Submission
Can You Assign Multiple Variables At Once in PHP Like You Can With Java
How to Get Filename from a Variable (Url) in PHP
How to Update Stock Quantity Using MySQL in PHP
Laravel Save() Method Returning True But Not Updating Records
Setting Selected Option in Laravel Form
Encoding CSV File With Arabic Content
Fatal Error: Call to Undefined Function Mysqli_Connect()
Laravel 6: Call to Undefined Method App\\User::Createtoken()
Mysql Combine Two Columns into One in Query
How to Get Max and Min Value in a Multidimensional Array
Get Selected Option in PHP Without Pressing Submit
Object of Class Mysqli_Result Could Not Be Converted to String