跳至内容

欢迎!

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.

此问题已终结
作为版主,您可以批准或拒绝该答案。
接受 拒绝
54 查看

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.

形象
丢弃

您的回复

请大家尽量给个实质性的回答。如果您想回答这个问题或发表评论,只需 使用评论工具。请记住,您可以随时修改您的答案。 - 不用重复回答同样的问题。另外,请不要忘记投票 - 它确实有助于选择最好的问题和答案!

相关帖文 回复 查看 活动
0
3月 25
47
0
3月 25
31
0
2月 25
40
0
2月 25
72
1
4月 24
131