Использование PHPMailer и Amazon SES

Я использую Amazon SES. Я пытаюсь отправить электронное письмо из своего скрипта PHP с помощью PHPMailer.

Я уже проверил два идентификатора электронной почты и пытался отправлять почту с и на эти идентификаторы электронной почты. Но это вызывает следующую ошибку.

ОШИБКА

SERVER -> CLIENT: 220 email-smtp.amazonaws.com ESMTP SimpleEmailService-693939519  QEPGeLndQQq5vJ53VMXU
CLIENT -> SERVER: EHLO localhost
SERVER -> CLIENT: 250-email-smtp.amazonaws.com250-8BITMIME250-SIZE 10485760250- STARTTLS250-AUTH PLAIN LOGIN250 Ok
CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 220 Ready to start TLS
CLIENT -> SERVER: EHLO localhost
SERVER -> CLIENT: 250-email-smtp.amazonaws.com250-8BITMIME250-SIZE 10485760250-STARTTLS250-AUTH PLAIN LOGIN250 Ok
CLIENT -> SERVER: AUTH LOGIN


SMTP NOTICE: EOF caught while checking if connected
SMTP connect() failed.
Mailer Error: SMTP connect() failed.

Вот мой PHP-скрипт:

<?php

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have   access to that
date_default_timezone_set('Etc/UTC');

require 'phpmailer/PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer();

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging

$mail->SMTPDebug = 2;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'email-smtp.us-east-1.amazonaws.com';

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
// I tried PORT 25, 465 too
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "SES Secret ID";

//Password to use for SMTP authentication
$mail->Password = "SES Secret Key";

//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'sender');

//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'receiver');

//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';


$mail->Body = 'This is a plain-text message body';
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
?>

Я перепробовал так много решений, которые нашел в Интернете, особенно stackoverflow.

Ничего не работает !!


person AKA    schedule 06.05.2014    source источник
comment
Почему вы используете PHPMailer, когда Amazon предоставляет PHP SDK? docs.aws.amazon.com/aws-sdk-php/guide / latest   -  person ashack    schedule 06.05.2014
comment
Спасибо, что напомнили мне о PHP SDK .. !! У меня получилось !! Спасибо !!   -  person AKA    schedule 07.05.2014


Ответы (5)


Мне удалось заставить это работать.

$ mail-> Port = 587; 

// Username to use for SMTP authentication - use full email address for gmail 
$ mail-> Username = "Amazon SES Secret ID"; 

// Password to use for SMTP authentication 
$ mail-> Password = "Amazon SES Secret Key"; 

Чтобы создать учетные данные, перейдите по этой ссылке: https://console.aws.amazon.com/ses/home?region=us-east-1#smtp-settings:

Чтобы отправить электронное письмо, оба отправляющие электронную почту, так как полученное вами электронное письмо обязательно должно быть зарегистрировано и проверено Amazon. (https://console.aws.amazon.com/ses/home?region=us-east-1#verified-senders-mail :)

По любым вопросам вы можете найти меня. Надеюсь я помог

person Victor Gomes    schedule 04.09.2014

У меня была та же проблема, я мог заставить ее работать только тогда, когда я изменил имя хоста, чтобы начать с ssl: //. Итак, это работает:

$mail = new PHPMailer;

$ mail-> SMTPDebug = 3; // Включить подробный вывод отладки

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'ssl://email-smtp.us-west-2.amazonaws.com';  // Specify main and backup SMTP servers

$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'blah';                 // SMTP username
$mail->Password = 'blahblah';                           // SMTP password


$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 443;                  
person leon    schedule 14.12.2015
comment
К вашему сведению: при использовании в инстансе EC2 внутри Amazon VPC добавление ssl: // фактически приводит к тому, что он НЕ работает. - person leiavoia; 29.08.2017
comment
Это работает, просто убедитесь, что ваш порт - 443 и tls. - person Vael Victus; 20.11.2017

Чтобы успешно отправлять электронную почту с помощью PHPMailer + AWS SES, мне пришлось использовать следующие настройки:

$mail->IsSMTP(true);
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host= "email-smtp.eu-west-1.amazonaws.com"; /** Edit to the region you're using **/
$mail->Port = 587;
$mail->Username = 'MYACCESSKEYID';
$mail->Password = 'MYSECRETACCESSKEY'

Сделав еще один шаг, я расширил класс PHPMailer до:

а. Удобно использовать значения по умолчанию для всей моей кодовой базы; и
б. Различают разработку и производство.

Выглядит это так:

<?php

/* MYMAILER
 * Our own custom mailer class. Makes it easier to use default settings for all things email.
 *
 * Rules of thumb:
 * - Keep bounce rate under 5%.
 * - Keep complaint rate under 0.1%
 *
 * Tips:
 * - To check that the SPF and DKIM settings are correct, simply send an email (e.g.: to Gmail) and check its headers.
 * - Check URIBL.com and SURBL.org to check my links are not blacklisted.
 *
 * Documentation:
 * - Best practices: http://media.amazonwebservices.com/AWS_Amazon_SES_Best_Practices.pdf -- includes iSP postmaster pages for many ISPs on last page.
 * - Header fields: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/header-fields.html
 * ================================================================================= */
class MyMailer extends PHPMailer {
    public function __construct() {
        parent::__construct();


        $this->CharSet = 'UTF-8';

        if ( defined('APP_DEVELOPMENT') ) {

            /**
             * Local development. e.g.: mhsendmail + MailHog.
             **/
            $this->IsMail(); /** PHPMailer's default, but let's be explicit here. **/

        } else {

            /**
             * Production, i.e.: Amazon's SES.
             * The `Username` and `Password` SMTP credentials are AWS `Access key ID`/`Secret access key` created specifically for Amazon SES.
             *  Cf. `AWS Console › SES › SMTP Settings` to create them.
             *  Cf. `AWS Console › IAM › Users` to list the access keys (passwords only available when creating credentials.)
             *      CAREFUL! Creating new access keys for the SMTP user via IAM is technically possible but it does NOT work!
             *      Instead, use the `SES › SMTP Settings` interface.
             * Remember that any FROM email has to be verified (either via domain or via email inbox.)
             **/
            $this->IsSMTP(true);
            $this->SMTPAuth = true;
            $this->SMTPSecure = "tls";

            $url = parse_url( getenv('SMTP_URL') );
            if ( $url == FALSE ) {
                $log->error( 'Failed to parse SMTP_URL' );
            }
            $this->Host= $url['host'];
            $this->Port = $url['port'];
            $this->Username = $url['user'];
            $this->Password = $url['pass'];

        }


        /**
         * Default values common to local + SES. Constant defined in config.php
         * Used defensively only.
         * Those values would and should be overwritten by the code.
         * Apparently, the order matters (TBC.)
         **/
        $this->AddReplyTo( MAIL_DEFAULT_ADDREPLYTO );
        $this->FromName = MAIL_DEFAULT_FROMNAME;
        $this->From = MAIL_DEFAULT_FROM;
    }
}

?>

Надеюсь, это поможет.

person Fabien Snauwaert    schedule 15.08.2017

Приведенная ниже запись помогла мне решить проблему, с которой я столкнулся, из-за того, что мои электронные письма не были доставлены. Хотя у меня были все остальные конфигурации, но я не мог понять, почему он не работает (не разработчик PHP и, следовательно, его нелегко понять).

$mail->SMTPSecure = 'tls';
person Anil    schedule 03.04.2015

Просто увеличьте квоту лимита отправки почты на AWS SES

У меня была такая же проблема с AWS ec2, а затем, выполнив поиск решения, я понял, что AWS SES отправляет письма только в том случае, если получатели также проверены, если вы находитесь в песочнице Amazon.

Если вы хотите отправить почту на другой почтовый идентификатор (который не подтвержден), вам необходимо увеличить квоту лимита отправки. просто следуйте инструкциям, указанным в URL-адресе

http://docs.aws.amazon.com/ses/latest/DeveloperGuide/submit-extended-access-request.html.

person Akash Ahire    schedule 09.03.2017