Send email from localhost/ online server using php

by  
Share:
Send email from localhost online server using php

Sending emails from localhost is one of the most frequently asked question from young learners. Even professionals like us need this script to test emails from our local server (localhost) / online server when developing projects. In this tutorial I will be explaining to send email from localhost/online server using php.

Using Phpmailer library to send emails

Phpmailer library is my personal favorite and in fact loved by estimated 9 million users worldwide. Using phpmailer you can send html emails, text emails, via smtp, qmail. You can also cc and bcc to multiple recipient. You can even download the phpmailer library from github and sourceforge. Have a look at some of the examples here.

Configuring phpmailer to send email via smtp

I am assuming that you have a google email (gmail) account, because this is the easiest way to send email via smtp. If you have accounts in hotmail, rediffmail or any other emails service it can be done too. Follow the steps to configure phpmailer library to send email.

The first step is to download phpmailer library zip file from the phpmailer website/github/sourceforge. Once you are done with that, extract to your project folder which is hosted on local (localhost) / online server.

Include the phpmailer class file in your php file. This will be the page from where you will be sending emails.

<?php
// include phpmailer file
require_once "phpmailer/class.phpmailer.php";
?>

Instantiate the phpmailer class i.e. create an object of phpmailer class.
<?php
// creating the phpmailer object
$mail = new PHPMailer(true);
?>

Set the class to use smtp method.
<?php
$mail->IsSMTP();
?>

If you want to debug the code or check the outputs after sending mail use this option.
<?php
// enables SMTP debug information (for testing)
// set 0 turn off debugging mode, 
// set 1 to show debug result
$mail->SMTPDebug = 0;
?>

Enable smtp authentication. It is recommended to use it.
<?php
$mail->SMTPAuth = true;
?>

Set email sending mode, smtp server and port no. Again I am assuming that you are using gmail credentials.
<?php
// for gmail
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;

// for hotmail
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.live.com';
// use 25 or 587
$mail->Port = 25; 

?>

Give your email address and password. Also set the sender email address and name
<?php

$mail->Username = 'youremail@gmail.com';
// must be in single quotes
$mail->Password = 'yourpassword';

$mail->SetFrom('youremail@gmail.com', 'Your Name');
?>

If you want to add one or multiple recipient, add this line below.
<?php
$mail->AddAddress('user1@domain.com');
// remove this line below 
// if you don't want to send to multiple recipient
$mail->AddAddress('user2@domain.com');
?>

You can also carbon copy (cc)/ blind carbon copy (bcc) to the recipient.
<?php
$mail->AddCC('user1@domain.com');
$mail->AddBCC('user2@domain.com');
?>

Add message body. You can use simple text or any formatted html template.
<?php
$message = '<html><body>';
$message .= '';
$message .= '<table rules="all" cellpadding="10">';
$message .= '<tr style="background: #eee;"><td>';
$message .= '<h1><a href="https://aarafacademy.com/" target="_blank">';
$message .= '<img src="https://aarafacademy.com/thesoftwareguy-logo-small.png" alt="" />';
$message .= '</a></h1>';
$message .= '</td></tr>';
// add body 
$message .= "<tr style='background: #eee;'><td>My sample text message goes here.</td></tr>";

$message .= "</table>";

// add footer
$message .= '<table rules="all" width="600px">';
$message .= '<tr><td>This mail is send via ';
$message .= '<a href="https://aarafacademy.com/" target="_blank">aarafacademy.com</a>';
$message .= ' and is used for demo purpose only. ';
$message .= '<b>Please do not reply to this mail.</b></td></tr>';

$message .= "</table>";
$message .= "</body></html>";

// add message body
$mail->MsgHTML($message);

?>

If you want to attach any files you can do the same using this code below.
<?php
// replace time.png with your file
$mail->AddAttachment('time.png');
?>

Triple check your configuration and send the mail now.
<?php
try {
    $mail->Send();
    echo "Mail send successfully";
} catch (phpmailerException $e) {
    echo $e->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

If you have any suggestion/problem regarding this tutorial, comment in the form below.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Ajay on

nice. it will really help us. i needed that thing.

Reply
Shahrukh Khan on

Thanks a lot.

Reply
misbah on

where is the database of this code???

Shahrukh Khan on

this code does not need any database.

raghava on

i was getting an error : SMTP Error: Could not authenticate.

Reply
Shahrukh Khan on

maybe your credentials are wrong, check the port no username and password.

Reply
ajay on

Hi ,

Firstly thanks for sharing .
I tried the above code updated the credentials for in page “testmail-gmail-smtp.php” and it worked fine .

But sending mail to multiple people does not works even thought I give my my mail ID and username .

Please help thanks

Reply
Shahrukh Khan on

what is the error.

Reply
chintan on

plz send me ur code

Reply
Shahrukh Khan on

code is available for download at the end of the tutorial.

chetan on

i have download the code and configure it as you explained
but it gives following error

Fatal error: Class ‘SMTP’ not found in C:\wamp\www\coding-cage\step-blogging\PHPMailer-master\PHPMailer-master\class.phpmailer.php on line 1290

Reply
Shahrukh Khan on

please check your file path.

Reply
haris on

Dear sharukh thnx for share differnt code with view demo it ‘s very helpful thnx thnx

Reply
dashrath on

is there any configuration in “php.ini ” file to work >

Reply
Shahrukh Khan on

no. it will work with the default configuration.

Reply
vikas on

i have tried it and provide same gmail and password but it gives following error even my gmail id or password is correct …

2015-07-23 17:57:50 CLIENT -> SERVER: EHLO localhost 2015-07-23 17:57:50 CLIENT -> SERVER: AUTH LOGIN 2015-07-23 17:57:51 CLIENT -> SERVER: cHJhZGVlcGtob2RrZTRAZ21haWwuY29t 2015-07-23 17:57:52 CLIENT -> SERVER: cHJhZGVlcGtob2RrZTIwMTU= 2015-07-23 17:57:53 SMTP ERROR: Password command failed: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 br14sm5536461pdb.47 – gsmtp 2015-07-23 17:57:53 SMTP Error: Could not authenticate. 2015-07-23 17:57:53 CLIENT -> SERVER: QUIT 2015-07-23 17:57:54 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Reply
Shahrukh Khan on

please check the other credentials like port no and password must be in single quotes if it contains any special characters.

Reply
vikas on

Still its not working

$mail->SMTPAuth = true;
$mail->SMTPDebug = 1;
$mail->Username = “mygmail4@gmail.com”;
$mail->Password = “mygmailpwd1254”;
$mail->SMTPSecure = “ssl”; // sets the prefix to the servier
$mail->Host = “smtp.gmail.com”; // sets GMAIL as the SMTP server
$mail->Port = 465;

Shahrukh Khan on

uncomment this
// $mail->SMTPSecure = “ssl”;

sandeep on

i give my correct email id or password still it gives following error

Message was not sent
Mailer Error: The following From address failed: validemail@gmail.com

Reply
Shahrukh Khan on

Try to comment this line, it will work.
$mail->SMTPSecure = ‘ssl’;
And also I would like to tell all the user if you face such issue you can try commenting the $mail->SMTPSecure line and check

Reply
Anshu Kumar on

Message could not be sent.Mailer Error: SMTP connect() failed. http://phpmailer.github.io/PHPMailer

above error will be thrown to me.
i write ur code whatever u specified

Shahrukh Khan on

try to turn off the ssl part. also if you have a email for your domain like info@aarafacademy.com or whatever your domain is, try that it will work.

harisatyanarayana on

hi send the mail from localhost is not at all working

Reply
siva on

SMTP Error: Could not authenticate???
plz help me bro

Reply
vikky on

2016-02-12 07:35:39 CLIENT -> SERVER: EHLO developersinaction.com 2016-02-12 07:35:39 CLIENT -> SERVER: AUTH LOGIN 2016-02-12 07:35:39 CLIENT -> SERVER: dGVzdC5kZXZlbG9wZXJzMjAxMkBnbWFpbC5jb20= 2016-02-12 07:35:39 CLIENT -> SERVER: bm9wYXNzMTIzNA== 2016-02-12 07:35:39 SMTP ERROR: Password command failed: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 y196sm1107704oia.24 – gsmtp 2016-02-12 07:35:39 CLIENT -> SERVER: QUIT SMTP Error: Could not authenticate.

getting this error

Reply
Shahrukh Khan on

try some live mail server details.

Reply
chintan on

end email PHP
Fatal error: Class ‘SMTP’ not found in C:\xampp\htdocs\mail\PHPMailer\class.phpmailer.php on line 1439

Reply
Shahrukh Khan on

either you are not calling the method properly or you have not given the path to the file correctly. Please check those.

Reply
Roshan kr Soni on

Hello Shahrukh, do u have any demo page for this ?

Reply
Shahrukh Khan on

no..i removed demo because of lots of spamming emails.

Reply
Shashank on

thanks for this post i really need this. It’s works fine.

Reply
Yogesh on

Hi Shahrukh,
Could you tell the steps to set this mailer in an intranet where the gmail services is blocked??

Reply
Shahrukh Khan on

Try checking gmail settings, check on weather you can send email using phpmailer library using goolge credentials or not.

Reply
Esinniobiwa Quareeb on

1. I used it on localhost, it worked fine and sent message to the mail provided but I tried hosting the demo on an online server, it is saving the data in online database but it is given the error SMTP connect() failed and not sending the message.

Reply
sunil on

smtp error could not authenticate

Reply
amutha on

SMTP connect() failed.

Reply
PAVAN KUMAR YADAV on

Its not working at all……..!
SMTP could not authenticate and I am not doing any mistake. I checked StackOverFlow too nothing working.

Reply
Shahrukh Khan on

maybe someting with google setings nowaadays. sorry for the late reply, being busy with my startup these days.

Reply
subham on

does this code works on online server while hosting

Reply
Shahrukh Khan on

Yes. If you hosting provider provides you with email capability.

Reply
VS Aithal on

Does this code only works with the gmail service?? If want to implement with other hosting service provider..is it possible in PHPMailer??
Thanks in advance

Reply
Shahrukh Khan on

yes it can be used with any of your host.

Reply
VS Aithal on

Thanks much!! It is working with local server host as well. I want to post some field data from index page. I mean need to post some data to the receiver along with the message? Could you help me please?? Thanks in advance.

Shahrukh Khan on

use query string (GET method)

RAVI PRAKASH YADAV on

I WANT TO ADD MORE FIELDS BUT I DON’T KNOW HOW TO PRINT ALL DATA OF FIELDS AND IF I WANT TO PRINT THE php form DATA IN $message=” SECTION IT got Parse error: syntax error, unexpected ‘”‘, expecting T_STRING or T_VARIABLE or T_NUM_STRING error.
so tell me how to send the data of more than five or six fields.

Reply
nahed on

above code is not working onlocalhost as well as on hosting space and no error also

Reply
Shahrukh Khan on

wont work on the local host, see if you have email sending option available on live server.

Reply
Sayali Gadade on

I got this error.

SMTP connect() failed.

Reply
Arjun on

Sir, I downloaded source file and changed username and password but i am getting SMTP connect() failed error.

I need solutions.

SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect() failed

Reply
Shahrukh Khan on

its already answered, please read the comment thread.

Reply
fnynn jamak on

SMTP connect() failed.

can tech me how to slove this ?

Reply
Shahrukh Khan on

pleae read the comment thread.

Reply
aquilasoft on

SMTP connect() failed. i need solutions

Reply
Shahrukh Khan on

please read the comment thread.

Reply
ramprath on

SMTP connect() failed.

Reply
Salman on

Could not instantiate mail function.

Reply
Yousef on

I tried the script on my localhost. It works. cheers.

Reply
Shahrukh Khan on

cheers!!!

Reply
selvam on

SMTP connect() failed…. but all value stored in database… i am run the localhost server

Reply
Shahrukh Khan on

please check the comments section, this problem has already been answered.

Reply
Shail on

Hi,
Code work on localhost (using wamp), but do not work on my website server. shows smtp() fail. what changes need to do for it?

Reply
Hasan on

You need to check your mail server hostname, protocol and the port number as well.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.