June 6, 2019
How to send email using PHP?
Sending emails in PHP are very common. PHP has pre inbuilt mail() function. You can send email using PHP mail() function easily.
Basic syntax of mail function in PHP given below:-
mail(to, subject, message, headers, parameters)
Let’s understand the parameters mentioned in mail function.
To: used for Recipient email id. Subject: used for email subject line. Message: used for the email message. Headers: headers parameter is optional, in which we can set From, CC, BCC etc. Parameters: used for extra parameter. |
Hope you understand the mail function, now you can find below the plain email code to send email using PHP through the HTML web form.
Sending plain text email using PHP mail function:-
<?php $to = "user@gmail.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: info@website.com"; // Sending email if(mail($to, $subject, $message, $headers)){ echo 'Your mail has been sent successfully.'; } else{ echo 'Unable to send email. Please try again.'; } ?>
Sending HTML Formatted email using web form:-
<?php $to = 'user@gmail.com'; $from = 'info@website.com'; $subject = 'HTML Formatted Text Email'; // To send HTML mail, the Content-type header need to set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Create email headers $headers .= 'From: '.$from."\r\n". 'Reply-To: '.$from."\r\n" . 'X-Mailer: PHP/' . phpversion(); // Compose a simple HTML email message $message = '<html><body>'; $message .= '<h2 style="color:#f40;">Hi User!</h2>'; $message .= '<p style="color:#080;font-size:18px;">This is HTML Formatted text email message.</p>'; $message .= '</body></html>'; // Sending email if(mail($to, $subject, $message, $headers)){ echo 'Your mail has been sent successfully.'; } else{ echo 'Unable to send email. Please try again.'; } ?>