Linux - 使用PHP Mail从SMTP服务器发送

时间:2013-10-18 15:38:22

标签: php linux email

好的,基本上我一直在编辑我的脚本以使用SMTP邮件服务器而不是使用php邮件继续使用我一直在使用的代码

<?php
if (!$_POST) exit;

$email = $_POST['email'];

//$error[] = preg_match('/\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if (!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" . "@" . "([a-z0-9]+([\.-][a-z0-9]+)*)+" . "\\.[a-z]{2,}" . "$", $email)) {
    $error .= "Invalid email address entered";
    $errors = 1;
}
if ($errors == 1) 
    echo $error;
else {
    $values = array('name', 'email', 'message');
    $required = array('name', 'email', 'message');

    $your_email = "zookenetwork@gmail.com";
    $email_subject = "New Message: " . $_POST['subject'];
    $email_content = "new message:\n";

    foreach ($values as $key => $value) {
        if (in_array($value, $required)) {
            if ($key != 'subject') {
                if (empty($_POST[$value])) {
                    echo 'PLEASE FILL IN REQUIRED FIELDS';
                    exit;
                }
            }
            $email_content .= $value . ': ' . $_POST[$value] . "\n";
        }
    }

    if (@mail($your_email, $email_subject, $email_content)) {
        echo 'Message sent!';
    } else {
        echo 'ERROR!';
    }
} ?>

我已经检查过了,但我的PHP知识很糟糕,所以我有点需要我的手持

1 个答案:

答案 0 :(得分:1)

我的PHP知识有点好。

我在许多项目中使用了PHPMailer。我也只能建议你这样做。

使用PHPMailer发送邮件非常简单,如下所示: (取自PHPMailer示例页面)

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup server
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'jswan';                            // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('josh@example.net', 'Josh Adams');  // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

echo 'Message has been sent';

愿来源与你同在......