How can i send an email using php including mail.php file - php

I want to send an email in php from my localhost which includes mail.php file.
Here is my code for test.php file:
<?php
include_once("Mail.php");
$From = "Sender's name <testing123xyz#gmail.com>";
$To = "Recipient's name <test2#gmail.com>";
$Subject = "Send Email using SMTP authentication";
$Message = "This example demonstrates how you can send email with PHP using SMTP authentication";
$Host = "mail.gmail.com";
$Username = "testing123xyz";
$Password = "testing";
// Do not change bellow
$Headers = array ('From' => $From, 'To' => $To, 'Subject' => $Subject);
$SMTP = Mail::factory('smtp', array ('host' => $Host, 'auth' => true,
'username' => $Username, 'password' => $Password));
$mail = $SMTP->send($To, $Headers, $Message);
if (PEAR::isError($mail)){
echo($mail->getMessage());
} else {
echo("Email Message sent!");
}
?>
When i hit the url of test.php file, server is throwing following error :
Failed to connect to smtp.gmail.com:25 [SMTP: Failed to connect socket: No connection could be made because the target machine actively refused it. (code: -1, response: )]
Please help me out.
Thanks.

Download and use phpmailer from github:https://github.com/PHPMailer/PHPMailer
Also, check this tutorial, it will help you: http://phpmailer.worxware.com/?pg=tutorial
This is the php code to send emails:
<?php
function email($recipient_email_id,$senders_name){
include("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
//IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "sender#gmail.com"; // SMTP username
$mail->Password = "xxx"; // SMTP password
$webmaster_email = "reply#gmail.com"; //Reply to this email ID
$email = "$recipient_email_id"; // Recipients email ID
$name = "$senders_name"; // sender's's name
$mail->From = $webmaster_email;
$mail->FromName = $name;
$mail->AddAddress($email, $name);
$mail->AddReplyTo($webmaster_email, "Name");
$mail->WordWrap = 50; // set word wrap
$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
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
}
?>

My guess is that you are using localhost. Try using Test Mail Server
EDIT as of this link, you are using wrong host. Change it to smtp.gmail.com

Related

PHP send email BCC & CC using SMTP

I have an PHP code to send email to, cc & bcc.
In this case, the cc is not working.
I tested it and saw on my email there is no cc email. (BCC email is worked)
Here is my code:
require_once "Mail.php";
$from = "WEBAPPS <donotreply#test.com>";
$subject = "Calibration will be expiring!";
$host = 'smtp.office365.com';
$port = '587';
$username = 'donotreply#test';
$password = 'w00ew?';
$to = "alwis.david#gmail.com";
$cc = "data.gw#gmail.com";
$bcc = "hidayurie.dave#yahoo.com";
$body = "aa";
$headers = array(
'Port' => $port,
'From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8'
);
$recipients = $to.", ".$cc.", ".$bcc;
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($recipients, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
Why CC is not working? and how to solve it?
in the above code, all recepients seems treating as same.
$recipients = $to.", ".$cc.", ".$bcc;
You can use PHPMailer class at https://github.com/PHPMailer/PHPMailer . This is user friendly library.
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail = new PHPMailer(true); //turn on the exception, it will throw exceptions on errors
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
if (!empty($recipientArr)) { //have mutiple recepients
foreach ($recipientArr AS $eachAddress) {
$mail->addAddress($eachAddress);
}
}
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
The carbon copy is an header.
All recipients are recipients in the same way for the mail server, the difference between carbon copy and blind carbon copy is just a matter of declaring it in the headers.
$headers = array(
'Port' => $port,
'From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8',
'Cc' => $cc
);

PHP send mail error 3

When I try to send the form on my web site, I got this error:
Sorry ..., it seems that my mail server is not responding. Please try again later!
I thing that is a problem with me contact_me.php file
There is the code
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
error_reporting(E_STRICT);
date_default_timezone_set('Portugal/Lisbon');
require_once('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "a.a.pt"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "a.a.pt"; // sets the SMTP server
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "a#a.pt"; // SMTP account username
$mail->Password = "a"; // SMTP account password
$mail->SetFrom('a#a.pt', 'First Last');
$mail->AddReplyTo("a#a.pt","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$address = "a#a.pt";
$mail->AddAddress($address, "a#a.pt");
$formcontent=" From: $name \n Phone: $phone \n Email: $email \n Message: $message";
$formcontent= eregi_replace("[\]",'',$formcontent);
$mail->MsgHTML($formcontent);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
You can try using my class, i'm sure this runs 100%, even if it does not work for you is a credential problem or email server that for some reason waste for the connection
class Mailplus{
protected $host = "ssl://smtps.*.com";
protected $port = "123";
protected $username = "email#example";
protected $password = "*";
protected $from = "Email from - Name <email#example>";
protected $smtp;
function __construct() {
require_once "Mail.php";
$this->smtp = Mail::factory('smtp',
array ('host' => $this->host,
'port' => $this->port,
'auth' => true,
'username' => $this->username,
'password' => $this->password));
}
function SendMail($to ,$subject,$body){
$headers = array ('From' => $this->from,
'Subject' => $subject,
'MIME-Version' =>'1.0',
'Content-Type' =>'text/html',
'charset' => 'ISO-8859-1');
$mail = $this->smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
return "Ex_001";
} else {
return true;
}
}
}
Then use this comand
$mail = new Mailplus ();
if ($mail.SendMail("to#example.com","Subject","html emial")==ture){
//email sent
else{
//email not sent
}

PHP Mailer - User email getting sent to admin

I am trying to send an email to user and admin using php-mailer.But when I send the mail, the user Acknowledgement mail is also getting sent to the admin. The e mails getting sent are in proper format. What is the issue here?
My Code is Here:
$name = "User Name";
$email = "user#gmail.com";
$mobile = 'User Phone No.';
$body = "<div><div>Name: <b>$name</b></div> <div>Email: <b>$email</b></div> <div>Mobile: <b>$mobile</b></div></div>";
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require 'PHPMailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail -> isSMTP();
function sendEmail($mail, $from, $password, $to, $body, $subject) {
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail -> SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail -> Debugoutput = 'html';
//Set the hostname of the mail server
$mail -> Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail -> Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail -> SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail -> SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail -> Username = $from;
//Password to use for SMTP authentication
$mail -> Password = $password;
//Set who the message is to be sent from
$mail -> setFrom($from, $from);
//Set who the message is to be sent to
$mail -> addAddress($to, $to);
//Set the subject line
$mail -> Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail -> msgHTML($body);
//Replace the plain text body with one created manually
$mail -> AltBody = 'This is a plain-text message body';
$sucess = $mail -> send();
// //send the message, check for errors
// if (!$sucess) {
// echo "Mailer Error: " . $mail -> ErrorInfo;
// } else {
// echo "Message sent!";
// }
}
$from = "noreplyadmin#gmail.com";
$maiAdmin = "admin#gmail.com";
$password = "password";
$subject = "Enquiry";
// Send Mail to admin
sendEmail($mail, $from, $password, $maiAdmin, $body, $subject);
// Send Mail to User
$userMessage = "We Received your request. Our representative will contact you soon.";
sendEmail($mail, $from, $password, $email, $userMessage, 'Acknowlwdgement');
You are using the same instance and have not cleared the previous out of the PHPMailer $mail instance. You can either clear the old data out of the PHPMailer Instance or do this:
$adminmail = new PHPMailer();
$adminmail -> isSMTP();
$usermail = new PHPMailer();
$usermail -> isSMTP();
sendEmail($adminmail, $from, $password, $maiAdmin, $body, $subject);
$userMessage = "We Received your request. Our representative will contact you soon.";
sendEmail($usermail, $from, $password, $email, $userMessage, 'Acknowlwdgement');
Whatever floats your boat I suppose.

Send attatchment using php mail()

I want to attach a image as an attachment using mail() function.
I am using xampp and want the image to be sent from my computer to an email id.
This code is sending text email easily:
<?php
if(mail('abc#gmail.com','Hello','Testing Testing','From:xyz#gmail.com'))
{
echo "Success";
} else {
echo "Fail";
}
?>
I want to add an image after it using normal mail method of php.
you need to use the pear library for composing or sending the mail.
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
here is a way
You could use the Mail class from the Zend library, very simple and no reliance on PEAR.
Its been covered in a previous question here.
I suggest to use Swiftmailer. It is up to date, easy to install and use. You can install it via PEAR, but there are lots of other options you might find more convenient as well.
Example code to send a mail with an attachement taken from the manual:
require_once 'lib/swift_required.php';
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('Your subject')
// Set the From address with an associative array
->setFrom(array('john#doe.com' => 'John Doe'))
// Set the To addresses with an associative array
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
// Give it a body
->setBody('Here is the message itself')
// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')
// Optionally add any attachments
->attach(Swift_Attachment::fromPath('my-document.pdf'));
this is using php and ajax it will work 100%
<?php
include "db.php";
if(isset($_POST['tourid']))
{
$to=$_POST['email'];
$file_name = "test/sample.pdf";
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = ''; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = ''; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = ''; //Sets SMTP username
$mail->Password = ''; //Sets SMTP password
$mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = ''; //Sets the From email address for the message
$mail->FromName = ''; //Sets the From name of the message
$mail->AddAddress($to, 'Name'); //Adds a "To" address
$mail->WordWrap = 50; `` //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem
$mail->Subject = 'Customer Details'; //Sets the Subject of the message
$mail->Body = 'Please Find Tour details in attached PDF File.'; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$message = '<label class="text-success">Tour Details has been send successfully...</label>';
echo $message;
unlink($file_name);
}
}
else
{
echo "sending error";
}
?>

Invalid Address in PHPMailer

I'm getting an invalid address error while running the PHP script below. The SMTP credentials and recipient e-mail were altered for this post. They are all valid on the actual script. I don't know why the recipient e-mail is being rejected. I'm trying to send an e-mail with SMTP authentication, and SMTP security (SSL, TLS) is not required.
Any help would be appreciated.
include 'PHPMailer_5.2.2/class.phpmailer.php';
function SendConfirmation ($sName, $sEmail)
{
$mail = new PHPMailer ();
$mail->SMTPDebug = 2;
$mail->Host = "mail.exchange.telus.com";
$mail->IsSMTP ();
$mail->Username = "inbin#website.com";
$mail->Password = "password";
$mail->From = "inbin#website.com";
$mail->FromName = "Web Site";
$mail->AddAddress ($sEmail, $sName);
$mail->Subject = 'PHPMailer Test' . date ('Y-m-d H:i:s');
$mail->Body = "This is a test.";
if ($mail->Send ())
echo "\r\nMail sent.";
else
echo "\r\nMail not sent. " . $mail->ErrorInfo;
echo "\r\n";
}
/***[ Main ] **************************************************************************/
$sName = 'Johan Cyprich';
$sEmail = 'jcyprich#website.com';
$bSent = SendConfirmation ($sName, $sEmail);
Make sure you have valid email addresses for AddReplyTo and/or AddAddress.
I had the same problem and it turned out to be because I was setting empty values for AddReplyTo.

Categories