Your Gateway To Digital Success
Wesbytes Blue Logo

Wesbytes Knowledge Base

Search our articles or browse by category below

Sending email using PHP (PHPMailer)

Last modified: July 2, 2022
You are here:
Estimated reading time: 1 min

Sending email using PHP (PHPMailer)

You can send an email using PHP with SMTP authentication. To utilise the PHPMailer courses, you simply need to download the class files:

The following is the sample code for SMTP authentication to send e-mails using the PHP script:

$mail->Host = “mail.domain.com”; // SMTP servers
$mail->SMTPSecure = ‘ssl’; // Enable SSL encryption, then change below port to 587.

You may remove this line to use non-SSL with port 25 or 26 in below.
$mail->Port = “25”; //specify SMTP Port
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “password”; // SMTP password

$mail->From     = “[email protected]”;
$mail->FromName = “Name”;
$mail->AddAddress(“[email protected]”,”Name”);
$mail->AddReplyTo(“[email protected]”,”Your Name”);

$mail->WordWrap = 50;                 // set word wrap

$mail->IsHTML(true);                               // send as HTML

$mail->Subject  =  “Here is the subject”;
$mail->Body     =  “This is the HTML body“;
$mail->AltBody  =  “This is the text-only body”;

if(!$mail->Send())
{
echo “Message was not sent

“;
echo “Mailer Error: ” . $mail->ErrorInfo;
exit;
}

echo “Message has been sent”;

?>

Please ensure that you make needed modifications to the above script.

Let's Look into PHPMailer

One of the most well-liked open-source PHP email sending libraries is PHPMailer. Since its initial release in 2001, aside from others like Swiftmailer, it has emerged as the preferred method of sending emails programmatically among PHP developers.

Why Do We Need It?

First and foremost, email needs to be sent from PHP code by developers. Mail is the only PHP function that can directly make this work (). The use of well-known technologies like HTML messages, encryption, authentication, and attachments is not supported, though.

Additionally, precisely formatting emails is a considerable challenge. Numerous overlapping and incompatible standards exist. They need strict adherence to excruciatingly complex encoding and formatting regulations. The great majority of internet code that uses the mail() method directly is incorrect, if not dangerous.

In addition, the PHP mail() function normally uses a local mail server, which on Linux, BSD, and macOS systems is typically fronted by a sendmail programme, but not on Windows. A local mail server is typically absent. Additionally, without even requiring a local mail server, PHPMailer’s integrated SMTP client enables email transmission on all platforms. The mail() function should be avoided whenever possible because SMTP to localhost is both quicker and safer.

Was this article helpful?
Dislike 0
Views: 6