Skip to Content

Welcome!

This community is for professionals and enthusiasts of our products and services.
Share and discuss the best content and new marketing ideas, build your professional profile and become a better marketer together.

This question has been flagged
As a moderator, you can either validate or reject this answer.
Accept Reject
53 Views

How to send email in php?

Before sending an email, make sure the email body, sender, recipient, and subject are properly set.


(1) Body setting:

$emailBody = <<<EOD

        Name: $name<br>

        Contact Number: $contact<br>

        Email: $email<br>

        Message: Live Chat : $livechatMessage<br>

        Website: <a href="$website">$website</a>

        EOD;


(2) Sender, recipient and subject: (It is better set a parameter in backend and retrieve it to avoid hardcode)

​$emailSubject = $params->get('email_subject');

        ​$fromEmail = $params->get('from_email');

        ​$fromEmailName = $params->get('from_email_name');

        ​$toEmail = $params->get('to_email');

​$cc = $params->get('cc_email');


(3) Check sender, recipient and subject exist before sending to avoid conflict

​if (empty($toEmail) || empty($emailSubject) || empty($fromEmail)) {

            die("Error: Required email parameters are missing.");

        ​}


(4) Prepare email header (From email and from name)

​$headers = 'Content-type:text/html;charset=UTF-8' . "\r\n";

        ​$headers .= 'From: "' . $fromEmailName . '" <' . $fromEmail . '>' . "\r\n";


(5) CC email if have

​if (!empty($cc)) {

            $headers .= 'Cc: ' . $cc . "\r\n";

        ​}


(6) Now you can send your email via mail

$mailSent = mail($toEmail, $emailSubject, $emailBody, $headers);


(7) Last, echo response to check email send success or not

​if ($mailSent) {

            $response = [

                "success" => true,

                "message" => "Email sent successfully!"

            ];

        ​} else {

            $response = [

                "success" => false,

                "message" => "Error: Email could not be sent."

            ];

        ​}

        ​// Return JSON response

        ​echo json_encode($response);


Summary:

It is better to build the email-sending function in a helper or plugin so that it can be called only when needed.

Avatar
Discard

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

Related Posts Replies Views Activity
0
Mar 25
46
0
Mar 25
30
0
Feb 25
39
0
Feb 25
70
1
Apr 24
130