Sending MIME email attachment with PHP

Have you ever want to send an attachment email with PHP?
PHP has its own builtin function to send an email, you can see right here http://www.php.net/manual/en/ref.mail.php. Its easy to use and simple.

But sometimes if we want more, for example we want to attach one or more files in our email then the PHP’s builtin mail() function cant do it for you like the way you used it for sending an text email.
There’s need extra formating to be possible attaching files on the email.

There’s alot of free pre-made scripts that can help you out there.
For example and popular one is the PHPMailer on http://phpmailer.sourceforge.net/

In personal, i’d like if i can have a more simple, faster, and lightweight function.
So, i’ve decided to made my own a ’sendmail’ functions, and its works like this:

<?php
include “sendmail.php”;

$sender = “my@emailaddress.com”;
$recipient = “her@mailbox.net”;
$subject = “Hi long time no see..”;
$message = “This is text only message.”;

// Send the email, the most minimal parameter
if(sendmail($sender, $recipient, $subject, $message)) {
  echo “Text-only mail was sent…”;
}
else {
  echo “Sending failed!”;
}

$htmlmessage = “This is <b>html</b> message.”;
$attachments = array( “dir/photo1.jpg”, “doc/letter.doc” );

// Send the email with alternative content
// html formatted, and attachments.
if(sendmail($sender, $recipient, $subject, $message, $htmlmessage, $attachments)) {
  echo “Mail was sent with with attachment…”;
}
else {
  echo “Sending failed!”;
}
?>

The email will be formatted automatically and will be sent using php’s builtin mail() function.

In above example, your email message will be sent with 2 alternative format, if the recipient mail reader client supports email with HTML format, the html message will be shown. Otherwise, your original text message will be shown instead.

In other case, if you need send the email directly through a SMTP server, just specify extra parameter.
Like this:

<?php
include “sendmail.php”;

$options["smtp_delivery"] = true;
$options["smtp_host"] = “your.smtp.host”;
// or an IP address like 192.168.1.1

// Optional, specify another port
// if the smtp server not on the standart port 25
$options["smtp_port"] = “2525″;

// Optional, Specify a username and password
// if the smtp server needs authentication.
$options["smtp_user"] = “smtpuser”;
$options["smtp_pass"] = “secret”;

// Send with the function like usual,
// But, with extra 1 parameter
if(sendmail($sender, $recipient, $subject, $message, $htmlmessage, $attachments, $options)) {
  echo “Mail successfully sent through SMTP…”;
}
else {
  echo “Mail sending failed!”;
}

// Show the conversation logs
// with the smtp server, if you want to see it
print_r($GLOBALS["smtp_logs"]);
?>

Its quite simple, and easy to use, isnt it?
I will put the full source code on my next post.

Friday, 22 June 2007. PHP Tutorials. Leave a comment.