Programing

PHP 메일러를 통해 Gmail SMTP 서버를 사용하여 이메일 보내기

crosscheck 2020. 10. 26. 07:42
반응형

PHP 메일러를 통해 Gmail SMTP 서버를 사용하여 이메일 보내기


PHP Mailer를 통해 Gmail SMTP 서버를 사용하여 이메일을 보내고 싶습니다 .

이것은 내 코드입니다

<?php
require_once('class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'MyUsername@gmail.com';
$mail->Password = 'valid password';
$mail->SMTPAuth = true;

$mail->From = 'MyUsername@gmail.com';
$mail->FromName = 'Mohammad Masoudian';
$mail->AddAddress('anotherValidGmail@gmail.com');
$mail->AddReplyTo('phoenixd110@gmail.com', 'Information');

$mail->IsHTML(true);
$mail->Subject    = "PHPMailer Test Subject via Sendmail, basic";
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
$mail->Body    = "Hello";

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

하지만 다음과 같은 오류가 발생합니다.

Mailer Error: SMTP Error: The following recipients failed: anotherValidGmail@gmail.com

SMTP server error: SMTP AUTH is required for message submission on port 587

내 도메인은 vatandesign.ir입니다.


$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "email@gmail.com";
$mail->Password = "password";
$mail->SetFrom("example@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("email@gmail.com");

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

위의 코드는 테스트를 거쳐 저를 위해 작동했습니다.

당신이 필요로 할 수 있습니다. $mail->SMTPSecure = 'ssl';

또한 문제가 발생할 수 있으므로 해당 계정에 대해 2 단계 인증이 켜져 있지 않은지 확인하십시오.

업데이트 됨

$ mail-> SMTP를 다음과 같이 변경할 수 있습니다.

$mail->SMTPSecure = 'tls';

일부 SMTP 서버가 연결을 차단한다는 점은 주목할 가치가 있습니다. 일부 SMTP 서버는 연결을 지원하지 않습니다 SSL(또는 TLS).


그래서 제 자신의 "SMTP 연결 실패"오류를 해결했고 다른 사람에게 도움이 될 경우를 대비하여 솔루션을 게시하고 싶었습니다.

PHPMailer 예제 gmail.phps 파일에 제공된 정확한 코드를 사용했습니다. MAMP를 사용하는 동안 간단히 작동했으며 개인 서버로 옮겼을 때 SMTP 연결 오류가 발생했습니다.

내가 읽은 모든 Stack Overflow 답변과 PHPMailer의 모든 문제 해결 문서에서 PHPMailer의 문제가 아니라고 말했습니다. 그것은 서버 측의 설정 문제였습니다. 다른 포트 (587, 465, 25)를 시도하고 'SSL'및 'TLS'암호화를 시도했습니다. 내 php.ini 파일에서 openssl이 활성화되어 있는지 확인했습니다. 방화벽 문제가 없는지 확인했습니다. 모든 것이 확인되었지만 여전히 아무것도 없습니다.

해결책은이 줄을 제거해야한다는 것입니다.

$mail->isSMTP();

이제 모든 것이 작동합니다. 이유는 모르겠지만 작동합니다. 나머지 코드는 PHPMailer 예제 파일에서 복사하여 붙여 넣습니다.


2 단계 인증이 활성화 된 경우 이메일 계정의 비밀번호 대신 사용할 애플리케이션 비밀번호를 설정해야합니다.

다음 안내에 따라 애플리케이션 비밀번호를 생성 할 수 있습니다. https://support.google.com/accounts/answer/185833

그런 다음 $mail->Password애플리케이션 비밀번호를 설정 합니다.


서버가 Gmail SMTP 서버에 연결하지 못하는 것 같습니다. 다음은이 문제를 해결하기위한 몇 가지 힌트입니다. 1) SSL이 PHP에 올바르게 구성되었는지 확인합니다 (이를 처리하는 모듈은 기본적으로 PHP에 설치되지 않습니다. phph.ini에서 구성을 확인해야합니다). 2) 방화벽이 필요한 포트 (여기서는 465 또는 587)로 발신 전화를 허용하는지 확인합니다. 그렇게하려면 텔넷을 사용하십시오. 포트가 열리지 않으면 sysdmin의 지원이 필요합니다. 이 문제를 빨리 해결하시기 바랍니다!


링크를 열고 Google 서버가 알 수없는 서버의 모든 시도를 차단하는 지침을 따르십시오. 따라서 보안 문자를 클릭하면 모든 것이 정상입니다.


Google은 스팸 발송자를 막기 위해 사용 가능한 사용자 정보에 따라 Gmail 계정을 다르게 취급합니다.

전화 확인을 할 때까지 SMTP를 사용할 수 없었습니다. 다시 확인하기 위해 다른 계정을 만들었고 확인했습니다.


이 코드는 나를 위해 잘 작동합니다.

    $mail = new PHPMailer;
    //Enable SMTP debugging. 
    $mail->SMTPDebug = 0;
    //Set PHPMailer to use SMTP.
    $mail->isSMTP();
    //Set SMTP host name                          
    $mail->Host = $hostname;
    //Set this to true if SMTP host requires authentication to send email
    $mail->SMTPAuth = true;
    //Provide username and password     
    $mail->Username = $sender;
    $mail->Password = $mail_password;
    //If SMTP requires TLS encryption then set it
    $mail->SMTPSecure = "ssl";
    //Set TCP port to connect to 
    $mail->Port = 465;
    $mail->From = $sender;  
    $mail->FromName = $sender_name;
    $mail->addAddress($to);
    $mail->isHTML(true);
    $mail->Subject = $Subject;
    $mail->Body = $Body;
    $mail->AltBody = "This is the plain text version of the email content";
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    }
    else {
           echo 'Mail Sent Successfully';
    }

 $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

cPanel을 사용하는 경우 SMTP로 외부 서버로 보낼 수있는 작은 상자를 클릭하면됩니다.

CPanel> Tweak Settings> All> "발신 SMTP를 root, exim 및 mailman으로 제한 (FKA SMTP Tweak)"에 로그인합니다.

여기에 대답 :

GMail 및 phpMailer로 전송할 때 "서버에서 비밀번호가 허용되지 않음 : 535 잘못된 인증 데이터"


Anderscc가 정확했습니다. 감사. 저에게는 효과가 있었지만 100 %는 아니 었습니다.

나는 설정해야했다

$mail->SMTPDebug = 0;

1로 설정하면 특히 일부 데이터를 json으로 다음 페이지로 전달하는 경우 오류가 발생할 수 있습니다. 예-메일이 전송되면 확인을 수행하고 json을 사용하여 ajax를 통해 데이터를 전달합니다.

I had to lower my gmail account security settings to get rid of errors: " SMTP connect() failed " and " SMTP ERROR: Password command failed "

Solution: This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).

Links that fix the problem (you must be logged into google account):

Note: You can go to the following stackoverflow answer link for more detailed reference.

https://stackoverflow.com/a/25175234


I think it is connection issue you can get code here http://skillrow.com/sending-mail-using-smtp-and-php/

include(“smtpfile.php“);
include(“saslfile.php“); // for SASL authentication $from=”my@website.com“; //from mail id

$smtp=new smtp_class;

$smtp->host_name=”www.abc.com“; // name of host
$smtp->host_port=25;//port of host

$smtp->timeout=10;
$smtp->data_timeout=0;
$smtp->debug=1;
$smtp->html_debug=1;
$smtp->pop3_auth_host=””;
$smtp->ssl=0;
$smtp->start_tls=0;
$smtp->localhost=”localhost“;
$smtp->direct_delivery=0;

$smtp->user=”smtp username”;
$smtp->realm=””;
$smtp->password=”smtp password“;

$smtp->workstation=””;
$smtp->authentication_mechanism=””;

$mail=$smtp->SendMessage($from,array($to),array(“From:$from”,”To: $to”,”Subject: $subject”,”Date: ”.strftime(“%a, %d %b %Y %H:%M:%S %Z”)),”$message”);

if($mail){
   echo “Mail sent“;
}else{
   echo $smtp->error;
}

참고URL : https://stackoverflow.com/questions/16048347/send-email-using-gmail-smtp-server-through-php-mailer

반응형