How to Send Mail From PHP

How to Send Mail From PHP

Sending mails from PHP can raise certain problems. Usually the mail is sent from php through a simple function PHP function: mail(…). However the function needs a module that should be enabled in the php ini file.

Not all the hosting providers enable it and you can not make changes in php admin area in the php shared hosting. In this case the another alternative should be used. There are 2 php libraries I’ve tried to send a mail which will be described in this tutorial: PHPMailer and Mail PEAR Package.

1. Using the php mail() function.
The first alternative you should use if it available is the php mail function.

2 Using PHPMailer
The PHP Mailer is a Object Oriented PHP library that can be used to send mails through SMTP and using the send mail Linux command. It is recommended to use SMTP for sending the emails. Most of the hosting providers offer the option to configure email boxes which can be used to send mails using SMTP protocol.

Here is a piece of code that can be used to send mails through SMTP:

SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "xxxx@xxxx.com"; // SMTP username
$mail->Password = "xxxxxx"; // SMTP password
$webmaster_email = "xxxx@xxxx.com"; //Reply to this email ID

$email="yyyy@yyyy.com"; // Recipients email ID
$name="name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$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";
}
?>

The previous piece of code was tested sending emails through gmail accounts and worked fine.

In many cases PHPMailer seems to raise some difficulties when it is used in different accounts. The same code might work for one hosting without working on other hosting accounts and the message errors are not detailed enough to give enough hints to fix the problem.

A frequent problem raised by PHPMailer is the following Exception:Language string failed to load: instantiate. This problem is generated by the fact that the languages files can not be found and appears usually when another error must be reported and when phpmailer is not installed in the root of the application.

3.

.