Wednesday, December 16, 2009

PHP sending emails with gmail smtp to prevent spam mails

1 Download PHPMailer from
2 Extract to folder phpmailer
3 Create a file email.php
4 Paste this code and change the values in blue as you need (I modified the sample code given on the PHPMailer homepage)

$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = ""; // SMTP username
$mail->Password = "password"; // SMTP password
$webmaster_email = ""; //Reply to this email ID
$email=""; // Recipients email ID
$name="name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->WordWrap = 50; // set word wrap
$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "
; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
echo "Mailer Error: " . $mail->ErrorInfo;
echo "Message has been sent";

5 Open the file class.smtp.php in phpmailer directory
6 Paste this code
$host = "ssl://";
$port = 465;
before the line 104 #connect to the smtp server
Hint: Search for #connect
7 Open this page in browser and it will send the email using GMail.

Hint: When you want to email the details from a form, set the variables using the form variables.
eg. $mail->Username=$_POST['email']