Showing posts with label Mail via PHPMailer. Show all posts
Showing posts with label Mail via PHPMailer. Show all posts

Monday, July 18, 2016

How to Send mail with PHPmailer class

PHP has in-build function for mailing i.e mail() but directly mailing from mail() function may lead to spamming. To resolve this problem we use a different class for mailing one of which is PHPmailer class.

You can download the class from Here


Its a very simple and easy to implement.

Set the class in your project and include

require_once('PHPMailer/PHPMailerAutoload.php');// Mailer Class included


$subject = 'YOUR MAIL SUBJECT';
$from = "FROM NAME";
$mailBodycontent= 'here is mail body content';

//Now initiate the class

$mail = new PHPMailer;

$mail->SMTPDebug = 3;                               // Enable verbose debug output
$mail->isSMTP(true);                                      // Set mailer to use SMTP
$mail->Host = 'ssl://your-smtp-url';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'USERNAME';                 // SMTP username
$mail->Password = 'PASSWORD';                           // SMTP password
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;   

$mail->setFrom($from, $name);
$mail->addAddress('EMAIL-TO-SEND');     // Add a recipient
$mail->addCC('EMAIL-TO-CC');
$mail->addReplyTo($from, 'FROM NAME');
$mail->isHTML(true);  // Set email format to HTML
$mail->Subject = $subject ;
$mail->Body    = $mailBodycontent;

if(!$mail->send()) {
      echo  'Mailer Error: ' . $mail->ErrorInfo;
} else {
       header('REDIRECT');
}

Simple!!!!

NOW little Modification in code and will be able to send  mail with attachment.

Here are changes

Define a upload directory

$upload_dir = 'uploads/';

Now upload the file

$upload_file=move_uploaded_file($_FILES["file"]["tmp_name"],$upload_dir.basename($_FILES["file"]["name"]));

JUST add these line before send()

$file_to_attach = $output_dir.basename($_FILES["file"]["name"]);
$mail->addAttachment($file_to_attach);

Note: Be Careful tha you define and send the accurate path of attachment.!!

Thanks