Smtp mail php code

Here is an example of PHP code that sends an email using SMTP:

<?php

// Define the email settings
$smtp_host = 'smtp.example.com';
$smtp_port = 587;
$smtp_username = 'your_email_username';
$smtp_password = 'your_email_password';
$from_email = '[email protected]';
$to_email = '[email protected]';
$subject = 'Test Email';
$message = 'This is a test email sent using PHP';

// Create a new SMTP connection
$smtp = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 30);

// Check if the connection was successful
if (!$smtp) {
    echo "Error connecting to SMTP server: $errstr ($errno)";
    exit;
}

// Send the SMTP commands
fputs($smtp, "HELO example.com\r\n");
fputs($smtp, "AUTH LOGIN\r\n");
fputs($smtp, base64_encode($smtp_username). "\r\n");
fputs($smtp, base64_encode($smtp_password). "\r\n");
fputs($smtp, "MAIL FROM: <". $from_email. ">\r\n");
fputs($smtp, "RCPT TO: <". $to_email. ">\r\n");
fputs($smtp, "DATA\r\n");
fputs($smtp, "Subject: ". $subject. "\r\n");
fputs($smtp, $message. "\r\n");
fputs($smtp, ".\r\n");

// Check if the email was sent successfully
if (feof($smtp)) {
    echo "Email sent successfully!";
} else {
    echo "Error sending email: ". fgets($smtp);
}

// Close the SMTP connection
fclose($smtp);

?>

This code uses the fsockopen function to establish a connection to the SMTP server, and then sends the necessary SMTP commands to authenticate, send the email, and close the connection.

You'll need to replace the placeholders ($smtp_host, $smtp_port, $smtp_username, $smtp_password, $from_email, $to_email, $subject, and $message) with your own email settings.

Note that this code uses the AUTH LOGIN authentication method, which is a simple and insecure method. You may want to consider using a more secure method, such as AUTH PLAIN or AUTH TLS, depending on your email provider's requirements.

Also, this code does not handle errors or exceptions well, so you may want to add some error handling code to make it more robust.

You can also use PHP's built-in mail function to send an email using SMTP, it's a simpler way to send an email:

<?php

$to = '[email protected]';
$subject = 'Test Email';
$message = 'This is a test email sent using PHP';

$headers = array(
    'From' => '[email protected]',
    'Reply-To' => '[email protected]',
    'Subject' => $subject,
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset=UTF-8'
);

mail($to, $subject, $message, $headers);

?>

This code is simpler and more straightforward, but it's also less flexible and less customizable than the previous example.