无法使用php mail功能代码

时间:2017-01-05 10:56:46

标签: php

我尝试使用php mail()函数从php发送电子邮件。 每当我尝试发送电子邮件时,它都会显示错误消息。我不知道出了什么问题。这是我的代码。谁能告诉我出了什么问题?

$message = "<html><body>";
    $message .= "<table rules='all'>";
    $message .= "<tr><td><strong>Name: Ramya</strong> </td></tr>";
    $message .= "<tr><td><strong>Email: ramyaroy</strong> </td></tr>";
    $message .= "</table>";
    $message .= "</body></html>";       

    $to = 'ramya@example.com';
    $email='vinay@example.net';

    $subject = 'Website Change Reqest';

    $headers = "From:".$email.PHP_EOL;
    $headers .= "Reply-To:".$email.PHP_EOL;
    $headers .= "MIME-Version: 1.0".PHP_EOL;
    $headers .= "Content-Type: text/html; charset=ISO-8859-1".PHP_EOL;

    if (mail($to, $subject, $message, $headers)) {
      echo 'Your message has been sent.';
    } else {
      echo 'There was a problem sending the email.';
    }

2 个答案:

答案 0 :(得分:1)

<?php
/*
    Below code works on live and local both server , also on SSL
    which I describe all options on comments
    you need to set SMTP server username and password ,
    this is same as your google email id and password

*/

/* You need to download php-mailer class 
 https://github.com/PHPMailer/PHPMailer */

define('SMTP_USERNAME','your smtp username');
define('SMTP_PASSWORD','password');
define('FROM_EMAIL','from email');
define('ADMIN_EMAIL','replay to email');
define('SITE_NM','your site name');

print_r(sendEmail('john.doe@gmail.com','Lorem Ipsum','anything....'));

function sendEmail($to, $subject, $message) {

    require_once("class.phpmailer.php");

    // create a new object

    $mail = new PHPMailer(); 

    // enable SMTP
    $mail->IsSMTP();

    // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPDebug = 0;

    // authentication enabled
    $mail->SMTPAuth = true;

    //mail via gmail
    //$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
    //$mail->Host = "smtp.gmail.com";
    //$mail->Port = 465; // or 587
    //mail via hosting server
    $mail->Host = SMTP_HOST;

    if (SMTP_HOST == 'smtp.gmail.com') {
        $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
        $mail->Port = 465; // or 58
    }else{
        $mail->Port = 587; // or 58
    }

    $mail->IsHTML(true);
    $mail->Username = SMTP_USERNAME;
    $mail->Password = SMTP_PASSWORD;
    //$mail->SetFrom(SMTP_USERNAME);
    $mail->SetFrom(FROM_EMAIL);
    $mail->AddReplyTo(ADMIN_EMAIL, SITE_NM);
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->AddAddress($to);
    // to add bcc mail list
    $mail->AddBCC("example@gmail.com", "your name");
    $mail->AddBCC("example2@gmail.com", "XXX XXXXX");
    $result = true;
    if (!$mail->Send()) {
        //echo "Mailer Error: " . $mail->ErrorInfo;
        $result = false;
    }
    return $result;
}



?>

答案 1 :(得分:0)

代码中没有错误。

问题可能是因为你的托管。通常,托管帐户将允许仅从该域帐户发送邮件。

将$ email更改为vinay @ [your_domain_name] .com

尝试后请告诉我。