[php] PHP 페이지에서 Gmail SMTP 서버를 사용하여 이메일 보내기

PHP 페이지에서 Gmail의 SMTP 서버를 통해 이메일을 보내려고하는데이 오류가 발생합니다.

인증 실패 [SMTP : SMTP 서버는 인증을 지원하지 않습니다 (코드 : 250, 응답 : 서비스에서 mx.google.com, [98.117.99.235] 크기 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]

누구든지 도울 수 있습니까? 내 코드는 다음과 같습니다.

<?php
require_once "Mail.php";

$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <ramona@microsoft.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "smtp.gmail.com";
$port = "587";
$username = "testtest@gmail.com";
$password = "testtest";

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
 } else {
  echo("<p>Message successfully sent!</p>");
 }
?>



답변

// Pear Mail Library
require_once "Mail.php";

$from = '<fromaddress@gmail.com>';
$to = '<toaddress@yahoo.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => 'johndoe@gmail.com',
        'password' => 'passwordxxx'
    ));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');
}


답변

Swift mailer를 사용하면 Gmail 자격 증명을 통해 메일을 보내는 것이 매우 쉽습니다.

<?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);
?>


답변

귀하의 코드는 TLS (SSL)를 사용하지 않는 것으로 보입니다. 이는 TLS (SSL)를 사용하여 Google에 메일을 전달 하는 데 필요합니다 (포트 465 또는 587) .

당신은 설정 하여이 작업을 수행 할 수 있습니다

$host = "ssl://smtp.gmail.com";

코드는 호스트 이름 체계에서 ssl : //를 참조하는 이 예제 와 비슷하게 보입니다 .


답변

나는 Pear Mail을 권장하지 않습니다. 2010 년 이후로 업데이트되지 않았습니다. 또한 소스 파일을 읽으십시오. 소스 코드는 거의 구식이며 PHP 4 스타일로 작성되었으며 많은 오류 / 버그가 게시되었습니다 (Google it). Swift Mailer를 사용하고 있습니다.

Swift Mailer 는 PHP 5로 작성된 모든 웹 응용 프로그램에 통합되어 다양한 기능을 가진 전자 메일을 보내는 유연하고 우아한 객체 지향 접근 방식을 제공합니다.

SMTP, sendmail, postfix 또는 사용자 정의 전송 구현을 사용하여 이메일을 보내십시오.

사용자 이름 및 비밀번호 및 / 또는 암호화가 필요한 서버를 지원하십시오.

요청 데이터 내용을 제거하지 않고 헤더 주입 공격으로부터 보호하십시오.

MIME 호환 HTML / 멀티 파트 이메일을 보냅니다.

이벤트 중심 플러그인을 사용하여 라이브러리를 사용자 정의하십시오.

메모리 사용량이 적은 대형 첨부 파일 및 인라인 / 내장 이미지를 처리하십시오.

Swift Mailer를 다운로드 하여 서버에 업로드 할 수있는 무료 오픈 소스 입니다. 기능 목록은 소유자 웹 사이트에서 복사됩니다.

Gmail SSL / SMTP 및 Swift Mailer의 실제 예는 다음과 같습니다.

// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';

// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
    ->setUsername('username@gmail.com') // Your Gmail Username
    ->setPassword('my_secure_gmail_password'); // Your Gmail Password

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

// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
    ->setFrom(array('sender@example.com' => 'Sender Name')) // can be $_POST['email'] etc...
    ->setTo(array('receiver@example.com' => 'Receiver Name')) // your email / multiple supported.
    ->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');

// Send the message
if ($mailer->send($message)) {
    echo 'Mail sent successfully.';
} else {
    echo 'I am sure, your configuration are not correct. :(';
}

이게 도움이 되길 바란다. 행복한 코딩 … 🙂


답변

<?php
date_default_timezone_set('America/Toronto');

require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

$body             = "gdssdh";
//$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host       = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 465;                   // set the SMTP port for the GMAIL server
$mail->Username   = "user@gmail.com";  // GMAIL username
$mail->Password   = "password";            // GMAIL password

$mail->SetFrom('contact@prsps.in', 'PRSPS');

//$mail->AddReplyTo("user2@gmail.com', 'First Last");

$mail->Subject    = "PRSPS password";

//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "user2@yahoo.co.in";
$mail->AddAddress($address, "user2");

//$mail->AddAttachment("images/phpmailer.gif");      // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

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

?>


답변

SwiftMailer 는 외부 서버를 사용하여 이메일을 보낼 수 있습니다.

다음은 Gmail 서버를 사용하는 방법을 보여주는 예입니다.

require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";

//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));


//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));


//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
    "smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));


답변

질문에 나열된 코드는 두 가지 변경이 필요합니다

$host = "ssl://smtp.gmail.com";
$port = "465";

SSL 연결에는 포트 465가 필요합니다.