Mail.php 和 Smtp 身份验证问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11477902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:36:20  来源:igfitidea点击:

Mail.php & Smtp Authentication Issue

phpsmtp

提问by junaidkaps

I've been trying to utilize a mail.php file from the jquery contactable plugin (found on google!) to use on my website. Although the script provided is fairly simple I'm running into issues with integrating it with my Host's SMTP requirement. Here is the original script without SMTP authentication:

我一直在尝试利用 jquery 可联系插件(在 google 上找到!)中的 mail.php 文件在我的网站上使用。尽管提供的脚本相当简单,但我在将其与主机的 SMTP 要求集成时遇到了问题。这是没有 SMTP 身份验证的原始脚本:

<?php
    // Assign contact info
    $name = stripcslashes($_POST['name']);
    $emailAddr = stripcslashes($_POST['email']);
    $issue = stripcslashes($_POST['issue']);
    $comment = stripcslashes($_POST['message']);
    $subject = stripcslashes($_POST['subject']);    

    // Set headers
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    // Format message
    $contactMessage =  
    "<div>
    <p><strong>Name:</strong> $name <br />
    <strong>E-mail:</strong> $emailAddr <br />
    <strong>Issue:</strong> $issue </p>

    <p><strong>Message:</strong> $comment </p>

    <p><strong>Sending IP:</strong> $_SERVER[REMOTE_ADDR]<br />
    <strong>Sent via:</strong> $_SERVER[HTTP_HOST]</p>
    </div>";

    // Send and check the message status
    $response = (mail('[email protected]', $subject, $contactMessage, $headers) ) ? "success" : "failure" ;
    $output = json_encode(array("response" => $response));

    header('content-type: application/json; charset=utf-8');
    echo($output);

?>

I've tried using suggestions from Google and played around with it for hours. Here is the latest version based on my nil-understanding of php thus far. -__- (Based on this: http://blog.geek4support.com/php-mail-script-with-smtp-authentication-how-to-send-mails-by-php-mail-script-using-smtp-authetication/)

我试过使用 Google 的建议并玩了几个小时。这是迄今为止基于我对 php 的零理解的最新版本。-__-(基于此:http: //blog.geek4support.com/php-mail-script-with-smtp-authentication-how-to-send-mails-by-php-mail-script-using-smtp-认证/)

<?php
 require_once "Mail.php";

    // Assign contact info
    $name = stripcslashes($_POST['name']);
    $emailAddr = stripcslashes($_POST['email']);
    $issue = stripcslashes($_POST['issue']);
    $comment = stripcslashes($_POST['message']);
    $subject = stripcslashes($_POST['subject']);    


 $host = "mail.mywebsite.com";
 $username = "[email protected]";
 $password = "mymailpassword";

    // Set headers
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    // Format message
    $contactMessage =  
    "<div>
    <p><strong>Name:</strong> $name <br />
    <strong>E-mail:</strong> $emailAddr <br />
    <strong>Issue:</strong> $issue </p>

    <p><strong>Message:</strong> $comment </p>

    <p><strong>Sending IP:</strong> $_SERVER[REMOTE_ADDR]<br />
    <strong>Sent via:</strong> $_SERVER[HTTP_HOST]</p>
    </div>";

 $smtp = Mail::factory('smtp',
   array ('host' => $host,
     'auth' => true,
     'username' => $username,
     'password' => $password));


 $response = ($smtp->send('[email protected]', $subject, $contactMessage, $headers))  ? "success": "failure";
$output = json_encode(array("response" => $response));  
    header('content-type: application/json; charset=utf-8');
    echo($output);

 ?>

I've actually run into a bit of a problem. My host doesn't support PHPMailer :-(. Only PearMail with SMTP. They have suggested tweaking the code listed above and incorporating my existing one with it. Exactly, what I've been trying to do before posting this online. Back to square 1, any ideas?

我实际上遇到了一些问题。我的主机不支持 PHPMailer :-(。只有 PearMail 和 SMTP。他们建议调整上面列出的代码并将我现有的代码与它结合起来。正是,在网上发布之前我一直在尝试做的事情。回到正方形1、有什么想法吗?

Comments, suggestions, anything would be most appreciated! :-)

评论,建议,任何事情都将不胜感激!:-)

回答by gosukiwi

For sending mails, try PHPMailer, it's tested, everybody uses it, and it just works. It also has a lot of features and configuration options.

对于发送邮件,请尝试PHPMailer,它经过测试,每个人都使用它,并且可以正常工作。它还具有许多功能和配置选项。

The latest version is this one, as for sending mails using SMTP with PHPMailer this is all the code you need

最新版本是这个,至于使用 SMTP 和 PHPMailer 发送邮件这是您需要的所有代码

// Data received from POST request
$name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$issue = stripcslashes($_POST['issue']);
$comment = stripcslashes($_POST['message']);
$subject = stripcslashes($_POST['subject']);   

// Send mail
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP

// SMTP Configuration
$mail->SMTPAuth = true;                  // enable SMTP authentication
$mail->Host = "myhost"; // SMTP server
$mail->Username = "[email protected]";
$mail->Password = "yourpassword";            
//$mail->Port = 465; // optional if you don't want to use the default 

$mail->From = "[email protected]";
$mail->FromName = "My Name";
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($issue . "<br /><br />" . $comment);

// Add as many as you want
$mail->AddAddress($emailAddr, $name);

// If you want to attach a file, relative path to it
//$mail->AddAttachment("images/phpmailer.gif");             // attachment

$response= NULL;
if(!$mail->Send()) {
    $response = "Mailer Error: " . $mail->ErrorInfo;
} else {
    $response = "Message sent!";
}

$output = json_encode(array("response" => $response));  
header('content-type: application/json; charset=utf-8');
echo($output);

回答by G O'Rilla

This my test script for getting around the disabled PHP mail() function. It uses PearMail. The print statements are for testing in a browser, you may want to remove them.

这是我绕过禁用的 PHP mail() 函数的测试脚本。它使用 PearMail。打印语句用于在浏览器中进行测试,您可能需要删除它们。

<?php
/*
 * Script to send an email as the PHP mail() function is disabled.
 * The hosting company requires SMTP authentication etc.
 * need to install the pear mail package in the cPanel
 *
 * Use the [email protected] as the sending/from email 
 * (or maybe the welcome one?)
 *
 * Sunday, 11 october 2015 
 * G O'Rilla
 *
 * 
 */
 function pearMail( $e_mail, $subject, $content ) {
 /*
 // To ignore the Strict Standards (which are non fatal) change your error 
 // reporting level in the php.ini file or better, inline with error_reporting()
 */
 error_reporting(E_ERROR | E_PARSE);
# To use installed modules (cPanel - PHP Extensions and Applications Package Installer)
# Add “/home/myaccount/php” to the include path. To do this, add the following code to your script:
ini_set("include_path", '/home/myaccount/php:' . ini_get("include_path")  );

require_once 'Mail.php';

#Server host only allows SMTP authentication
/*
 * Use below setting for SMTP Authentication.
 * --
 * SMTP Host : myserver.com
 * SMTP User : Use domain email Address [[email protected]]
 * SMTP Password : Use domain email password.
 * SMTP Port : 25 
*/
//print "Start Script <br>";
$params = array();
$params["host"] = “myserver.com";              # - The server to connect. Default is localhost - use your domain name.
$params["port"] = 25;                            # - The port to connect. Default is 25.
// Error: return fron mailer: Failed to set sender: [email protected] 
//[SMTP: Invalid response code received from server (code: 550, response: 
// Access denied - Invalid HELO name (See RFC2821 4.1.1.1))] 
// sever requires authentication so TRUE 
$params["auth"] = TRUE;                         # - Whether or not to use SMTP authentication. Default is FALSE.
$params["username"] = "[email protected]";  #- The username to use for SMTP authentication.
$params["password"] = “********”;                #- The password to use for SMTP authentication.

print_r ( $params );
//Other parameters assuming default values will do
#$params["localhost"] - The value to give when sending EHLO or HELO. Default is localhost
#$params["timeout"] - The SMTP connection timeout. Default is NULL (no timeout).
#$params["verp"] - Whether to use VERP or not. Default is FALSE.
#$params["debug"] - Whether to enable SMTP debug mode or not. Default is FALSE.
# Mail internally uses Net_SMTP::setDebug .
#$params["persist"] - Indicates whether or not the SMTP connection should persist over multiple calls to the send() method.
#$params["pipelining"] - Indicates whether or not the SMTP commands pipelining should be used.

 $rc = $mailer = & Mail::factory( "smtp", $params ); # creates a mailer instance
 if ( $rc == NULL ) {
     print "<br>Failed to create mail instance <br>";
 }
 else {
     print "<br>mail instance created <br>";
 }

 $recipients = $email; //'[email protected]';

$headers['From']    = '[email protected]'; 
$headers['To']      = $email; //'[email protected]';   // Input param
$headers['Subject'] = $subject;  //'TAF: Test message';        // Input param

$body = $content;  //'This is a test using PEAR mailer';       // Input param

print ( "recipients: " . $e_mail . " subject: " . $subject . " content: " . $content . "<br>");

$rc = $mailer->send( $recipients, $headers, $body );
print ( "return from mailer; " . $rc );

//print "<br>End Script";
 }
?>