All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Send Mail Using SMTP In PHP Example

Last Updated : Mar 11, 2024

Send Mail Using SMTP In PHP Example

In this article we will show you the solution of send mail using smtp in PHP example, SMTP is a protocol for transferring emails (SMTP). E-mail is transmitted from one user to another using the TCP/IP protocol SMTP.

A push method pushes the email to the destination mail server, while a POP or IMAP method retrieves the email. It is necessary to know the hostname, user name, password, and port number for the SMTP server.

In PHP, we use the PHPMailer Library to send emails via an SMTP server. This means that we should include PHPMailer in the email-sending script.

PHP offers two methods of sending emails - the default PHP mail () function and the PHPMailer library.

Step By Step Guide On Send Mail Using SMTP In PHP Example :-

<?php
function sanitize_my_email($field) {
    $field = filter_var ($field, FILTER_SANITIZE_EMAIL);
    if (filter_var ($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}
$to_email = 'name @ company. com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: no-reply @ company. com';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
    echo "Invalid input";
} else {
//send email
    mail ($to_email, $subject, $message, $headers);
    echo "This email is sent using PHP Mail";
}
?>
  1. The short tags start with "<?" and end with "?>".
  2. “filter_var (…)” is the validation and sanitization function used as “$field” is the value of the field to be filtered.
  3. Then we use the if and statement for executing the true and false values.
  4. FILTER_VALIDATE_EMAIL – it returns true for valid email addresses and false for invalid email addresses.
  5. We use the filter for creating a custom function that validates and sanitizes the email address using the filter_var built-in function. Filter_var function.
  6. “$subject” is the email subject
  7. “$message” is the message to be sent.
  8. Since echo () isn't actually a function, you can use parentheses without using parentheses.
  9. Then the program is closed for the execution of output.

Conclusion :-

PHP's filter_var () function facilitates the sanitization and validation of data, which are essential to send secure emails.

I hope this article on send mail using smtp in PHP example helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Dikshita

Passionate Electronics and Communication Engineering student with expertise in web development (HTML, CSS, JS,PHP, Bootstrap, React.js) and content writing. Eager problem solver and tech enthusiast, adept at creating engaging web experiences.

Follow Dikshita On Linkedin 🡪