如何在我的Amazon SES SendRawEmail PHP代码

时间:2015-07-07 14:24:32

标签: php amazon-web-services amazon-ses

我多次阅读Amazon SES文档并提出以下PHP代码,使用他们所谓的HTTPS查询API方法通过Amazon SES发送电子邮件,以便在不使用Amazon AWS SDK for PHP的情况下发送电子邮件。但是我遇到了InvalidSignatureException并且无法通过它。似乎我在某处可能犯了错误(1)创建请求签名或(2)选择正确的数据来生成请求签名。任何帮助修复我的代码非常感谢。我的代码如下。在不将Amazon AWS SDK包含在我的PHP代码中的情况下执行此方法非常重要。谢谢。

define("EMAIL_TO", <Amazon SES configured & verified from email id>);
define("EMAIL_FROM", <Amazon SES configured & verified from email id>);
define("SMTP_USERNAME", <AWS ACCESS KEY>);
define("SMTP_PASSWORD", <AWS SECRET ACCESS KEY>);

function amazonsesrawmailcurlpost($strToEmailId, $strEmailSubject, $strEmailBody)
{
    $strDateRFC2822 = date("r", time());

    $strRawEmailData = "From: ".EMAIL_FROM."\n";
    $strRawEmailData.= "Subject: $strEmailSubject\n";
    $strRawEmailData.= "\n";
    $strRawEmailData.= $strEmailBody;

    $strRequestContentPart = "Action=SendRawEmail";
    $strRequestContentPart.= "&Destinations.member.1=$strToEmailId";
    $strRequestContentPart.= "&RawMessage.Data=".base64_encode($strRawEmailData);
    $strRequestContentPart = urlencode($strRequestContentPart);

    $nRequestContentPartLength = strlen($strRequestContentPart);

    $strSignature = base64_encode(hash_hmac(
        "sha256",
        $strDateRFC2822,
        SMTP_PASSWORD,
        TRUE
    ));

    $rCurlToMailer = curl_init();
    curl_setopt($rCurlToMailer, CURLOPT_URL, "https://email.us-west-2.amazonaws.com/");
    curl_setopt($rCurlToMailer, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($rCurlToMailer,
        CURLOPT_HTTPHEADER,
        array(
            "POST / HTTP/1.1",
            "Host: email.us-west-2.amazonaws.com",
            "Date: $strDateRFC2822",
            "Content-Type: application/x-www-form-urlencoded",
            "Content-Length: $nRequestContentPartLength",
            "X-Amzn-Authorization: AWS3-HTTPS AWSAccessKeyId=".SMTP_USERNAME.", Algorithm=HmacSHA256, Signature=$strSignature"
        )
    );

    curl_setopt($rCurlToMailer, CURLOPT_POST, TRUE);
    curl_setopt($rCurlToMailer, CURLOPT_POSTFIELDS, $strRequestContentPart);

    $strMailerResponse = curl_exec($rCurlToMailer);
    echo $strMailerResponse;
    curl_close($rCurlToMailer);
}
amazonsesrawmailcurlpost(EMAIL_TO, "amazonses test mail", date("Y-m-d H:i:s"));

1 个答案:

答案 0 :(得分:0)

SES使用的带有HTTPS的签名版本3与其他AWS服务常见的V2或V4截然不同,因为您签署的事项是日期值

  

要创建要签名的字符串,请计算符合RFC 2104的HMAC哈希值,其中包含Date标头值,您的秘密访问密钥作为密钥,SHA256或SHA1作为哈希算法。

     

- http://docs.aws.amazon.com/ses/latest/DeveloperGuide/query-interface-authentication.html

另请注意,POST Content-Type: application/x-www-form-urlencoded中的所有键和值都需要实际为... urlencoded。我在你的代码中没有看到这个。它不会与错误相关,但可能会在以后引起其他问题。