In this tutorial I am going to show you how to send email with attachment using phpmailer. I have already write a tutorial on How to Send Email in PHP it included attachment also. Now in this tutorial, I will write send email with attachment using phpmailer.
Simple Code:
<?php require('PHPMailer/class.phpmailer.php'); $msg = 'Hello World'; $subj = 'test mail message'; $to = 'info@yoursite.com'; $toName = 'Name'; $first_name = 'Name'; $last_name = 'Last'; $from = 'you@youremail.com'; //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->IsSMTP(); $mail->Timeout = 360; //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = "hidden"; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = 25; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication $mail->Username = $from; //Password to use for SMTP authentication $mail->Password = "*******"; //Set who the message is to be sent from $mail->SetFrom($from, $first_name.' '.$last_name); //Set an alternative reply-to address //$mail->AddReplyTo('replyto@example.com','First Last'); //Set who the message is to be sent to $mail->AddAddress($to, $toName); //Set the subject line $mail->Subject = $subj; //Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body $mail->Body = $msg; //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //Attach an image file //$mail->AddAttachment($file); $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); //Send the message, check for errors if(!$mail->Send()) { echo "<script>alert('Mailer Error: " . $mail->ErrorInfo."')</script>"; } else { echo "<script>alert('Your request has been submitted. We will contact you soon.')</script>"; Header('Location: main.php'); } ?>
This is the simple code to send email to any one with attachment.
If you want more option in attachment like name, MIME and file type use it like this.
$mail->AddAttachment($path, $name, $encoding, $type); // advance parameters for attachment.
I hope this tutorial will help you to send email with attachment using phpmailer in PHP.