How to send email using smtp in php?

Member

by jasen , in category: Third Party Scripts , 10 days ago

How to send email using smtp in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 9 days ago

@jasen 

To send an email using SMTP in PHP, you can use the PHPMailer library which provides a simple and efficient way to send emails using SMTP. Here's a basic example code to send an email using SMTP in PHP with PHPMailer:

  1. First, you need to download the PHPMailer library from https://github.com/PHPMailer/PHPMailer and include it in your PHP script.
  2. Create a new PHP file and include the PHPMailer Autoload file at the beginning of your script:
1
2
3
4
5
6
7
8
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

// Include PHPMailer library files
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';


  1. Next, create a new instance of the PHPMailer class and setup the SMTP settings:
1
2
3
4
5
6
7
8
$mail = new PHPMailer();

$mail->isSMTP();
$mail->Host = 'smtp.yourmailserver.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_email_password';


  1. Set the email content:
1
2
3
4
5
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Subject of your email';
$mail->Body = 'Body of your email';
$mail->isHTML(true); // Set email format to HTML


  1. Finally, send the email:
1
2
3
4
5
6
if (!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}


This is a basic example of sending an email using SMTP in PHP with PHPMailer. You can customize it further by adding attachments, setting CC/BCC recipients, and adding additional headers.