Php sending mail using smtp
Here is an example of how to send an email using SMTP in PHP:
Using PHP's built-in mail()
function
You can use the mail()
function to send an email using SMTP. Here is an example:
<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email';
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'MIME-Version: 1.0'. "\r\n".
'Content-Type: text/plain; charset=UTF-8';
mail($to, $subject, $message, $headers);
?>
In this example, the mail()
function takes four arguments:
$to
: the recipient's email address$subject
: the subject of the email$message
: the body of the email$headers
: the headers of the email, including theFrom
,Reply-To
,MIME-Version
, andContent-Type
headers
Using a PHP SMTP library
If you want more control over the SMTP connection and the email itself, you can use a PHP SMTP library. Here are a few popular ones:
- PHPMailer: a popular and widely-used library that provides a simple and easy-to-use interface for sending emails using SMTP.
- SwiftMailer: another popular library that provides a more advanced and flexible interface for sending emails using SMTP.
Here is an example using PHPMailer:
<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email';
if (!$mail->send()) {
echo 'Error sending email: '. $mail->ErrorInfo;
} else {
echo 'Email sent successfully!';
}
?>
In this example, we create a new instance of the PHPMailer
class and set the SMTP server details, including the host, authentication, username, password, and port. We then set the from address, add the recipient address, set the subject and body of the email, and send the email using the send()
method.
Common SMTP settings
Here are some common SMTP settings that you may need to configure:
- Host: the hostname or IP address of the SMTP server
- Port: the port number used by the SMTP server (usually 25, 587, or 465)
- SMTPAuth: whether to use authentication (true or false)
- Username: the username to use for authentication
- Password: the password to use for authentication
- SMTPSecure: the encryption method to use (none, ssl, or tls)
- Timeout: the timeout value for the SMTP connection (in seconds)
Note that the specific settings may vary depending on your email provider or the SMTP server you are using.