PHP发送邮件的问题

时间:2013-07-07 20:50:54

标签: php email

我在通过PHP从本地服务器发送邮件时遇到问题。我正在使用easyPHP运行localserver。我基本上试图在本地服务器上测试它,然后使用此表单提交到我的网站。

<?php
    $error = false;
    $sent = false;

    if(isset($_POST['submit'])) {
        if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
            $error = true;
        } 
        else {

            $to = "myusername@gmail.com";

            $name = trim($_POST['name']);
            $email = trim($_POST['email']);
            $comments = trim($_POST['comments']);

            $subject = "Contact Form";

            $message =  "Name: $name \r\n Email: $email \r\n Comments: $comments";
            $headers = "From:" . $name;

            $mailsent = mail($to, $subject, $message, $headers);

            if($mailsent) {
                $sent = true;
            }
       }
  }
?>

<?php if($error == true){ ?>
<p class="error">Text</p>
<?php } if($sent == true) { ?>
<p class="sent">Text</p>
<?php } ?>  
<div id="form">
    <form name="contact" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <fieldset>
            <h4>Contact Me!</h4>
            <label for="name">Name:</label>
                <input type="text" name="name" id="name"/>
                <label for="email"/>Email:</label>
                <input type="text" name="email" id="email"/>
                <label for="comments" id="comments">Comments:</label>
                <textarea name="comments" id=""></textarea>
                <fieldset>
                <input class="btn" type="submit" name="submit"  class="submit" value="Send email"/>
                <input class="btn" type="reset" value="Reset"/>            
                </fieldset> 
        </fieldset>
    </form>
</div>

我更改了php.ini的设置

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

但是,我仍然收到错误邮件():SMTP服务器响应:530 5.7.0必须首先发出STARTTLS命令。 dg3sm18559983pbc.24 - gsmtp

1 个答案:

答案 0 :(得分:0)

dskanth的解决方案对我有用。 SwiftMailer效果很好。

<?php
require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
  ->setUsername('GMAIL_USERNAME')
  ->setPassword('GMAIL_PASSWORD');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(array('abc@example.com' => 'ABC'))
  ->setTo(array('xyz@test.com'))
  ->setBody('This is a test mail.');

$result = $mailer->send($message);
?>