PHP Sending Emails

PHP mail() function is used to send eamils. We can send text email, HTML email, attachments with email using PHP mail() function.

PHP Syntax :

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

Parameters,

$to - Required. Receiver, or receivers of the mail.
$subject - Required. Subject of the email to be sent.
$message - Required. Defines the message to be sent.
$headers - Optional. Specifies additional headers, like From, Cc, and Bcc. Multiple extra headers should be separated with a CRLF (\r\n).
$extra_parameters - Optional. Additional parameter can be used to the sendmail program like the one defined in the sendmail_path configuration setting. (Example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option)

Email Configuration in php.ini

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section texted [mail function].

Configure smtp port, smtp server, send mail from, send email path , header as per as below in php.ini file

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP=localhost
; http://php.net/smtp-port
smtp_port=25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail().
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header=On

; The path to a log file that will log all mail() calls. Log entries include
; the full path of the script, line number, To address and headers.
;mail.log =
; Log mail to syslog (Event Log on Windows).
;mail.log = syslog

Sending Simple Email

You can send simple email as per as below example.

PHP Example : 

<?php

$msg = "Learn PHP by aryatechno. \n Learn HTML by aryatechno.";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

// send email
if(mail("[email protected]","Learn Tutorials",$msg))
{
    echo "Email is sent successfully.";
    
}else {
    echo "Email is not sent successfully.";
}
?>

Output:

Email is sent successfully.

 

Click here to Learn PHP Sending HTML email

Click here to PHP Sending attachments with email

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

91890