Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure PHP to send e-mail?

Tags:

php

email

smtp

I need to send mail to the users of my website using php script. I have tried using mail function in php.
My code is as follows:

  $to = "[email protected]";
  $subject = "Test mail";
  $message = "My message";
  $from = "[email protected]";
  $headers = "From:" . $from;
  mail($to,$subject,$message,$headers);

When I try running the program this is what I get:

 Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set().

Please tell me what address to include in the $from variable. Do I need a smtp server for this? How do I send mails using a localhost? Please tell me what exactly to edit in the php.ini file

I am new to all this.. Please help me..

like image 538
abcdefgh Avatar asked Jul 08 '13 18:07

abcdefgh


People also ask

How can I send an email using PHP?

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters. mail( to, subject, message, headers, parameters );

Does PHP mail require SMTP?

PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail. On a hosted server, the SMTP settings would have already been set. The SMTP mail settings can be configured from “php. ini” file in the PHP installation folder.


1 Answers

Use PHPMailer instead: https://github.com/PHPMailer/PHPMailer

How to use it:

require('./PHPMailer/class.phpmailer.php');
$mail=new PHPMailer();
$mail->CharSet = 'UTF-8';

$body = 'This is the message';

$mail->IsSMTP();
$mail->Host       = 'smtp.gmail.com';

$mail->SMTPSecure = 'tls';
$mail->Port       = 587;
$mail->SMTPDebug  = 1;
$mail->SMTPAuth   = true;

$mail->Username   = '[email protected]';
$mail->Password   = '123!@#';

$mail->SetFrom('[email protected]', $name);
$mail->AddReplyTo('[email protected]','no-reply');
$mail->Subject    = 'subject';
$mail->MsgHTML($body);

$mail->AddAddress('[email protected]', 'title1');
$mail->AddAddress('[email protected]', 'title2'); /* ... */

$mail->AddAttachment($fileName);
$mail->send();
like image 103
pouria Avatar answered Sep 22 '22 04:09

pouria