E-Mails increases your site’s traffic. E-Mails are used in websites that require E-Mail verification to Reset Passwords. There is already a mail function in PHP, but the E-Mails that are sent via PHP‘s mail function goes to SPAM folder in most of the mail services. So, developers use API services to send E-Mails that gets received on user’s Inbox. Most of the API‘s need money to use. If you are a starting developer, you need a Free service. In fact there is a free service provided by Mailgun. 10,000 E-Mails are free in every month. Isn’t that a good offer ? You can sign up free without entering any credit card details. They have their own class for sending E-Mail’s in PHP, but in this post I will be introducing you to a simple PHP function (send_mail) that will send E-Mail‘s through Mailgun‘s API service vai cURL. I will also tell you the step by step instructions from signing up to sending mails. Like any other services, you have to sign up to use the features of Mailgun. You can sign up @ https://mailgun.com/signup. Fill up the required fields and click “Create Account” button. Now you need to get the API Key. Login to your new account. Note that you need to add your domain and verify your domain. If you don’t verify your domain, you will be limited to send only 300 mails per day. So you need to verify your domain. Go to the page https://mailgun.com/cp/my_account. On the left side, you can see the API key :
You will need this API key for future use in this tutorial. Let’s move on to the send_mail function :
<?
function send_mail($email,$subject,$msg) {
$api_key="";/* Api Key got from https://mailgun.com/cp/my_account */
$domain ="";/* Domain Name you given to Mailgun */
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:'.$api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/'.$domain.'/messages');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'from' => 'Open <[email protected]>',
'to' => $email,
'subject' => $subject,
'html' => $msg
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
Don’t forget to fill the following fields : $api_key – API key got from https://mailgun.com/cp/my_account $domain – The domain name you gave in Mailgun (https://mailgun.com/cp/my_account). You can now send E-Mails using send_mail() function with the values as below :
$email - E-Mail address
$subject - Subject of E-Mail
$msg - Body of E-Mail
An example of sending email to [email protected] with subject Hello Kerala and body as Kerala is a nice place :
<?
send_mail("[email protected]", "Hello Kerala", "Kerala is a nice place.");
?>
If you encountered with any problems or have a feedback, please say it on the comments. I love to hear from you and Merry Christmas.