Want to create an awesome PHP script? but don’t know how to send mail in PHP.
Now you don’t need to worry anymore because today I will not teach you how to send emails using PHP but also clear all your doubts regarding PHP mail function. Don’t hesitate to ask your doubts in the comments section below.
Table Of Contents
Basic Example Of PHP Script To Send Emails
The PHP mail function is pretty easy to understand it includes has only three parameters required which are as follows –
- Email (email address of the person who has to receive the email)
- Subject (subject of your email)
- Body (the context of your email)
So to send your email we could use this code.
<?php // Simple PHP Email Script Example mail("email@example.com","this is my subject", " Hello, \n ...... Thank you") ; ?>
Sending Email From PHP Email Script Using Variables Example
Now I will show you an example of a PHP script to send emails by using PHP variables.
<?php // Simple PHP Email Script Example $to = "firstname.lastname@example.org" ; $subject = "Your Email Subject" ; $body = "Hello, ...... Thank You." // the context/body of your email // Make sure that none of your lines exceed 70 characters $body = wordwrap($body,70); mail($to,$subject,$body) ; ?>
This code is similar to our previous code we have just used variables instead of directly writing arguments to our PHP mail() function.
The only thing that we added up to the code was that we used the wordwrap() to ensure that our body text doesn’t exceed 70 characters.
Sending Emails To Multiple Recipients At Once.
If you are developing an awesome web application you might need to send emails to multiple recipients. Using a loop for doing this is not a good approach.
Therefore you can do something like this to send the same email to multiple recipients.
<?php // Sending same email to multiple recipients $to = "email@example.com , firstname.lastname@example.org , email@example.com =" ; $subject = "Your Email Subject" ; $body = "Hello, ...... Thank You." // the context/body of your email // Make sure that none of your lines exceed 70 characters $body = wordwrap($body,70); mail($to,$subject,$body) ; ?>
Basically, you just have to add all your emails to the $to variable using the “, ” separator.
These were the basics of sending an email using the PHP mail() function. If you need you may also read the documentation of the PHP mail function over here.
I hope you may have liked the post and if the post did help you please don’t forget it to share with your web developer friends.