Използване на 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 /последно   -  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 до:

а. Удобно споделяне на стойности по подразбиране в моята кодова база; и
b. Правете разлика между разработка и производство.

Изглежда така:

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