如何发送电子邮件? PHP代码

时间:2013-09-14 14:30:00

标签: php

这有什么问题..

我正在尝试向邮件发送邮件,但收件人未收到邮件..我的密码有什么问题?或者你有什么建议吗?请帮忙:

这是我的代码:

<?php

if(isset($_POST['subject'], $_POST['sender'], $_POST['receiver'], $_POST['body']))        {
    //Validate Subject
        if(empty($_POST['subject'])) {
            $errors[] = "Please enter a subject";
        } else{
            $subject = htmlentities($_POST['subject']);
        }

    //Validate Sender Email
        if(empty($_POST['sender'])) {
            $errors[] = "Please enter a valid eMail Address";
        } else if(strlen($_POST['sender']) > 347) {
            $errors[] = "Email is too long. Please provide a valid email address";
        } else if(filter_var($_POST['sender'], FILTER_VALIDATE_EMAIL) ===  false) {
            $errors[] = "Please provide a valid eMail address";
        }else{
            $email = "<" .htmlentities($_POST['sender']). ">";
        }

    //Validate Receiver's Email
        if(empty($_POST['receiver'])) {
            $errors[] = "Please enter a valid eMail Address";
        } else if(strlen($_POST['receiver']) > 347) {
            $errors[] = "Your email is too long. Please provide a valid email address";
        } else if(filter_var($_POST['receiver'], FILTER_VALIDATE_EMAIL) === false) {
            $errors[] = "Please provide a valid eMail address";
        }else{
            $to = "<" .htmlentities($_POST['receiver']). ">";
        }

    //Validate the Message
        if(empty($_POST['body'])) {
            $errors[] = "Please enter a message.";
        } else {
            $body = htmlentities($_POST['body']);
        }
        }

?>
<!DOCTYPE HTML>
<html>
<head>
    <title>Mail Test</title>
</head>
<body>
    <?php
    if(empty($errors) === false) {
    ?>
        <ul>
            <?php
                foreach($errors as $error) {
                    echo "<li>", $error, "</li>";
                }
            ?>
        </ul>
    <?php
    } else {
        if (isset($to, $subject, $body, $email)){
        mail($to, $subject, $body, "From: ($email)");
        echo "Message sent!";
        }
    }
    ?>
    <form method="post" action="">
        <label for="subject"> Subject: </label>
            <input type="text" id="subject" name="subject" /><br/>

        <label for="sender"> Your eMail: </label>
            <input type="text" id="sender" name="sender" /> <br/>

        <label for="receiver"> Receiver: </label>
            <input type="text" id="receiver" name="receiver" /> <br/>

        <label for="body"> Message: </label>
            <textarea id="body" name="body" cols="100" rows="20">  </textarea> <br/>
            <input type="submit" value="Send Email" />
</body>
</html>

1 个答案:

答案 0 :(得分:2)

删除()

($email)中的mail($to, $subject, $body, "From: ($email)");

读作:

mail($to, $subject, $body, "From: $email");

它现在可以使用了。的(测试)

当我最初使用() $email进行测试时,最终使用unknown sender进入垃圾邮件。

然后当我删除括号时,它现在以发件人的电子邮件地址进入我的收件箱。